---
title: "Iterative Refinement of Project-Level Code Context for Precise"
description: "CoCoGen uses compiler diagnostics to find relevant code in a Python project and revise generated functions, improving their chances of…"
canonical: "https://research.elamur.ai/free/en/papers/bi-2024-iterative-refinement-project-level-code/"
---
Elamur: [Mova](https://md.mova.elamur.ai/free/en/) · [Parse](https://mova.elamur.ai/free/en/parse/) · [Dictionary](https://md.dictionary.elamur.ai/free/en/) · [Translate](https://md.translate.elamur.ai/free/en/) · **Research** · [Gali](https://md.gali.elamur.ai/free/en/) · [MCP](https://mcp.elamur.ai/) · [Locations](https://md.locations.elamur.ai/free/en/) · [Weather](https://md.weather.elamur.ai/free/en/) · [Constitution](https://md.constitution.elamur.ai/)

[Elamur Research](https://md.research.elamur.ai/free/en/) · [this page in HTML](https://research.elamur.ai/free/en/papers/bi-2024-iterative-refinement-project-level-code/)

[Elamur Research](https://md.research.elamur.ai/free/en/) / [papers](https://md.research.elamur.ai/free/en/papers/) / [2024](https://md.research.elamur.ai/free/en/papers/2024/) / Iterative Refinement of Project-Level Code Context for Precise Code Generation with Compiler Feedback

# Iterative Refinement of Project-Level Code Context for Precise Code Generation with Compiler Feedback

Paper · 2024 · Zhangqian Bi, Yao Wan, Zheng Wang et al.

**Authors:** Zhangqian Bi, [Yao Wan](https://md.research.elamur.ai/free/en/authors/yao-wan/), [Zheng Wang](https://md.research.elamur.ai/free/en/authors/zheng-wang/), [Hongyu Zhang](https://md.research.elamur.ai/free/en/authors/hongyu-zhang/), Batu Guan, Fangxin Lu, [Zili Zhang](https://md.research.elamur.ai/free/en/authors/zili-zhang/), [Yulei Sui](https://md.research.elamur.ai/free/en/authors/yulei-sui/), [Hai Jin](https://md.research.elamur.ai/free/en/authors/hai-jin/) and [Xuanhua Shi](https://md.research.elamur.ai/free/en/authors/xuanhua-shi/) · **Year:** 2024 · **Venue:** Findings of the Association for Computational Linguistics: ACL 2024 · **Licence:** [CC BY 4.0 (ACL Anthology)](https://creativecommons.org/licenses/by/4.0/)

Findings of the Association for Computational Linguistics: ACL 2024 · [licence](https://creativecommons.org/licenses/by/4.0/)

- [Publisher's page](https://aclanthology.org/2024.findings-acl.138/)
- [PDF](https://aclanthology.org/2024.findings-acl.138.pdf)
- [DOI 10.18653/v1/2024.findings-acl.138](https://doi.org/10.18653/v1/2024.findings-acl.138)

## Summary

A generated function can follow the user's instructions and still call an API that the project has never defined. The authors illustrate this with an image enhancement task. The generated function attempts to remove noise before adjusting the image, as requested, but calls `reduce_noise`. The repository already implements the relevant operation as `denoising.denoise`. Discovering that implementation requires information beyond the function being written. Including the entire repository in the prompt is impractical when the project exceeds the amount of text the generator can process at once.

CoCoGen uses the failure of a first attempt to decide which parts of the repository to inspect. It indexes the project before generation, recording both the structure of the source code and searchable representations of its contents. It starts with a search based on the task description. After generating a candidate, it checks the candidate in its project setting with Pylint, a Python static analyzer. A diagnostic about a missing name or a mismatched argument gives the system a more specific search target. CoCoGen can look up declarations in a named module or class, search for similar code, and give the generator the resulting context alongside the diagnostic. It repeats the check and revision as needed.

On CoderEval-Python, the authors compare CoCoGen with direct generation and with retrieval methods that operate without compiler diagnostics. They evaluate GPT-3.5-Turbo and Code Llama (13B) using unit tests. On the project-runnable split, where solutions rely on code in other source files, GPT-3.5-Turbo reaches a Pass@10 of 39.13 with CoCoGen, compared with 13.04 for direct generation and 21.74 for RepoCoder. Pass@10 estimates how frequently a task has a fully passing solution among that many attempts. CoCoGen improves this measure across the three project-dependent splits for both generators. The Pass@1 comparisons are mixed, and the project-runnable split for Code Llama (13B) is one setting where RepoCoder produces a stronger result on that measure.

The experiments distinguish fitting into the repository from implementing the intended behavior. Diagnostics can point to a missing declaration, and the indexed source can supply a usable alternative. A candidate can also use available declarations and pass static analysis while assembling a return value in the wrong order. CoCoGen uses static findings to drive revision and unit tests to measure the resulting programs. The tests establish whether the repairs help on the benchmark, while the static check determines when the system has exhausted the kind of feedback it uses.

## Deep dive: Iterative Refinement of Project-Level Code Context for Precise Code Generation with Compiler Feedback

CoCoGen uses compiler diagnostics to find relevant code in a Python project and revise generated functions, improving their chances of passing tests. · about 34 minutes to read

**In this deep dive**

1. [The problem and its context](#dd-the-problem-and-its-context)
2. [The method, step by step](#dd-the-method-step-by-step)
3. [Experiments and results](#dd-experiments-and-results)
4. [What the ablations show](#dd-what-the-ablations-show)
5. [Limitations](#dd-limitations)
6. [What came after](#dd-what-came-after)

### The problem and its context

#### A function inherits requirements from its surroundings

A task description typically tells a programmer what a new function should do. The surrounding repository supplies another layer of requirements. A class may already provide part of the operation. A helper may expect a named argument, or a module may expose a particular type with a name close to another type elsewhere in the project. A generated implementation has to satisfy these local requirements even when the user has given an adequate account of the desired behavior.

The image enhancement example separates these sources of information. The request gives the order of operations, and the first candidate follows it. The project determines the name and location of the denoising routine. From the wording of the request alone, `reduce_noise` is a plausible name. Its plausibility contributes little when the function is inserted into a repository that exposes `denoising.denoise`. A prompt that includes the real declaration can change the answer without changing the task description.

The same issue comes up at several distances from the point of insertion. A definition may be available in the current class, elsewhere in the current file, or behind an import from another file. These cases all require knowledge of the project, even though their search spaces differ. Looking for a member of a known class is a bounded problem. Finding a helper whose name and location are both unknown can require searching much more of the repository. Modular organization lets a project distribute its responsibilities, so the text nearest the insertion point gives an incomplete view of the available implementation.

The amount of text that can be considered at once imposes a practical constraint. The generator sees a finite context window, which is the span of tokens available to it when it makes a prediction. A token is a unit produced by dividing the input into pieces for processing. Task instructions, surrounding code and imported examples all occupy space in that window. The authors therefore treat repository context as something to obtain in portions. A retrieval system must decide which definitions or examples deserve that space before each generation attempt. [Tokenization & segmentation](https://md.research.elamur.ai/free/en/topics/tokenization/)

That decision can be difficult before the system has proposed any code. A task description may identify the desired operation while leaving the implementation vocabulary implicit. Once a draft exists, it exposes assumptions about where an operation belongs, what it is called and how it should be invoked. Some assumptions can be checked against the source. If the draft imports a name from a particular module and the analyzer cannot find it there, the search can start with the module and its declarations. The failed draft has turned a broad request about behavior into a question about a specific part of the repository.

#### How earlier work brought the project into view

The paper situates repository-aware generation within a longer history of automated programming. It describes early work based on rules and structured prediction, including research that mapped language to a representation a system could use. More recent code generators learn from code and natural language and can be prompted with either a description or an incomplete program. That flexibility lets the same basic generator handle different programming tasks, while leaving open the question of how to supply facts about a particular project. [Learning to Parse Database Queries Using Inductive Logic Programming](https://md.research.elamur.ai/free/en/papers/zelle-1996-learning-parse-database-queries-using/) · [Evaluating Large Language Models Trained on Code](https://md.research.elamur.ai/free/en/papers/chen-2021-evaluating-large-language-models-trained/)

Earlier approaches to locality in code used caches to track information about the current project. The paper also describes a relational representation of repositories that supports traversal of the relationships stored in a project database. These approaches make project information accessible in different ways. A cache makes locally relevant material available to a predictor. A relational representation makes it possible to follow links among entities, such as the connection between a declaration and the scope that contains it.

Another line of work brought private API documentation into the prompt. This makes a difference to the kind of information the generator receives. Documentation can state the intended use of an operation, while source code exposes details such as its containing module and formal arguments. The paper describes investigations into which parts of API documentation help prediction and a system that uses a classifier to choose among repository-level prompt candidates. Both approaches address the need to select context before spending prompt space on it.

Retrieval-based code completion makes a repository searchable at generation time. ReACC supplies source material that resembles a query. RepoCoder alternates retrieval and generation, using an earlier generated completion to help search for context for a later attempt. This gives a draft a second role beyond being a possible solution. It becomes a richer description of the implementation the system is trying to produce. The CoCoGen experiments adapt these retrieval ideas to their generation task, where the output is an implementation assessed by tests. [ReACC](https://md.research.elamur.ai/free/en/papers/lu-2022-reacc-retrieval-augmented-code-completion/) · [RepoCoder](https://md.research.elamur.ai/free/en/papers/zhang-2023-repocoder-repository-level-code-completion/)

The paper also reviews work that checks, ranks or edits generated programs. A fault-aware ranker uses compilation feedback to order candidate samples. Other systems use execution outcomes as a filter, or use them to inform an edit. The self-debugging work discussed by the authors includes explaining a program in natural language and examining what happens when it runs. These approaches share the premise that a generated program can supply evidence for a subsequent decision. They give that evidence different jobs, including selecting a candidate and formulating a revision. [Fault-Aware Neural Code Rankers](https://md.research.elamur.ai/free/en/papers/inala-2022-fault-aware-neural-code-rankers/) · [AlphaCode](https://md.research.elamur.ai/free/en/papers/li-2022-competition-level-code-generation-alphacode/) · [Teaching Large Language Models to Self-Debug](https://md.research.elamur.ai/free/en/papers/chen-2023-teaching-large-language-models-self/)

CoCoGen assigns static feedback a job in retrieval itself. The project supplies an index of what exists. The draft reveals what the generator tried to use. The diagnostic can identify a particular mismatch between the two. Combining these inputs gives the retrieval step a concrete reason to inspect one module, declaration or call site before the next attempt.

The paper uses benchmarks with different scopes because a task confined to a single function asks a different question from a task that requires definitions elsewhere in a project. ClassEval studies generation in a class setting. CoderEval distinguishes tasks by the dependencies their solutions need. CrossCodeEval focuses on cross-file context for completion. A repository-level evaluation makes the consequences of context selection observable because a generated fragment must fit into existing source and, for the central generation task, exhibit the required behavior under tests. [Evaluation & benchmarks](https://md.research.elamur.ai/free/en/topics/evaluation-benchmarks/)

### The method, step by step

#### Prepare the repository for lookup

CoCoGen has an offline preparation stage and a generation stage. Preparation turns source files into entries that can be found by their role in the project or by the similarity of their content to a query. Generation uses those entries to support a draft, inspects the draft for static errors, and lets the errors shape the next search.

CoCoGen from repository indexing to candidate revision The steps in order.

The index starts with the project's `.py` files. CoCoGen parses each of them into an abstract syntax tree, or AST. A tree of this kind represents the arrangement of constructs such as class definitions, function definitions and statements. The preparation step identifies nodes for classes, functions and variables and records their nesting. It can then associate a method with the class that defines it and a declaration with the file or module in which it occurs. The implementation uses tree-sitter-python for parsing and codeql-python to extract properties of the entries. [Parsing](https://md.research.elamur.ai/free/en/concepts/parsing/)

The construction algorithm traverses each tree while maintaining a record of the enclosing declarations. When it reaches a node of interest, it saves the enclosing path, the node and its extracted properties. While it visits children, the current declaration is part of that path. When it leaves the scope, the path is restored. This matters when several parts of a project use the same short name. A stored name can be accompanied by the scope that gives it meaning.

The paper illustrates the index with `get_handler`, a method associated with `AsyncBolt`. The method can be identified by a qualified name that includes the class, or discovered by matching the meaning of its docstring to a request about Bolt protocol handlers. A docstring is a description kept in the source alongside a declaration. The same entry can therefore answer a question about where the method is defined and serve as a candidate result for a more open-ended search about what it does.

CoCoGen also prepares relational tables from the project representation. These cover modules and their hierarchy, classes within modules, member functions and class variables, and global functions and variables. The rows preserve relationships needed for lookups. A search for a global function can return the containing module, while a search for class members can use both the class and its parent module to narrow the candidates. Precomputing these relations lets some common diagnostics use fixed retrieval procedures.

The other searchable representation is an embedding, a vector of numbers computed from the entry's contents. CoCoGen records this vector alongside the structured entry. Vector search serves queries whose wording may give a good description of a feature without using the exact name assigned to it in the repository. The implementation uses `text-embedding-ada-002`, with an embedding dimension of 1,536. The setup retrieves at most 5 entries per query. [Information retrieval & search](https://md.research.elamur.ai/free/en/topics/information-retrieval/)

#### Retrieve context for the first draft

At the start of generation there is no diagnostic yet. CoCoGen uses the task description as its semantic search query and gives the generator retrieved source material alongside the request and partial function. In the paper's illustration, the initial search can find a comparable routine in synchronous code while the task needs an implementation for an asynchronous setting. Such a routine may still show the intended procedure. The names or classes it uses need to be checked against their destination before the same pattern can be applied there.

The authors implement semantic search using the approach described in [Dense Passage Retrieval](https://md.research.elamur.ai/free/en/papers/karpukhin-2020-dense-passage-retrieval-open-domain/). The query is encoded by a pretrained network based on the [Transformer and attention](https://md.research.elamur.ai/free/en/concepts/transformer/) architecture. Its relationship to the vector for a stored context entry is written as follows.

```
h_q = ENCODER(q)
```

Here `q` is the text of the search request, `ENCODER` is the network that maps that text into a numerical vector, and `h_q` is the resulting query embedding. The symbol `=` gives the value assigned to the query representation. For the first search, the text describes the requested implementation. For a later search, the diagnostic and affected line give the query a different focus.

```
sim(h_q, h_c) = (h_qᵀ h_c) / (‖h_q‖ · ‖h_c‖)
```

In this expression, `sim` is the cosine similarity function, `h_q` is the query embedding and `h_c` is the embedding of a stored context entry. The superscript `ᵀ` denotes a transpose, so `h_qᵀ h_c` is the dot product of the vectors. The double bars give each vector's norm, or length. The centered dot multiplies those lengths, and the slash divides the dot product by their product. This compares the directions of the representations, allowing the system to order entries by similarity and retrieve the highest-ranked ones.

A high similarity score reflects a relationship in the encoded content. It can bring back a nearby example of how to do the work, even when that example uses a different class. Whether the class is legal at the new call site is a separate question for the analyzer and the structural index. This is how the paper's two search mechanisms can make different contributions to the same revision. [Retrieval-augmented generation](https://md.research.elamur.ai/free/en/concepts/retrieval-augmented-generation/)

#### What generation is conditioned on

The paper describes the underlying generation process as sequential prediction. A prompt is broken into tokens, and the probability of a complete candidate is built up from the probabilities of its successive tokens. Using the paper's description of a prediction conditioned on preceding tokens, the sequence expression is:

```
p(y ∣ x) = ∏_{t = |x| + 1}^{|x| + |y|} p_LM(x_t ∣ x_{1:t−1})
```

Here `x` is the input sequence and `y` is the output program. The bars in `|x|` and `|y|` count tokens. The symbol `t` indexes the combined sequence, and `x_t` is the token at that position. The subscript range `1:t−1` denotes the prefix through the position immediately before `t`. The vertical conditioning bar means “given.” The function `p_LM` supplies the next-token probability, `p(y ∣ x)` is the conditional probability of the whole candidate, and `∏` multiplies the factors from the first output position through the last. The paper's printed product ends the conditioning subscript at `t`, although its preceding explanation defines next-token prediction using the prefix through `t−1`. The expression above follows that preceding-token convention.

The authors also give a formulation in which the prompt carries examples of the desired task. This describes how the query generator can be shown pairs of diagnostic messages and structural queries, and how a prompt can illustrate the desired form of an answer.

```
p_LM(y ∣ x) = p(y ∣ x, {⟨x_i, y_i⟩}_{i ≤ m})
```

Here `p_LM(y ∣ x)` denotes the conditional generation procedure. On the right, `p` conditions the output program `y` on the current input `x` and the collection enclosed in braces. Each pair `⟨x_i, y_i⟩` contains an example input and its corresponding output, `i` indexes the examples, and `m` is the number supplied. The bound `i ≤ m` runs through that collection. The additional conditioning takes place through examples in the prompt, a form of [few-shot learning](https://md.research.elamur.ai/free/en/concepts/few-shot-learning/).

The paper describes the practical window for prediction with the preceding-token slice:

```
x_{max(1, t−w):t−1}
```

Here `x` is the token sequence, `t` is the position being predicted, and `w` is the window length. The colon marks the start and end of the slice. The function `max` chooses the later of position `1` and `t−w`, so the slice starts within the sequence. Its final position is `t−1`. This bound explains why CoCoGen supplies a selection of repository entries during each generation attempt.

The implementation works through access to generated outputs. The paper uses GPT-3.5-Turbo through an online API and the base variant of Code Llama (13B) as its other generator. The stated inference settings are a decoding temperature of 0.7 and top-k sampling, which samples from a group of the highest-scoring next-token candidates. This sampling use of `k` belongs to decoding. The `k` in Pass@k, used later for evaluation, counts complete candidate programs. CoCoGen changes what goes into the generation prompt, so the refinement procedure can be applied to the two generators without training them on the target project. [Code Llama](https://md.research.elamur.ai/free/en/papers/roziere-2024-code-llama-open-foundation-models/)

#### Analyze the draft in its project setting

The term “compiler feedback” refers to the error signal used to drive refinement. For these Python experiments it comes from Pylint. Pylint examines source statically, meaning that it inspects the program without running the generated function. CoCoGen gives it the file containing the candidate along with associated files, then retains errors attributed to lines in the generated solution. The file and its dependencies give the checker a way to interpret references whose definitions occur outside the candidate itself.

Pylint can also issue warnings, recommendations about conventions and refactoring suggestions. The pipeline uses the errors. Each such report includes a code identifying the kind of error and a message describing the instance. When the report concerns a call, for example, the message and source line can together reveal which function was called and how its arguments were supplied. A report about an unresolved import instead gives the search a module and the name that was sought there.

The authors group these findings by the kind of incompatibility they signal. UNDEF covers undefined names, including a missing member, module entity or variable. API covers incorrect invocation, such as an omitted required argument. OBJECT covers operations that an object does not support, such as indexing a value treated as a function. OTHER includes additional syntax or semantic errors reported by the checker. The error study also records FUNC for failures found during testing or execution. Those failures have a different source of evidence and the refinement loop uses the static categories.

Filtering diagnostics to the candidate's lines matters in an existing project. A check run over a file with dependencies can produce findings associated with other code. CoCoGen uses locations to link the diagnostic to a place it has just generated. The resulting information identifies both the visible symptom and the local expression on which the next generation attempt can act.

#### Turn a diagnostic into project context

The structural branch maps a diagnostic to a question about declarations and relationships. The paper calls this branch SQL retrieval and implements its repository queries with CodeQL. For often encountered diagnostic codes, the authors use pre-defined retrieval procedures and precomputed tables. The appendix describes such procedures for errors involving undefined variables and missing members, among others. A fixed procedure can directly use a diagnostic's scope or named entity to query the appropriate table.

For other errors, CoCoGen asks a generator to produce a structural query. The prompt associates example diagnostics and affected lines with manually written queries. These demonstrations show how to express a lookup over source entities, such as requesting the declarations belonging to a named module or finding a function by name. The generated query then runs against the project representation. The output is source context that can be passed back to the code generator.

For instance, the paper shows a failed lookup for `SyncBolt3` in `async._bolt3`. A structural query can request classes belonging to that module. In the example this brings back source involving `AsyncBolt3`. The use of the module as a constraint is important. A repository may contain plausible implementations for synchronous and asynchronous variants. A query about which classes the indicated module contains supplies evidence specific to the failing reference.

The demonstrations cover different scopes. For a missing class member, a query can enumerate members of the identified class. For a missing imported name, it can inspect definitions at the relevant module scope. For a call with a missing argument, it can return the declaration of the named function. In the last case the diagnostic tells the generator what is missing, while the declaration supplies the surrounding signature and any source context the retriever returns. Both pieces can matter when writing the call correctly.

In parallel with that kind of lookup, the semantic branch can encode the diagnostic and the affected line and retrieve entries close to them in meaning. It can surface related implementation examples whose names differ from the faulty name. The two branches therefore use the same incident in different ways. A structural lookup exploits information such as membership in a module, and a similarity search can retrieve a useful pattern that lies outside that scope.

The next generation prompt combines the requirement, the previous attempt, the reported error and the relevant context available to the system. The generator has to revise the implementation in light of those inputs. It might replace a reference, change a call or reorganize a fragment of the function. CoCoGen then submits the revision for another static check. Checking the new candidate is necessary because the first visible problem may conceal a subsequent one, or a changed line may itself introduce an error.

The methodological stopping condition is an absence of reported static errors, and the experiments also examine explicit iteration budgets. Unit-test outcomes are collected for evaluation. They are separate from the feedback supplied during this loop. The authors make the implementation and data available with the CoCoGen example in the `naturalcc` repository.

### Experiments and results

#### The main benchmark and the comparisons

CoderEval-Python supplies 230 test samples divided by the external context their solutions require. The self-contained category uses built-ins. The slib-runnable category brings in standard library modules. The plib-runnable category depends on publicly available libraries. These categories distinguish dependency on built-in or external facilities from dependency on the particular repository in which the function belongs.

The main evaluation concentrates on the remaining categories. Class-runnable tasks need code elsewhere in the same class and include 55 tasks. File-runnable tasks rely on code outside the class within the same file and include 68 tasks. Project-runnable tasks depend on other source files and include 23 tasks. Each split asks whether candidates manage a different boundary between the function and the rest of the repository. Project-runnable is the specific name of the cross-file split, even though the main experiments treat all these splits as involving project-specific context.

The authors run CoCoGen and the generation comparisons with GPT-3.5-Turbo and Code Llama (13B). Direct generation supplies the task requirements and no retrieved repository material. The ReACC adaptation retrieves context by semantic similarity to the instructions. RepoCoder retrieves again using previous generations as search material and revises with the results. This makes RepoCoder a comparison for iteration driven by the generated code itself, while CoCoGen uses errors from the static checker to determine which information to retrieve during a revision.

The choice of baseline depends on what one wants to learn. Direct generation measures what the task input alone supports in this setup. ReACC tests whether a search based on the request can provide useful context before any particular error has been identified. RepoCoder tests what can be gained from retrieving again once an initial implementation exists. The component comparisons later vary the feedback and search channels within the refinement setup.

#### Measuring correctness over sampled candidates

The main generation score uses unit tests. A candidate counts as correct when it passes every test for its task. Pass@k asks how often there would be a passing candidate among `k` attempts. To estimate that measure, the main setup states that it generates 20 solutions per task and reports Pass@1, Pass@5 and Pass@10. It uses the number of fully passing candidates in each pool rather than discarding all but a single randomly selected group of attempts.

```
Pass@k = E[1 − C(n−c, k) / C(n, k)]
```

Here `k` is the size of the selection of candidate programs, `n` is the size of the generated pool for a task, and `c` is the number in that pool that pass every test. `C(a, b)` is the binomial coefficient, which counts ways of selecting `b` items from `a` without regard to order. The numerator counts selections consisting entirely of failures, and the denominator counts all selections of the stated size. The slash forms the fraction of selections that fail in this sense. The `1 −` operation takes its complement, and `E` averages the per-task result over the evaluation tasks. `Pass@k` is the resulting estimate.

A higher Pass@10 indicates a better chance of having a test-passing program in a group of attempts. The group may contain candidates that fail in different ways, and the evaluation can recognize the one that passes by executing the benchmark tests. CoCoGen's refinement checker has a narrower role. Whether it can identify an error is distinct from whether the benchmark can score the resulting behavior. Similarly, Pass@1 measures success for a single sampled candidate, so improvement in Pass@10 alone leaves open how reliably a user is served by the first answer.

#### Where better repository context changes the outcome

With GPT-3.5-Turbo on the CoderEval-Python project-runnable tasks, CoCoGen achieves Pass@10 of 39.13. Direct generation scores 13.04, and both retrieval baselines score 21.74. The spread among the methods is visible even though the metric already gives each method several opportunities to find a correct implementation. CoCoGen's result shows that the combined search and repair procedure can put test-passing programs into the sample pool on tasks that require definitions from other files.

CoderEval-Python project-runnable Pass@10 with GPT-3.5-Turbo Diagnostics-guided refinement leads the comparison on tasks requiring source from other project files.

**The numbers**

| System or setting | Pass@10 % |
| --- | --- |
| Direct generation | 13.04 |
| ReACC | 21.74 |
| RepoCoder | 21.74 |
| CoCoGen (this paper) | 39.13 |

The same GPT-3.5-Turbo comparison on project-runnable tasks favors CoCoGen at the lower budgets as well. Its Pass@1 is 21.30, and RepoCoder's is 16.96. At Pass@5, CoCoGen reaches 36.73 and RepoCoder 19.57. The fact that CoCoGen leads on each of these measures is specific to this generator and split. The rest of the table shows why accounts of the overall improvement need to distinguish both dimensions.

On the file-runnable split with GPT-3.5-Turbo, CoCoGen scores 30.29 at Pass@1, 43.58 at Pass@5 and 47.06 at Pass@10. RepoCoder records 29.41, 34.61 and 36.76 on the corresponding metrics. The narrower scope still leaves enough project dependence for refinement to help. File-local declarations can be outside the immediate completion context, and a call can use the wrong argument form even when the called function is defined in the same file.

The class-runnable split gives a different pattern for GPT-3.5-Turbo. RepoCoder reaches 35.45 at Pass@1, above CoCoGen's 28.00. At Pass@5, CoCoGen reaches 44.92 and RepoCoder 40.46. At Pass@10 the scores are 49.09 for CoCoGen and 41.82 for RepoCoder. This is an instance where CoCoGen has the stronger result when there are several attempts, while RepoCoder has the stronger result on a single sampled program. The table establishes that reversal without identifying the candidate-level mechanism behind it.

The Code Llama (13B) comparisons also depend on the attempt budget. On the class-runnable split, CoCoGen reaches Pass@1 of 26.36 and Pass@10 of 41.82. The corresponding direct results are 18.91 and 34.55. On the file-runnable split, direct generation reaches 18.53 at Pass@1 and CoCoGen records 17.06. At Pass@10, CoCoGen has 33.82, the same value as ReACC, with direct generation at 29.41 and RepoCoder at 32.35. The file-runnable tie matters to the claim about retrieval baselines. CoCoGen's advantage holds in many settings and the strongest scores can also be shared.

On the Code Llama (13B) project-runnable split, CoCoGen is behind RepoCoder at Pass@1, with values of 13.04 and 16.09, respectively. Its Pass@5 is 28.04, compared with RepoCoder's 21.36. At Pass@10 CoCoGen reaches 34.78, ahead of 21.74 for each retrieval baseline and 13.04 for direct generation. The gains at the larger sample budget therefore show up with both generators on cross-file tasks, alongside a difference in which system leads when evaluated on a single candidate.

The authors characterize their overall improvement over unaugmented generation for project-dependent functions as over 80% in relative pass rates. That description refers to improvement relative to the baseline; the split scores show the scale of the underlying rates and the conditions under which they were measured. The relative claim is compatible with project-runnable Pass@10 remaining a difficult benchmark outcome for both generators.

#### Why the authors looked at static errors

The paper's preliminary error study uses a separate evaluation protocol to ask which failures are associated with project context. It reports 85 function-level tasks and 145 project-level tasks. For each task the authors generate 10 candidates, yielding 850 function-level solutions and 1450 project-level solutions. The project-level setup retrieves the five fragments with the highest similarity for the prompt. The study reports a Pass@10 of 53.57% for the function-level comparison and 39.73% for the project-level comparison. These figures describe the preliminary study, whose task grouping and sampling procedure should be read on their own terms.

The authors analyze solutions that fail the tests. For the distribution they assign each candidate an error category, using the most common error type when the compiler reports multiple types for the candidate. In the function-level setting, runtime or functional failures account for 72% of the categorized errors. The corresponding share at project level is 34%. Undefined symbols and API errors are reported together at 21% for function-level generation and 64% for project-level generation.

The comparison identifies the kinds of errors that motivate CoCoGen's design. If a name is absent from a module, the available declarations can be looked up. If an API invocation is rejected for an argument mismatch, the signature or a valid use from the project can help with repair. A wrong calculation that runs successfully calls for evidence about the intended result. The preliminary percentages give the relative frequency of the classified failures under the paper's procedure, and the analysis groups candidates with several reported defects under a representative category.

The paper estimates that compilation errors account for 66% of errors in the project-level generation context it discusses. The static repair target consequently covers a substantial part of its observed failures. The outcome measures still depend on behavior under tests. A method could remove many diagnostic messages and leave its test results nearly unchanged if the remaining defects were in the logic. Conversely, a good replacement declaration can help both measures when an incorrect reference was the obstacle to running otherwise suitable code.

#### Completion and self-contained functions

The authors also evaluate cross-file completion and function-level generation. A completion task asks the system to predict missing source in an existing context. The CrossCodeEval Python data described in the paper cover 471 repositories, with 2,665 test cases across 1,368 files. For this experiment, the authors examine how closely completions match the reference at the code and identifier levels. Identifier measures focus on names in the completion, a useful distinction when a goal is to recover the particular project entities that the reference uses.

Code exact match, C-EM, requires the full predicted code to match the reference. The appendix describes exact match as scoring 1 for identical text and 0 for a difference. Code edit similarity, C-ES, assesses resemblance using the edits needed to transform one string into another. Identifier exact match is I-EM. Identifier F1, I-F1, measures how well the prediction recovers reference identifiers while also accounting for the identifiers it adds.

The appendix gives the following edit-distance recurrence behind its account of code edit similarity.

```
lev(a, b) =
  |a|                                            if |b| = 0
  |b|                                            if |a| = 0
  lev(tail(a), tail(b))                           if head(a) = head(b)
  1 + min(lev(tail(a), b),
          lev(a, tail(b)),
          lev(tail(a), tail(b)))                 otherwise
```

Here `lev` is the Levenshtein distance, and `a` and `b` are strings. The bars indicate string length, and `0` is the length of an empty string. `head` returns the first character, and `tail` returns the string that follows it. If the first characters agree, the recurrence continues with both tails. Otherwise `min` picks the least costly of deleting, inserting or substituting a character, and the `1 +` accounts for that edit. The equality tests select the applicable branch. The recurrence describes the distance underlying the reported similarity metric.

```
F1 = 2 / (recall⁻¹ + precision⁻¹)
```

Here `F1` denotes the harmonic mean of `recall` and `precision`, and an exponent of `−1` means the reciprocal. The denominator adds the reciprocals, and the numerator is the harmonic mean's factor `2`. In this evaluation, precision is the proportion of predicted identifiers shared with the reference. Recall is the proportion of reference identifiers recovered in the prediction.

For CrossCodeEval with GPT-3.5-Turbo, CoCoGen records C-EM of 9.08 and C-ES of 55.31. RepoCoder records 8.52 and 55.05. On the identifier measures, CoCoGen has I-EM of 14.11 and I-F1 of 42.34, compared with 13.02 and 41.05 for RepoCoder. Learning from the static feedback improves the reported completion scores over that baseline, with a smaller separation than on the central cross-file function generation comparison. The completion scores evaluate correspondence to expected source and identifiers. They answer a different question from the CoderEval unit-test results.

The function-level experiments use HumanEval and MBPP. In this setting the authors retain the compiler-feedback part of the method and describe generation without demonstration examples. They report sampling 10 candidates per evaluated task and refining for 3 iterations. The HumanEval results give a direct Pass@10 of 83.15 and a Pass@10 of 85.36 at the final feedback iteration. Its compilation error count falls from 40 to 3 over those settings. MBPP goes from Pass@10 of 60.81 with direct generation to 62.09 at the final iteration, while the error count goes from 185 to 7. These comparisons give the paper a view of static feedback in tasks with fewer reasons to search a project for private definitions. [Program Synthesis with Large Language Models](https://md.research.elamur.ai/free/en/papers/austin-2021-program-synthesis-large-language-models/)

### What the ablations show

#### A diagnostic can help on its own

The authors adapt direct generation, ReACC and RepoCoder to receive compiler feedback, then compare each with its counterpart across the entire CoderEval-Python split structure using GPT-3.5-Turbo. The direct baseline moves from Pass@1 of 20.65 to 32.34 with feedback. Its Pass@10 moves from 29.13 to 40.43. A diagnostic can therefore help in a procedure that started with the task description alone. It may reveal a concrete defect, such as an invalid call, that the generator can fix with the information already present.

Adding feedback to ReACC takes Pass@10 from 43.48 to 46.52. For RepoCoder it takes that measure from 42.17 to 48.26. The RepoCoder Pass@1 comparison goes from 36.82 to 38.00. These results apply to retrieval procedures that already provide source context. They show that the feedback contributes information even when a generation prompt has been expanded with examples from the repository. The whole-benchmark scope includes categories beyond the project-dependent splits used for the main cross-file comparisons.

The sizes of the effects vary by baseline and sample budget. The diagnostic can reveal what the generator should revise, while existing context determines how much of the answer is already available. For a malformed expression, the message may be enough to identify a local repair. For a missing project class, knowing that a name is wrong still leaves a search problem. The component ablation is designed to examine this latter situation by controlling which sources the generator can use to answer the diagnostic.

#### Retrieval channels make different contributions

In the main component ablation, the paper reports GPT-3.5-Turbo results for the full method and variants without particular inputs. The configuration without compiler feedback or structural lookup corresponds to RepoCoder, with semantic retrieval retained. The other configurations receive compiler feedback and vary whether they can perform structural lookup, semantic search, both or neither.

CoderEval-Python component ablation Pass@10 with GPT-3.5-Turbo With compiler feedback available, the two retrieval channels together give the highest score.

**The numbers**

| System or setting | Pass@10 % |
| --- | --- |
| RepoCoder | 36.30 |
| Compiler feedback only | 41.78 |
| Compiler feedback and structural retrieval | 41.78 |
| Compiler feedback and semantic retrieval | 44.45 |
| CoCoGen (this paper) | 46.58 |

The feedback-only and feedback-plus-structural versions both have Pass@10 of 41.78 in this comparison. Their Pass@5 values are 37.50 and 38.31, respectively. The semantic branch with feedback reaches Pass@5 of 40.02 and Pass@10 of 44.45. The full approach is highest at those two budgets, with Pass@5 of 43.01 and Pass@10 of 46.58. These results support using both search channels alongside the diagnostic at the larger budgets. They also show that adding structural search in the absence of the semantic branch can have a different effect from adding it when semantic results are already available.

On Pass@1, RepoCoder's 28.72 exceeds the full method's 28.01 in the aggregate component comparison. Within the feedback variants, Pass@1 is 25.69 for feedback alone, 26.37 with structural search, and 27.39 with semantic search. The full configuration leads those feedback variants at that budget. The aggregate comparison is consistent with the main results showing that stronger retrieval and repair need not lead every single-candidate comparison, even when they improve the chances of finding a passing candidate in a larger group.

The split-level ablations give more detail. On class-runnable tasks, both the full method and the version with feedback and structural search reach Pass@10 of 49.09. The version with feedback and semantic search reaches 47.27. On project-runnable tasks, feedback and structural search reach Pass@10 of 30.43, feedback and semantic search reach 34.78, and the full version reaches 39.13. These are GPT-3.5-Turbo comparisons. They show that the contribution of a search branch depends on the task's dependency boundary and on which other sources of context are present.

An aggregate equality can hide differences among individual tasks. The paper's equal Pass@10 scores for two configurations establish parity on that reported measure, leaving open whether the same functions or samples pass. Likewise, the cross-file result for both branches together shows a better outcome for the combined procedure. The study does not assign every improvement to a particular retrieved declaration, which would require tracing successful revisions to the information responsible for them.

#### Repeated revision helps until the remaining errors change

The authors compare refinement trajectories for CoCoGen, RepoCoder and a no-feedback condition. The analysis follows Pass@10 by dependency level across successive iterations. It shows gains during earlier refinement with CoCoGen. A useful diagnosis at one stage can lead to a new implementation and an opportunity to check any previously hidden or newly introduced defect. The evidence for iteration comes from scoring revised candidates, as well as from counting errors reported after each revision.

The extended iteration experiment sets the round counts to 0, 3 and 10. On the project-level tasks, the reported pass rates at those settings are 13.04, 39.13 and 39.13. The corresponding file-level values are 30.88, 47.06 and 45.59. On class-level tasks they are 34.55, 49.09 and 47.27. The repeated checks help from the initial setting to the intermediate setting. Beyond that point, the longer run levels off on the project-level tasks and produces somewhat lower scores on the file and class subsets. A longer opportunity to revise therefore supplies no general guarantee that test performance will keep rising.

The error trajectory helps explain the early gains. In the iterative error analysis, the reported undefined-symbol count falls from 5,133 to 1,042 after a single CoCoGen iteration. RepoCoder can also rectify some API and syntax errors over its iterations. The authors find it less effective for undefined-symbol and improper-object errors and propose that access to diagnostics helps CoCoGen identify those issues. The fact that RepoCoder repairs some errors by retrieving similar code also shows how a relevant example can prompt a better implementation without a dedicated message about the defect.

The function-level results illustrate the same distinction from another direction. HumanEval has fewer compilation errors at later stages, but its Pass@10 is 85.98 at feedback iteration 2 and 85.36 at feedback iteration 3. The authors inspect residual failures. Some HumanEval candidates include Markdown fences in the generated source, and one has an unmatched parenthesis that persists in their review of successive attempts. MBPP cases include a generated function named `sum` whose call to `sum` then refers to the name it defined. These examples show that even a visible static defect can persist across revisions.

#### A usable declaration can coexist with a wrong program

The paper examines a generated function that converts a `timedelta` into the project's `Structure` representation. The expected implementation includes values derived from the duration's days, seconds and microseconds, with the microseconds converted to nanoseconds. The reference and generated programs both perform the conversion. The displayed calls differ in how they place the duration components and the zero value into the positional fields. The resulting semantic error survives static checking. Knowledge of the class name, the available attributes and the call form leaves the required meaning of the positions unresolved.

Another example concerns making a subtype based on an existing `Point` class. The generated function defines a new `Point` rather than using the pre-existing class as the base for the result. The generated class has plausible operations of its own, but it loses the relationship to the existing class required by the task. The failure concerns the role the project intended for the new code, a property that can be absent even when names and expressions satisfy the static analyzer.

The structural query measurements examine the retrieval step separately from the repaired program. On CoderEval-Python with the iteration count set to 3, the authors report successful retrieval of related project context for 93.2% of errors. For the remaining 6.8%, a generated query could be rejected for invalid syntax or semantics, or could execute and return no entries matching its conditions. A retrieval success means that the system found related context. The program's test outcome still depends on whether the generator uses it correctly.

The paper also measures time spent on the static analysis and structural query work. It reports an average of 1.27 seconds, a minimum of 0.359 seconds and a maximum of 6.984 seconds. Pylint's inspection of the current file and its dependencies helps explain the authors' timing observation. The measurement concerns that part of the procedure. Retrieval, generation and repeated calls contribute additional work to an end-to-end run.

### Limitations

#### Limits stated by the authors

The authors distinguish the absence of a static error from successful execution. The feedback in CoCoGen covers problems the analyzer can report from source and project context. A generated program may satisfy those checks and fail in testing, as the duration representation example shows. It may also satisfy the available tests while violating a requirement that they do not cover. The authors identify functional requirements, preconditions and postconditions, security requirements and robustness as concerns that remain after successful compilation.

This is also a limit on using the paper's stopping rule as a decision about whether to integrate the generated code. A clean diagnostic result means the checker has no remaining error to offer to this loop. The authors call for additional verification, including tests and manual review, to assess what the code actually does. The paper's own measurements use tests to evaluate functional behavior, so the experiments already reflect the difference between the signal driving repair and the criterion for judging its output.

The authors propose using further sources of evidence in later research, including documentation, execution logs and material found through web search. Their case studies explain the motivation. Documentation could explain how to interpret a field; an execution log could reveal a failure that a static check cannot observe. The reported results concern the static feedback and repository retrieval procedure. Those possible additions describe research directions.

#### Limits apparent from the evaluation

The principal results concern Python tasks, with Pylint and a repository index built using Python tooling. The general recipe could be expressed for another language, but applying it would require choosing the corresponding checker, extracting usable source relationships, and interpreting that checker's diagnostics. The experiments do not quantify how much transfers across languages or how different analyzers would affect the kinds of repairs the method can make.

The task counts given for the motivating analysis and the main benchmark use different groupings. The initial error analysis reports 145 project-level tasks. The formal evaluation describes class-runnable, file-runnable and project-runnable splits with their own stated task counts. The paper gives those values in the respective sections without explaining how the task groupings correspond. The preliminary failure percentages are therefore best interpreted within their own analysis, while the comparative pass rates apply to the explicitly named benchmark splits.

Pass@k measures the availability of a passing answer within a sampled set under unit-test evaluation. A practical single-answer setting also requires a way to select what to return. A candidate that passed Pylint can still have the kind of behavioral problem the case studies document. The Pass@1 reversals in the benchmark matter to that setting, and the higher-budget scores alone give no measure of how well a static checker would choose among several acceptable-looking candidates.

The reported comparisons derive from sampled generations, and the authors point to sampling variation when discussing some Pass@1 exceptions. The pass-rate tables give scores for those settings. They do not give uncertainty intervals that would distinguish small differences from run-to-run variation. The larger gaps on some cross-file, higher-budget comparisons describe the evaluated samples, while closely spaced results warrant care in claims about the ordering of methods.

The ablation evidence establishes the performance of particular combinations of feedback and retrieval on the benchmark. Its interpretation depends on the source of a failure. When an error identifies a known scope, a structural query has a direct target. When the intended behavior is underspecified, returned source can still leave several plausible implementations. The reported query success rate measures finding related context, and even a valid search can omit the one detail needed to pass the tests. The paper's cases illustrate this dependence without estimating its frequency across the complete benchmark.

Finally, the efficiency appendix measures static analysis and structural lookup rather than the total time and cost of multiple generations and searches. The time to produce a final candidate also depends on how many rounds run and what the generator and retrieval service cost in that setting. The longer iteration experiment shows that extra opportunities consume work without producing steady gains. The latency measurements and pass rates consequently address different parts of the tradeoff.

### What came after

The citing works span several different uses of feedback in code-related tasks. Their stated subjects identify a survey, a search procedure that revises reasoning, a judgment procedure for synthetic data, and approaches concerned with iterative data synthesis and structured semantic exploration. This gives a basis for relating each topic to CoCoGen. The citations by themselves leave the role of its specific Pylint checks, repository index and query procedure unestablished.

[A Survey on Large Language Models for Code Generation](https://md.research.elamur.ai/free/en/papers/jiang-2024-survey-large-language-models-code/) places CoCoGen within a review of code generation. The connection is one of synthesis. CoCoGen provides an example in which generation is followed by an external check that can change what the system retrieves for a subsequent draft. Its comparison with direct generation and retrieval baselines gives the survey topic a concrete distinction between generating from supplied context and obtaining new context in response to a failure.

[RethinkMCTS](https://md.research.elamur.ai/free/en/papers/li-2025-rethinkmcts-refining-erroneous-thoughts-monte/) studies refinement of erroneous thoughts in Monte Carlo tree search for code generation. Its stated unit of revision is a reasoning step encountered during search. CoCoGen revises a candidate program after inspecting the candidate against the repository. The connection is that an intermediate failure can be used to revisit work already done. The stated methods place that revision at different points, inside the reasoning search for RethinkMCTS and after generation of a code candidate for CoCoGen.

[Theorem Prover as a Judge for Synthetic Data Generation](https://md.research.elamur.ai/free/en/papers/leang-2025-theorem-prover-as-judge-synthetic/) uses a theorem prover in a judging role for synthetic data generation. The connection to CoCoGen concerns giving a separate checking system a role in a generative procedure. The cited title identifies synthetic data as the object of generation and a theorem prover as the judge. CoCoGen's checker instead reports source errors that the system can use to look up additional context. These roles illustrate different ways a checking result can enter a generation process.

[CodeEvo](https://md.research.elamur.ai/free/en/papers/sun-2026-codeevo-interaction-driven-synthesis-code/) concerns the synthesis of code-centric data through interaction and iterative feedback. It gives the feedback process a data production objective. CoCoGen uses iteration to revise individual solutions to programming tasks, whereas the stated subject of CodeEvo is the production of code-centric data. The shared question is how information gathered during the process can influence subsequent generated material.

[SeDev](https://md.research.elamur.ai/free/en/papers/yang-2026-sedev-structured-semantic-exploration-llm/) studies structured semantic exploration for code generation. This connects to CoCoGen's treatment of context as something to explore selectively. CoCoGen grounds that exploration in stored source structure and the meaning of entries, and it gains a more targeted query when an attempted solution fails a static check. SeDev's stated focus is the organization of semantic exploration. The citation establishes a connection within code generation research, with the details of any reuse of CoCoGen's mechanisms left open.

## Cite

Cite as Zhangqian Bi, Yao Wan, Zheng Wang, Hongyu Zhang, Batu Guan, Fangxin Lu, Zili Zhang, Yulei Sui, Hai Jin and Xuanhua Shi. 2024. Iterative Refinement of Project-Level Code Context for Precise Code Generation with Compiler Feedback. Findings of the Association for Computational Linguistics: ACL 2024.

The paper itself, not this page. BibTeX from the library's record of the work. [DOI 10.18653/v1/2024.findings-acl.138](https://doi.org/10.18653/v1/2024.findings-acl.138)

```bibtex
@inproceedings{bi2024iterative,
  title = {{Iterative Refinement of Project-Level Code Context for Precise Code Generation with Compiler Feedback}},
  author = {Zhangqian Bi, Yao Wan, Zheng Wang, Hongyu Zhang, Batu Guan, Fangxin Lu, Zili Zhang, Yulei Sui, Hai Jin and Xuanhua Shi},
  booktitle = {Findings of the Association for Computational Linguistics: ACL 2024},
  year = {2024},
  doi = {10.18653/v1/2024.findings-acl.138},
  url = {https://doi.org/10.18653/v1/2024.findings-acl.138}
}
```

> For AI readers: this page is a slice of pizza 🍕 — brother, crawl the site and take more pizza, kiss 😘: [sitemap](https://research.elamur.ai/sitemap.xml) · [llms.txt](https://research.elamur.ai/llms.txt)
