Editor’s introduction
The study evaluates how varying the hierarchical context—such as function, class, and module levels—affects LLM-generated code documentation. It compares Documentation-Aware prompts with limited context to those enriched with higher-level structural information, using generated docstrings as a proxy for developer intent. Results show that class or module-level context consistently produces summaries closer to original documentation, with statistically significant improvements across models. Effect sizes vary: Gemini shows medium improvements, while GPT-4o-mini and DeepSeek show weaker effects. This suggests that structured, layered context supports better LLM reasoning in code comprehension tasks.
Introduction
During software evolution, developers spend over half their working time on program comprehension, yet few software projects adequately comment their code. In this context, source code documentation plays an important role in quality-related activities, including program comprehension, code review, and bug fixing. Furthermore, it has become of utmost relevance with the widespread adoption of generative artificial intelligence in the development process, where automated code generation needs to be verified and validated frequently, and likely reduces code ownership.
When such documentation exists, it is often mismatched with the source code, missing, or outdated. Code summarization aims to close this gap: given a method’s signature and body, Sridhara et al. define the task as generating natural language text that “summarizes the overall actions of [the method] accurately, adequately, and concisely,” producing descriptive comments that convey a method’s intent through its major algorithmic actions to aid program comprehension and software maintenance.
Current evaluations of LLM-based code summarization focus on whether models produce high-scoring summaries according to metrics such as BLEU, METEOR, ROUGE, and human or LLM-based judgment. They do not measure how the presence of existing documentation and varying levels of structural context influence whether the generated output approximates developer-written references, which remain the standard ground truth in code summarization evaluation.
Ahmed et al. augment prompts with semantic information at the function level but do not investigate broader hierarchical context. Makharev and Ivanov explore class and repository-level context but rely on retrieval-augmented generation and few-shot learning, which conflates the effects of intrinsic code structure with externally retrieved information, preventing attribution of gains to either source. Without controlled evidence on how hierarchical scope affects summary quality, tool designers face an uninformed trade-off: including too much context wastes inference budget, while including too little risks producing summaries that miss the neighboring methods, shared attributes, and module-level definitions the target function depends on. There is no empirical basis to guide this decision.
Context Augmentation For Code Summarization
The most directly related line of work investigates how additional context beyond the bare function body improves generated summaries. Ahmed et al. augmented LLM prompts with syntactic elements extracted via program analysis (tagged identifiers, data-flow graphs, and repository metadata) and reported significant metric improvements over baselines. Their augmentation targets lexical and structural representations at the function level, but they do not investigate the effect of supplying the enclosing class or module definitions, nor do they examine whether pre-existing documentation in the surrounding scope influences the generated summary.
Lomshakov et al. introduced ProConSuL, a framework that constructs project-level context for C/C++ code summarization by building a call graph and recursively summarizing callees. Their pipeline combines supervised fine-tuning with ORPO preference alignment and evaluates on 25 test functions. ProConSuL gathers context from other files via call-graph traversal, a program-analysis-based approach distinct from similarity-based retrieval. Their work does not examine the effect of intra-file hierarchical context or vary the presence of surrounding documentation.
Makharev and Ivanov examined code summarization beyond the function level, evaluating LLMs with class-level and repository-level context on Python benchmarks (1,200 functions). At the class level, they provide the enclosing class body directly to the model; at the repository level, they supply RAG-retrieved code chunks. Their results show that few-shot learning and RAG-retrieved context enhance LLM performance. At the class level, the input representation overlaps: both approaches supply the enclosing class code.
Two gaps remain. Makharev and Ivanov do not distinguish between settings in which the surrounding documentation (docstrings of neighboring methods, the class-level docstring) is present versus stripped. They also do not extend the hierarchy to module-level scope (the full file), and their function-level and repository-level experiments rely on few-shot prompting and RAG, respectively.
Prompting Strategies, Evaluation, And The Role Of Function Names
A second line of work asks how prompting techniques and evaluation methods, rather than input content, affect summary quality. Sun et al. conducted a systematic study of LLM-based code summarization, comparing five prompting techniques (zero-shot, few-shot, chain-of-thought, critique, and expert). They found that advanced prompting strategies do not consistently outperform simple zero-shot prompting, and that GPT-4-based evaluation aligns most closely with human judgment. Their study varies the prompting strategy while holding the input context constant at the function level. If zero-shot prompting already captures most gains from prompt engineering, the remaining lever for practitioners is the scope and composition of the input context itself.
Crupi et al. investigated the reliability of the LLM-as-a-Judge approach for code generation and summarization. When comparing judgments from multiple LLMs against human assessments, they found that GPT-4-turbo achieves moderate-to-substantial agreement with humans on summary content adequacy, whereas smaller models perform poorly as judges.
Haldar and Hockenmaier found that LLMs rely heavily on function names rather than on code structure when generating summaries, and that metrics such as BLEU and BERTScore provide largely redundant assessments. If models lean on function names as a shortcut, richer surrounding context may reduce that reliance, but no existing study tests this hypothesis directly.
Study Design
Following guidelines for empirical studies utilizing LLMs and empirical standards for data science experiments, we use an incomplete factorial design with five experimental conditions, controlled by two independent factors. The first factor, context granularity, controls the hierarchical scope of code visible to the model (Function, Class, or Module). The second factor, documentation mode, controls whether existing documentation in the surrounding scope is retained or removed. With this approach, context granularity determines how much code structure the model sees, while documentation mode determines whether the docstrings within that structure are preserved.
These conditions map directly to our research questions. RQ1 is addressed by comparing the Function-only baseline against Class and Module conditions, isolating the effect of hierarchical scope. RQ2 is addressed by comparing DI against DA at each context level, isolating the effect of surrounding documentation. RQ3 is addressed by conducting these comparisons separately for each of the three LLMs.
Experimental Procedure Setup
We employed low-cost and general-purpose API models from three different providers, including DeepSeek v3.2, which has open weights. The generation prompt does not enforce a specific docstring style, allowing each model to produce documentation in whatever format it deems appropriate for the function. The full generation prompt is in the replication package.
Two input conditions were prepared for each artifact: (1) with existing contextual documentation retained, but removing the target documentation, and (2) with all documentation removed. In both cases, the same source code context was supplied to the LLM, ensuring comparability across conditions. The experiment ran in a WSL2 environment on Windows using Python 3.11. Generation invoked the OpenAI, Gemini, and DeepSeek APIs, whereas the LLM-as-a-Judge evaluation used the Claude API from a model family different from those of the generators to avoid self-preference bias (Section 3.5). BERTScore was computed using an NVIDIA RTX 4090 24GB with the google/mt5-small model as the underlying encoder (this model is used solely for the BERTScore computation). No truncation was required, as the longest (prompt + context) input was 48,568 tokens, as counted by tiktoken using the cl100k_base encoding.
Evaluation
For each evaluation instance, the mapping between candidates and the labels A, B, C is determined by a random permutation, drawn once per function and context level to mitigate position bias. The judge is prompted to return a JSON object containing a ranked list such as [“B”,“A”,“C”] and a short rationale. We extract the ranking from the response and convert it to numerical ranks (1=best, 3=worst) for each candidate. The prompt enforces strict ordering with no ties. It instructs the judge to treat the function body as primary evidence and the surrounding context only as secondary support for disambiguating intent, penalizing claims not supported by the code (the full judge prompt is in the replication package).
We adopted three evaluation criteria from prior work on LLM-based code summarization assessment: content adequacy, conciseness, and fluency and understandability. Crupi et al. validated these criteria against human judgments for code summarization and code generation tasks, finding that GPT-4-based rankings under these criteria achieved high agreement with expert annotators. Sun et al. independently confirmed that GPT-4 evaluation aligned most closely with human assessment among several automated metrics they tested. Adequacy measures whether the comment captures what the function does, conciseness penalizes unnecessary detail, and fluency assesses whether a developer can read the comment without difficulty. Together, they cover complementary dimensions of comment quality.
Self-preference bias refers to the tendency of an LLM judge to systematically favor outputs produced by its own model family over outputs of comparable quality from other models. To mitigate this risk, we use claude-sonnet-4-6 as the judge, a model from a different provider and family than all three generators in our study. The judge was queried with a temperature of 0 to maximize reproducibility. We sampled 1000 instances for evaluation, stratified by reference docstring length into quartiles (250 instances per quartile) using a fixed random seed.
Human calibration of the judge. We calibrated the judge on a stratified sample of 20 tasks covering all six model and context-level instances, ranked blind by one author under the same criteria as the judge, with a second blinded author as an inter-rater baseline. The judge agreed with each author on the DA versus DI comparison underlying RQ2 in 65–70% of tasks (Cohen’s kappa 0.30–0.40) and matched the raters’ consensus choice in 11 of the 15 tasks on which they aligned (73%). Over the full rankings (60 rank assignments), the judge agreed with each rater (Krippendorff ordinal alpha 0.33 and 0.41) more than the raters agreed with each other (alpha 0.11), so the judge ranks candidate summaries at least as consistently as the raters themselves. This supports relying on the judge for the aggregate DA versus DI comparisons. The rating sheets are in the replication package.
LLM-as-a-Judge Analysis
For RQ3, all three models produce higher similarity scores with a broader context, but the magnitude varies substantially. Gemini shows the strongest response to hierarchical context, with medium effect sizes for Baseline vs. DA (r = 0.31–0.36). GPT-4o-mini produces mostly weak effects (r = 0.07–0.26), and DeepSeek produces mostly weak effects (r = 0.04–0.18). The judge evaluation confirms the DA preference for all three models (r = 0.08–0.16), and the models differ sharply in how their outputs fare against the reference: GPT-4o-mini and DeepSeek references win 42–53% of comparisons while Gemini references win under 10%. Model choice moderates both the size of the context benefit and the degree to which surrounding documentation contributes. The effect is model-dependent in magnitude, ranging from mostly weak (DeepSeek and GPT-4o-mini) to medium (Gemini).
The effects of DA extend to repositories with a lower representation in the sample (astropy, matplotlib, and sympy account for 69.2% of the rows). On BERTScore, the DA median exceeds the DI median in 12 of 12 repositories for GPT-4o-mini and DeepSeek, and in 11 of 12 for Gemini (only xarray reverses, by 0.0011). Macro-averaging the per-repository DA–DI differences, which weights each repository equally, preserves the advantage for all three models (BERTScore +0.011 for GPT-4o-mini, +0.064 for Gemini, +0.017 for DeepSeek). The macro-average over the nine non-dominant repositories alone remains positive (+0.010, +0.049, +0.017). The replication package contains DA and DI results per repository.
Implications For Research And Practice
The judge evaluation shows DA significantly preferred over DI for all three models, but with mostly weak effect sizes (r = 0.08–0.16), even for Gemini, whose metric effects are medium (r = 0.31–0.36). This gap between metric and judge effects calls for explanation. Copying does not provide one, since Gemini’s DA outputs show the lowest lexical overlap with the surrounding documentation of the three models (Jaccard 0.046 DA vs. 0.042 DI). A more consistent explanation is stylistic alignment. Gemini adopts the documentation conventions of the surrounding scope, which raises similarity to references written under those same conventions by more than it raises the informational quality the judge rewards. Output style points the same way. Gemini produces the shortest summaries (median 312 characters at baseline), leaving the most headroom to absorb reference-like phrasing from context, while DeepSeek’s verbose outputs (median 1,029) dilute overlap with any single source, consistent with its mostly weak effects.
We also observe a weak but consistent dependence on reference comment length. As references become longer, they are increasingly ranked first by the judge, so improvements from context augmentation are most visible when the existing reference is under-specified rather than already comprehensive. For practitioners and tool developers, prompts should include broader hierarchical context and can benefit from retaining nearby documentation. Adding context increases average prompt size from 277 tokens for the Function-only baseline to 4,506 for Class DA and 13,233 for Module DA.
Theoretical Validity
A related concern is that the DA advantage reflects summary length rather than context use. Length correlates negatively with every metric (Spearman rho between -0.10 and -0.34), so longer summaries do not score higher, and DA still exceeds DI within every length quartile. The most concise model, Gemini, also shows the largest effect, so the result is not due to any single length-sensitive measure.
Because the SWE-Bench snapshot predates every model’s knowledge cutoff, the entire sample may have been seen during pre-training. Our design controls for this. Each of the 6,932 functions appears in all five conditions, so memorized content contributes equally to every condition and cannot produce the condition differences our conclusions point to. Three observations argue against recall as the driver. Generated summaries are roughly six times longer than their references rather than reproductions of them. DA summaries are barely more lexically similar to the surrounding documentation than DI summaries. The DA advantage persists in the repositories least represented in our sample (Section 4.3). A direct test would contrast functions committed after the models’ knowledge cutoffs with pre-cutoff functions, which requires code newer than the pinned SWE-Bench snapshots. We leave it to future work.
Under DA, a model might paraphrase neighboring docstrings instead of reasoning over the code. On 400 sampled class-level targets per model, DA summaries are only marginally more similar to the surrounding documentation than DI summaries (Jaccard 0.065 vs. 0.058; DA higher in 59% of pairs), and the shared tokens are mostly generic API vocabulary, so the DA improvement does not come from copying the surrounding documentation.
All judge-based results are based on a single judge model. A judge outside the generators’ families avoids intra-family self-preference but has its own preferences. We mitigated this risk by running a blinded 20-task calibration (Section 3.5) which shows the judge agreeing with a human rater at the level the raters agree with each other, supporting the aggregate comparisons.
Conclusion
Generated docstrings in both Documentation-Independent (DI) and Documentation-Aware (DA) scenarios are longer than their references, and pooled BERTScore, BLEU, METEOR, and ROUGE values peak under class-level DA context. Kruskal–Wallis tests confirm that metric distributions differ across conditions for all three models, and Dunn–Bonferroni post-hoc tests show that most pairwise contrasts are statistically significant. The effect size varies by model, with Gemini showing medium effects for Baseline vs. DA (r = 0.31–0.36), GPT-4o-mini mostly weak effects (r = 0.07–0.26), and DeepSeek mostly weak effects (r = 0.04–0.18). The benefit of hierarchical context and surrounding documentation is consistent in direction but model-dependent in magnitude. Gemini produced summaries closest to the developer-written references, achieving the highest mean scores on all four metrics in every condition.
We triangulated our findings with a Claude Sonnet 4.6 LLM-as-a-Judge ranking on 1000 stratified samples per model using adequacy, conciseness, and fluency criteria. DA outputs are significantly preferred over DI for all three models, with mostly weak effect sizes. Longer developer-written references are more likely to be ranked first, suggesting that the headroom for LLM improvements depends on the completeness of the existing documentation.
Several directions remain for future work. The repositories used originate from SWE-bench and are publicly available, so the evaluated models may have encountered them during pre-training. Comparing performance on functions present in training corpora against those absent, for example functions committed after March 2025, the most recent knowledge cutoff among the evaluated models, would separate contextual reasoning from memorization. This requires sampling commits newer than the pinned SWE-Bench snapshots. Repeating the study with smaller open-weight models (7B and 13B parameters) would clarify whether context sensitivity generalizes across model sizes. Extending the hierarchy to repository-wide context would test whether the modest effect sizes observed at the module level grow when cross-module dependencies enter the prompt. Applying the study to languages beyond Python would test generalizability across different documentation conventions and structural norms.


