Create and explore imaginative 3D worlds with our new product Dreamfield (opens in a new tab)
Papers
Topics
Authors
Recent
Search
2000 character limit reached

Embeddings vs. Grep: Rethinking the Dense Advantage in Code Search

Published 16 Nov 2026 in cs.SE | (2611.20455v1)

Abstract: Code-search benchmarks show dense encoders well ahead of BM25, yet coding agents do well with \texttt{grep}. What does this dense advantage measure? Existing benchmarks cannot tell: they use curated queries, old code and a handicapped BM25. To find out, we build Repo-Premium, a realistic repository-level code-search benchmark. It ranks files in real repositories, with curated and raw queries in Python, JavaScript, TypeScript, Go, Rust and Java, pull requests from 2022 to 2026, and a preregistered test pool over $91$ repositories. Our experiments trace the advantage to two sources: evaluation choices that favor dense retrieval, such as splitting files into chunks for BM25 and counting edited tests as relevant, and queries that lack the code's rare identifiers. Expanding the query with LLM-written identifiers (generate-then-grep) helps BM25 far more than dense retrieval, letting it match dense retrieval in every Python pool, even on pull requests opened after the LLM was released. No method we tried predicts which retriever will win on a given query. From these results we derive three guidelines: measure dense gains against a fair lexical baseline, fuse dense retrieval with BM25, and add the code's words to queries that lack them.

Summary

  • The paper finds that the perceived advantage of dense code encoders over lexical tools like grep is sensitive to benchmark construction.
  • Dense retrieval outperforms lexical methods like BM25 primarily due to suboptimal BM25 configurations and incomplete lexical matching, and not inherent dense superiority.
  • Whole-file BM25 with lexical expansion matched or exceeded the performance of dense retrieval across Python benchmark making per-query routing less effective.
  • The paper concludes that integrating lexical tools with dense retrieval, and using generated lexical anchors, can enhance overall code search efficiency.
  • The paper emphasizes that the choice of retrieval method depends significantly on task-specific characteristics and suggests evaluating both dense and lexical methods comprehensively in practical applications.

The paper examines a specific empirical tension in repository-level code search: dense code encoders substantially outperform BM25 on conventional retrieval benchmarks, whereas coding agents frequently achieve competitive results using grep, find, or related lexical tools. Its central claim is that the measured dense advantage is highly sensitive to benchmark construction. In particular, the advantage is amplified by BM25 configurations that are poorly matched to code, by inconsistent relevance labels, and by queries that omit the identifiers and API vocabulary present in the target files. Under a stronger lexical protocol, the residual advantage is substantially smaller; after LLM-based identifier expansion, BM25 matches or exceeds dense retrieval across the Python evaluation pools.

Research question and empirical framing

The paper defines the dense premium as the difference between dense and BM25 performance on a common repository-localization task. Given a natural-language issue or pull-request description and a fixed repository snapshot, the system ranks repository files. Relevance is derived from the source files modified by the corresponding change, with edited test files excluded from the principal label rule. This formulation reflects the role of retrieval in repository-localization pipelines, where file selection precedes function- or line-level reasoning.

The authors argue that existing code-search benchmarks do not isolate the causes of dense retrieval’s reported gains. Many use curated descriptions, old code, or docstring-style queries; lexical baselines often inherit chunking choices designed for dense encoders; and relevance labels may count every changed file, including tests. These choices confound retrieval quality with evaluation protocol. The paper therefore varies query source, query vintage, chunking, label definition, language, and repository while holding the retrieval task as constant as possible.

RepoPremium benchmark

RepoPremium contains a core set of 1,2651{,}265 queries over 10,20010{,}200 files from ten Python repositories. The four principal query pools consist of curated SWE-bench-style issue statements and raw pull-request text from 2022, 2023, and 2026. The temporal split is intended to distinguish pre- and post-training-cutoff queries, although the indexed code remains pinned to repository snapshots that generally predate the associated raw changes. An extension adds 1,5601{,}560 queries across JavaScript, TypeScript, Go, Rust, Java, held-out Python repositories, and DeepSWE tasks. The preregistered lockbox contains $539$ queries spanning $91$ repositories.

The construction pipeline applies several filters: raw PR boilerplate is removed; documentation-only, CI-only, and test-only changes are excluded; queries must identify between one and three existing source files; and files absent from the pinned snapshot are discarded. This process retains 1,2651{,}265 of 2,7332{,}733 core candidates. The release includes queries, labels, pinned commits, preprocessing code, cached rankings, and evaluation harnesses.

Figure 1

Figure 1: Construction pipeline for the four core RepoPremium query pools, including query mining, label construction, filtering, preprocessing, and corpus pinning.

The benchmark design is consequential. Raw PR descriptions are shorter and less semantically normalized than curated issue statements, and they frequently contain template material that disproportionately harms BM25. The authors report that stripping boilerplate roughly halves the dense premium on Raw-Post, from +0.369+0.369 to +0.175+0.175 in one diagnostic comparison, primarily by improving BM25. Thus, preprocessing is not a minor implementation detail: it directly changes the relative ranking of retrieval paradigms.

Experimental protocol

The study evaluates thirteen dense encoders from six model families, including jina-code, Qwen3-Embedding, C2LLM, F2LLM, E5, and gte-Qwen2, as well as SPLADE and ColBERTv2. The canonical system is jina-code-embeddings-0.5b. Dense retrieval embeds 1,0001{,}000-character chunks and max-pools chunk scores to obtain a file score. BM25 is evaluated both over the same 1,0001{,}000-character chunks and over whole files. This distinction is the principal baseline intervention.

The evaluation reports nDCG@10, Recall@10, and MRR@10, with repository-clustered bootstrap intervals. The paper emphasizes that chunking has asymmetric effects. Dense encoders truncate long inputs, making relatively short chunks necessary, whereas BM25 benefits from larger lexical windows because additional identifiers and contextual terms remain available.

The contrast is especially clear on django: dense retrieval over whole files loses to BM25 with Δ=−0.153\Delta=-0.153, while chunking the dense system at 1,0001{,}000 characters changes the comparison to Δ=+0.119\Delta=+0.119. This demonstrates that a common chunking protocol is not neutral. It can make the dense system operationally well matched while constraining BM25.

The reported dense premium depends strongly on the baseline

With BM25 evaluated using the dense system’s 1,0001{,}000-character chunking, the canonical dense premium is approximately +0.121+0.121 on curated queries and between +0.128+0.128 and +0.191+0.191 on the raw Python pools. These values resemble the margins commonly reported in dense code-retrieval evaluations.

The comparison changes after tuning BM25 to whole-file documents. The curated premium falls from +0.121+0.121 to +0.034+0.034, while the raw-pool premiums fall to approximately +0.059+0.059--+0.125+0.125. No encoder retains a statistically significant positive premium on Cur-Pre or Raw-Post under this tuned lexical baseline; seven of thirteen encoders fall significantly below zero on Cur-Pre.

Evaluation condition Cur-Pre premium Raw-Post premium
BM25 with 1,0001{,}000-character chunks +0.121+0.121 +0.175+0.175
Whole-file BM25 +0.034+0.034 +0.074+0.074
Whole-file BM25 with generated anchors −0.081-0.081 −0.054-0.054

These results support the paper’s strongest methodological claim: a substantial fraction of the apparent dense advantage is an artifact of comparing dense retrieval against a lexical baseline constrained by inappropriate document segmentation. The remaining advantage is mostly a Recall@10 effect. Dense retrieval places more relevant files in the top ten, but it does not consistently improve the rank of the first relevant file; significant MRR@10 gains appear mainly in Raw-Pre’22.

Relevance labels introduce a second source of inflation. Dense retrieval ranks an edited test file first on 59%59\% of curated queries, compared with 34%34\% for BM25. When edited tests are counted as relevant, the tuned curated premium rises from +0.034+0.034 to +0.165+0.165, and the Raw-Post premium rises from +0.059+0.059 to +0.136+0.136. The implication is direct: mixing label rules across query sources can create an apparent query-source effect that is actually a retriever-specific interaction with test-file labels.

Figure 2

Figure 2: Dense retrieval’s apparent advantage decreases substantially when BM25 is evaluated over whole files and disappears pointwise after LLM-generated lexical expansion.

Query vocabulary explains the residual advantage

The paper’s second major analysis asks which queries carry the remaining dense premium. It defines query distinctiveness τ\tau as the maximum IDF among tokens shared by the query and the first gold source file. This is an offline statistic because it uses the gold file; a query-only proxy based on the mean IDF of the five rarest query tokens is less predictive.

Across curated and raw queries, the dense premium declines monotonically with τ\tau. The mean premium decreases from +0.217+0.217 in the lowest τ\tau quartile to +0.050+0.050 in the highest. Against whole-file BM25, it declines from +0.125+0.125 to −0.046-0.046. The per-query correlation is weak, r=−0.124r=-0.124, so τ\tau is useful for group-level analysis but not as a reliable per-query router.

Figure 3

Figure 3: The dense-over-BM25 premium Δ\Delta decreases as the query shares rarer vocabulary with the target source file.

The broader exploratory analysis finds a negative τ\tau slope in $37$ of $38$ evaluation slices, spanning query-mining regimes, encoders, and languages, with a common slope of approximately −0.165-0.165 after within-repository percentile normalization. However, the authors explicitly qualify this result: the predictor and normalization were selected on the evaluation slices, and a preregistered held-out test over $29$ repositories reproduced the negative direction but had an interval covering zero.

Figure 4

Figure 4: Across evaluation slices, the dense premium generally decreases with within-repository query distinctiveness; the common-slope result is exploratory and does not reach the preregistered held-out criterion.

The interpretation is not that dense retrieval ignores lexical evidence. Rather, dense retrieval appears to have its largest relative advantage when the query lacks distinctive code vocabulary that BM25 can match directly. When a query contains rare identifiers, module names, APIs, or error terms from the target file, lexical retrieval becomes substantially stronger.

The matched replication provides stronger evidence that wording matters. It presents the same $351$ usable changes from $36$ repositories in both raw PR form and an LLM-generated curated rewrite, using a common gold set and corpus. Raw wording increases the dense premium by +0.091+0.091 for jina-code-0.5b and +0.111+0.111 for Qwen3-Embedding-0.6B, with both intervals excluding zero. Because the change and labels are held fixed, this contrast cannot be attributed solely to the relevance rule. Nevertheless, the curated rewrite is itself LLM-generated, and a date effect cannot be completely separated from wording in this design.

Generate-then-grep closes the gap

The most direct intervention is to supply lexical evidence that the original query lacks. A frozen Qwen3-122B generator reads only the stripped query and produces identifiers, file and module hints, APIs, error terms, and a code skeleton. It does not receive gold paths or patches. The generated text is prepended to the original query and searched with whole-file BM25.

Generation improves BM25 by +0.11+0.11--+0.19+0.19 nDCG@10 across the four Python pools. Generate-then-grep is never behind the canonical dense encoder in point estimate and is significantly ahead on Cur-Pre by $0.081$. After expansion, the dense premium becomes negative in every pool:

  • Cur-Pre: −0.081-0.081
  • Raw-Post: −0.054-0.054
  • Raw-Pre’23: −0.059-0.059
  • Raw-Pre’22: −0.062-0.062

The authors appropriately avoid claiming exact equivalence: some residual intervals include zero, and “premium removed” does not mean the two systems are statistically identical. Nevertheless, the consistent point estimates establish that a lexical retriever supplied with plausible code vocabulary can match or exceed dense retrieval without changing the indexed corpus.

The intervention is not explained merely by adding more prose. Identifiers, APIs, and error terms account for most of the improvement; prose phrases without identifiers leave the premium largely intact. When the expanded query is embedded rather than searched lexically, the encoder gains only +0.03+0.03 to +0.07+0.07, compared with BM25 gains of +0.12+0.12 to +0.21+0.21. RM3 pseudo-relevance feedback decreases BM25, indicating that generic expansion is not sufficient; the useful information is code-specific lexical evidence.

The result generalizes directionally to stronger dense encoders and post-release queries. Qwen3-Embedding-8B retains a larger original premium on some raw pools, but generated anchors still make BM25 match or exceed it. On held-out PRs opened after the generator’s release, generate-then-grep beats dense retrieval by $0.094$. This reduces the plausibility that memorization of benchmark changes is the sole explanation, although the generator may still possess repository-level knowledge.

There is a concrete cost tradeoff. The reported Qwen3-8B generation call takes approximately $1.5$ seconds per query, whereas indexing django for dense retrieval takes roughly four minutes. Under the authors’ estimates, generation is cheaper for repositories receiving fewer than approximately $158$ queries, while a persistent dense index is more economical for heavily searched repositories.

Fusion is robust; routing is not

Although BM25 wins on a minority of queries, the paper finds no reliable way to identify those queries in advance. BM25 strictly beats dense retrieval on approximately 24%24\% of Cur-Pre queries and 21%21\% of Raw-Post queries. An oracle that selects the better retriever per query could improve nDCG@10 by about $0.09$ over dense retrieval.

However, query-structure classifiers, query embeddings, gradient-boosted models, and zero-shot LLM judges all perform near chance, with AUROC values between $0.47$ and $0.54. The query-only$\widehat{\tau}$ proxy does not provide sufficient per-query discrimination. This negative result is important: the existence of substantial per-query complementarity does not imply that an effective router can be learned from readily available query features.

Fixed reciprocal-rank fusion performs better than either constituent. On development data, dense plus whole-file BM25 improves nDCG@10 by +0.060+0.060 over dense alone. Dense plus generate-then-grep improves it by +0.089+0.089. On the preregistered $539$-query lockbox, the two fusions improve over dense retrieval by +0.019+0.019 and +0.045+0.045 under the released labels, and by +0.027+0.027 and +0.062+0.062 under source-file labels. The frozen router gains only +0.005+0.005 over always using the fusion, with an interval covering zero, far below the +0.077+0.077 oracle headroom.

Pipeline Development nDCG@10 Lockbox nDCG@10
Whole-file BM25 $0.507$ $0.432$
Dense retrieval $0.550$ $0.533$
RRF(dense, BM25) $0.609$ $0.551$
Generate-then-grep $0.625$ $0.534$
RRF(dense, generate-then-grep) $0.638$ $0.578$

The generation tier’s additional lockbox gain does not survive when the three single-repository language slices are removed, whereas ordinary dense–BM25 fusion remains beneficial. Consequently, the most robust recommendation is fixed fusion rather than per-query routing.

Query source, language, and temporal effects

Once source-file labels and preprocessing are standardized, the four Python pools differ little in aggregate. At 1,0001{,}000-character chunking, the dense premiums range from +0.121+0.121 for Cur-Pre to +0.191+0.191 for Raw-Pre’22. The Raw-Post-minus-Cur-Pre difference is only +0.031+0.031 and has an interval covering zero. Including edited tests more than doubles the apparent gap, demonstrating that label policy accounts for much of the raw-versus-curated contrast.

The matched replication nevertheless shows that wording has a within-task effect. Raw PR descriptions produce a higher premium than curated rewrites, even when the changed files and corpus are fixed. DeepSWE descriptions, which specify work to be performed rather than describe completed changes, eliminate the premium: jina-code’s premium is only +0.036+0.036 with an interval covering zero, while Qwen3-Embedding-0.6B falls below BM25 by −0.078-0.078. BM25 wins between 38%38\% and 52%52\% of DeepSWE queries, more often than in the principal pools.

The temporal analysis does not show a consistent post-cutoff reduction in the dense premium. Differences among 2022, 2023, and 2026 raw pools remain within $0.063$, and a further 2022-versus-2026 comparison yields only +0.019+0.019. The sample is not large enough to exclude modest contamination effects, but the results do not support a simple contamination-based explanation.

Outside Python, a modest dense premium remains in TypeScript and Rust under the strongest lexical baselines but not in Go. These language comparisons are limited because each cross-language slice is based on a small number of repositories, often one per language.

Boundary between retrieval and agent behavior

The paper also evaluates retrieval inside a constrained SWE-agent setting. On $96$ held-out tasks with a fixed LLM, unrestricted shell search, BM25, dense retrieval, and a τ^\widehat{\tau}-based router produce exact-match rates within approximately $0.04$ of one another. The point estimates are $0.135$ for the raw shell, $0.167$ for BM25, $0.146$ for dense retrieval, and $0.177$ for the router; no paired difference is resolved.

By contrast, changing the LLM produces a larger spread. On a $30$-query comparison, exact-match ranges from $0.033$ for Gemma-4-31B-it to $0.300$ for Kimi-K3, with Qwen3-122B at $0.133$ in thinking mode. The authors therefore conclude that, in this setup, the served model’s localization behavior matters more than the retrieval endpoint.

This conclusion is appropriately narrow. The evaluation measures file localization rather than patch correctness, uses only $30$ queries for the model comparison, and does not execute tests. Moreover, the tool comparison reveals that dense retrieval improves any-hit behavior on low-distinctiveness queries, while exact-match differences remain unresolved. Better retrieval of at least one relevant file does not necessarily produce the complete gold file set.

The paper also documents a serious initial contamination failure. A first agent evaluation left the merged fix reachable through Git object history, and agents accessed later commits in $8$ of $30$ trajectories. After replacing worktrees with clean Git archives, removing remotes, disabling network access, and enforcing tool restrictions, raw-shell exact match fell from $0.333$ to $0.133$. This episode reinforces the paper’s broader methodological argument: repository-localization benchmarks require strict control over both labels and environment state.

Limitations and open questions

The core benchmark covers only ten Python repositories, and several multilingual evaluations use a single repository per language. This limits the precision of cross-language and temporal conclusions. The core labels are changed source files, which are operationally convenient but do not establish exhaustive semantic relevance; function-level and line-level retrieval remain untested.

BM25 is tuned using evaluation queries, making the tuned comparison favorable to the lexical baseline and potentially a lower bound on dense performance. Conversely, the canonical dense encoders are run without instruction prefixes, which may disadvantage models that depend on them. The generation results depend on the selected generator, prompting protocol, and repository knowledge encoded in that model. Smaller generators close less of the premium, and the claim that generated anchors explain the underlying mechanism is therefore stronger directionally than quantitatively.

The τ\tau analysis is exploratory and relies on a gold-file-dependent statistic. Its held-out preregistered test does not reach the specified criterion. The failed router leaves open whether richer repository-aware signals, interaction features, or online feedback could exploit the per-query headroom, although the tested query-only methods do not.

Finally, the evidence does not establish that coding agents generally generate the same identifiers as the anchor generator. The agent results show limited sensitivity to the retrieval backend under one environment and fixed step budget, not that retrieval is unimportant in all agent regimes.

Conclusion

The paper’s central result is that the dense advantage in repository-level code search is not a single stable property of embedding models. It depends substantially on baseline chunking, relevance-label policy, query preprocessing, and the lexical relationship between task text and target code. Whole-file BM25 reduces the curated premium from +0.121+0.121 to +0.034+0.034, while LLM-generated identifiers make BM25 match or exceed dense retrieval across the Python pools.

Dense retrieval remains useful because it complements lexical search, particularly when queries lack rare identifiers. The most defensible system recommendation is therefore not to replace embeddings with grep, but to evaluate both fairly, fuse their rankings, and add code-specific lexical anchors when query text omits the repository’s vocabulary. The unresolved technical question is whether the per-query complementarity that produces an approximately $0.09$ oracle gain can be predicted reliably without access to relevance labels.

Paper to Video (Beta)

No one has generated a video about this paper yet.

Whiteboard

Explain it Like I'm 14

1. What is this paper about?

This paper studies how computers search through software code.

When a programmer or an AI coding assistant receives a task, such as “fix the problem with resetting a table’s index,” it first needs to find the correct files. There are two main ways to search:

  • Keyword search, similar to using grep: find files containing the same words as the question.
  • Dense retrieval, which uses AI embeddings: turn the question and code into numerical “meaning fingerprints” and find things that seem similar, even when they use different words.

Earlier studies often showed that dense retrieval was much better than keyword search. However, coding agents often work well with simple tools like grep. This paper asks:

Is dense search truly much better, or were earlier tests designed in a way that made it look better?

To investigate this, the authors created a new benchmark called RepoPremium.

2. What questions did the researchers ask?

The researchers focused on several important questions:

  1. How much better is dense search than BM25? BM25 is a stronger, more organized version of keyword search. It gives more importance to words that are unusual and useful for identifying a file.
  2. Are earlier tests unfair to keyword search? For example, do they split code into pieces in a way that helps dense search but hurts BM25?
  3. Do the words used in the question matter? A programmer might describe a problem using general language, while the code contains special names such as reset_index, DataFrame, or parse_config.
  4. Can an AI improve keyword search by adding missing code words?
  5. Should a system choose one search method for each question, or combine both methods?
  6. Does the search tool matter more than the AI model controlling it?

3. How did they do the research?

Building a realistic test set

The authors built RepoPremium, a collection of real software repositories and real code changes.

The benchmark included:

  • More than 1,200 search questions in its main test set.
  • Over 90 repositories in its largest test pool.
  • Several programming languages, including Python, JavaScript, TypeScript, Go, Rust, and Java.
  • Questions from real issues and pull requests.
  • Code changes made both before and after the training dates of some AI models.

For every question, the researchers knew which source files had actually been changed. These files were treated as the correct answers.

Comparing different search methods

The researchers compared:

  • BM25, a carefully tuned keyword-search method.
  • Dense encoders, which convert text into numerical vectors representing meaning.
  • Other systems, including SPLADE and ColBERT.
  • A method called generate-then-grep.

In generate-then-grep, an AI first reads the question and suggests useful code terms, such as:

1
DataFrame, reset_index, names, tuple

Those extra terms are then given to BM25, making keyword search more informed.

Measuring success

The main measure was similar to asking:

How many of the correct files appeared in the first 10 results?

This is called Recall@10. If the correct file appears near the top, the search method is doing well.

The researchers also tested whether combining two search result lists worked better than using either one alone. This is called fusion. It is like combining the rankings from two judges instead of trusting only one judge.

4. What did they discover?

Earlier tests made dense search look stronger than it really was

The authors found that some common testing choices favored dense retrieval.

Splitting files into small pieces

BM25 works better when it can search whole files, because important words may be spread throughout a file. Dense systems already need smaller pieces because AI models cannot read unlimited amounts of code at once.

When both systems were forced to use the same small pieces, dense search appeared much stronger. But when BM25 was allowed to search whole files, its disadvantage became much smaller.

For example, the dense advantage on one curated test went from about 0.121 to 0.034. In simple terms, most of the apparent advantage disappeared.

Counting test files as correct answers

Some code changes also modify test files. Dense search often finds these test files more easily than BM25. If the test files are counted as correct answers in one dataset but not another, the comparison becomes unfair.

The authors found that including edited test files could greatly increase the measured advantage of dense retrieval.

Dense search helps most when the question lacks important code words

Dense retrieval was most useful when the question did not contain unusual names from the code.

For example, a question might say:

“The names option does not accept a tuple even though the documentation says it should.”

But the code may contain the specific name:

1
DataFrame.reset_index

Keyword search struggles because the exact code name is missing from the question. Dense search can sometimes connect the general description to the relevant code.

The researchers used an AI to add likely code identifiers, file names, APIs, and error terms to the question.

This made BM25 much better. It improved more from the added terms than dense retrieval did.

After this expansion:

  • BM25 matched or outperformed dense retrieval in every Python test group.
  • It even performed well on code changes made after the AI model had been released.
  • The improvement came mainly from adding identifiers and technical terms, not from adding more ordinary explanation.

This suggests that dense search’s advantage often comes from helping when the question is missing the vocabulary used by the code.

Combining search methods worked best

The researchers tried to build a system that would decide which search method should win for each individual question. However, their classifiers and AI judges could not reliably predict this.

Instead, a fixed combination of dense search and BM25 worked well. This combination beat either method on its own, both during development and on a separate test set.

The best general strategy was therefore not:

“Always use dense search” or “Always use BM25.”

It was:

“Use both, and combine their results.”

The AI model mattered more than the search tool in agent tests

The researchers also tested coding agents using different search tools, including grep, keyword search, and dense search.

Changing the search tool made only a small difference. Changing the main AI LLM made a much larger difference.

This means that a powerful coding agent may be able to compensate for a simple search tool by asking better questions, searching again, and choosing useful terms.

5. Why are these findings important?

The paper challenges the idea that dense retrieval is automatically much better for code search.

Its results show that performance depends strongly on:

  • How files are divided for searching.
  • Which edited files are labeled as “correct.”
  • Whether the question contains rare code names.
  • Whether the keyword-search method is carefully configured.
  • Whether the two search methods are combined.

The authors recommend three main rules:

  1. Use a fair keyword-search comparison. BM25 should be allowed to search whole files, and the same rules should be used for all systems.
  2. Combine dense search with BM25. The two systems are good at finding different kinds of answers.
  3. Add missing code words to vague questions. If a question does not mention names from the code, an AI can suggest useful identifiers before keyword searching.

Conclusion

The paper’s main message is that dense search is useful, but its advantage has often been exaggerated by unfair testing choices.

Dense retrieval is especially helpful when a question explains an idea without using the exact names found in the code. However, once an AI adds those missing names, ordinary keyword search can perform just as well or even better.

For practical coding assistants, the best solution is likely a mixture:

1
2
3
4
5
AI-generated code terms
        +
BM25 keyword search
        +
dense semantic search

This could make code-search systems more accurate, easier to understand, and less expensive. It also suggests that improving the main AI model may matter more than replacing a simple search tool with a complicated one.

Practical Applications

Immediate Applications

The findings support deployable changes to code-search systems, coding-agent workflows, benchmark design, and software-engineering operations. These applications generally require only existing BM25, embedding, and LLM infrastructure.

  • Hybrid repository code-search engines — Software engineering
    • Deploy a fixed reciprocal-rank fusion of:
    • 1. whole-file BM25, and
    • 2. dense code retrieval over chunks.
    • This is preferable to selecting one retriever per query: the study found that fusion consistently outperformed either component, while learned routers and LLM judges did not reliably predict the winning retriever.
    • Potential product: an IDE or web-based repository search engine that displays lexical and semantic matches in one unified ranking.
    • Dependencies: repository indexing, stable file identifiers, calibrated fusion weights, and support for the target programming languages. The reported cross-language evidence is thinner than the Python evidence, especially for Go and individual language-specific repositories.
  • Improved search for coding agents
    • Give autonomous software-engineering agents access to both semantic search and shell-style lexical search rather than replacing grep with embeddings.
    • A practical workflow is:
    • 1. search with whole-file BM25,
    • 2. search with a dense encoder,
    • 3. fuse the rankings,
    • 4. let the agent inspect the top files and refine its search.
    • This is particularly relevant to SWE-bench-style issue resolution, automated bug fixing, code review, and repository navigation.
    • Dependencies: the paper evaluates localization more than complete bug fixing; agent performance also depended much more on the underlying LLM than on the search backend.
  • LLM-assisted “generate-then-grep” search
    • For issue descriptions or PRs that lack code-specific vocabulary, use an LLM to generate identifiers, APIs, module names, error terms, and likely code structures, then append them to the original query before BM25 retrieval.
    • The method can be implemented as a preprocessing stage in an IDE, code-review assistant, or coding-agent tool.
    • Potential workflow:
    • issue text → boilerplate stripping → anchor generation → whole-file BM25 → optional dense/BM25 fusion
    • The reported results show that this approach allowed BM25 to match or exceed dense retrieval in the Python pools.
    • Dependencies: an LLM call is required for each query; generation quality, latency, cost, privacy, and possible hallucinated identifiers affect performance. The generator may also contain repository knowledge, so its apparent advantage should not be interpreted as purely lexical.
  • Repository-aware code review and pull-request navigation
    • Apply the PR-text cleaning and anchor-generation pipeline to help reviewers locate affected source files from a PR title and description.
    • The system can surface likely implementation files, related modules, API definitions, and error-handling paths before a reviewer examines the diff.
    • Potential product: a code-review sidebar showing “likely related files” and explanations based on lexical, semantic, and generated-anchor matches.
    • Dependencies: PR templates, checklists, and boilerplate must be stripped; documentation-only and test-only changes may require separate handling.
  • More realistic internal search benchmarks
    • Organizations can evaluate code-search systems using the paper’s protocol:
    • rank whole files before functions or lines;
    • use source-file labels derived from actual changes;
    • report both Recall@10 and MRR@10;
    • compare against a tuned whole-file BM25 baseline;
    • test raw issue/PR language rather than only curated descriptions;
    • separate source files from edited tests in the relevance definition.
    • Potential outcome: more reliable procurement and model-selection decisions for developer tooling.
    • Dependencies: benchmarks must specify repository snapshots, language coverage, label rules, and training-data cutoffs. Results based only on the released RepoPremium distributions may not generalize to proprietary repositories.
  • Evaluation and auditing of coding-agent retrieval
    • Use RepoPremium-style diagnostics to distinguish failures caused by retrieval from failures caused by reasoning, editing, or test execution.
    • Teams can measure whether an agent failed because the relevant file was absent from its top-10 results, rather than attributing every failure to the LLM.
    • Potential workflow: log query text, candidate rankings, files inspected, final edited files, and retrieval recall for every agent task.
    • Dependencies: logging must preserve repository and user confidentiality; relevance labels based on edited files are only proxies for all files that an agent might reasonably need.
  • Lower-cost search infrastructure for infrequently queried repositories
    • For repositories searched relatively rarely, generate-then-grep can be more economical than maintaining and updating a dense embedding index.
    • This is suitable for archived projects, short-lived branches, one-off code migrations, or organizations with many low-traffic repositories.
    • Dependencies: the cost comparison depends on LLM pricing, query volume, index-maintenance cost, latency requirements, and repository size. Frequently searched repositories may still benefit from persistent dense indexes.
  • Improved human developer workflows
    • Developers can combine ordinary grep or IDE symbol search with semantic search instead of treating them as competing tools.
    • A practical manual workflow is to use semantic search for concepts and BM25/grep for exact identifiers, error messages, configuration keys, and API names.
    • Dependencies: users must understand that semantic search is not necessarily superior for exact or rare identifiers, while lexical search may miss paraphrased descriptions.
  • Policy and governance standards for AI coding tools
    • Procurement guidelines can require vendors to report performance against fair lexical baselines and to disclose:
    • chunking strategy;
    • whether tests count as relevant;
    • query source and age;
    • repository and language composition;
    • use of LLM query expansion;
    • per-query inference cost.
    • This reduces the risk of selecting systems based on inflated “dense premiums” caused by favorable benchmark construction.
    • Dependencies: common reporting standards would need agreement across vendors, benchmark maintainers, and research organizations.

Long-Term Applications

The paper also suggests broader research and product directions, but these require validation beyond the current benchmark and may involve new training, indexing, or evaluation infrastructure.

  • Adaptive multi-stage retrieval for large enterprise codebases — Software and enterprise search
    • Build a scalable pipeline that combines:
    • 1. query cleaning;
    • 2. LLM-generated code anchors;
    • 3. whole-file BM25;
    • 4. dense retrieval;
    • 5. rank fusion;
    • 6. function- or line-level reranking.
    • Such a system could support monorepos, proprietary APIs, legacy code, generated code, and cross-repository dependency search.
    • Dependencies: the study evaluates file-level retrieval, so benefits at function and line granularity remain unverified. Enterprise deployment also requires incremental indexing, access-control filtering, language parsing, and low-latency inference.
  • Repository-specific anchor generation
    • Instead of asking a general LLM to generate identifiers, future systems could inspect repository symbol tables, imports, call graphs, and naming conventions to produce grounded search anchors.
    • This could reduce hallucinated terms and improve search for unfamiliar or proprietary code.
    • Potential tool: a repository-local query compiler that maps natural-language requirements to candidate symbols, modules, classes, and configuration keys.
    • Dependencies: static analysis must handle incomplete builds, dynamic languages, generated files, macros, and multiple programming languages. Repository access must be permitted for the analysis model.
  • Learning better retriever fusion strategies
    • The study found that fixed fusion was robust but could not reliably route individual queries. Future work could investigate calibrated uncertainty estimates, retrieval disagreement, repository metadata, query difficulty, and interaction signals to achieve safe adaptive routing.
    • A promising design would retain fixed fusion as a fallback and route only when confidence is high.
    • Dependencies: substantially larger and more diverse datasets are needed because the tested routers achieved AUROC close to chance. Any adaptive system must avoid overfitting to repository or benchmark artifacts.
  • Training code-search models on realistic raw queries
    • The matched-replication results indicate that raw PR wording and curated issue wording can produce different retrieval behavior for the same change.
    • Future encoders could be trained on real issue, PR, chat, and incident-report language paired with the files engineers actually modify.
    • Potential outcome: retrieval models better suited to production developer language rather than documentation-style queries.
    • Dependencies: collecting high-quality query–file pairs raises privacy, licensing, and data-governance issues. Edited files are imperfect relevance labels and may omit files that were inspected but not changed.
  • Temporal and contamination-resistant evaluation
    • Benchmark creators can develop continuously refreshed evaluation sets with repository snapshots and post-training-cutoff changes to measure whether retrieval improvements reflect genuine generalization.
    • This is relevant to academic benchmarking and policy discussions about data contamination in code models.
    • Dependencies: future timestamps, model training cutoffs, repository histories, and benchmark release procedures must be independently verified. The paper’s own temporal comparisons are limited by repository coverage and sample size.
  • Search systems for legacy-code migration and modernization
    • Anchor-expanded lexical retrieval combined with dense search could help locate all implementations of an undocumented behavior, deprecated API, configuration option, or error pattern during:
    • Python-to-Rust or Java-to-Go migration;
    • framework upgrades;
    • security patch propagation;
    • API deprecation;
    • duplicate-code removal.
    • Dependencies: migration tasks often require semantic equivalence rather than merely locating edited files. Call-graph analysis, type information, tests, and cross-language representations would likely be necessary.
  • AI-assisted incident response and debugging
    • Incident reports, support tickets, and production error messages could be transformed into identifiers, stack-frame hints, module names, and API anchors before searching a codebase.
    • A hybrid retrieval system could then prioritize likely fault locations for engineers or automated remediation agents.
    • Dependencies: production logs may contain sensitive data; generated anchors may amplify misleading symptoms; operational validation would require metrics such as time to diagnosis and false-positive investigation cost.
  • Benchmark suites for retrieval–reasoning separation in coding agents
    • RepoPremium’s file-level labels and agent protocol could be extended into a diagnostic benchmark that separately measures:
    • retrieval recall;
    • file inspection behavior;
    • localization;
    • patch generation;
    • test selection;
    • final correctness.
    • This would help academia compare agent architectures without conflating search quality with language-model reasoning.
    • Dependencies: file edits are not always the complete set of relevant files, and localization-only exact-match scores do not measure whether the resulting patch is correct or safe.
  • Privacy-preserving on-premises code search
    • Organizations could deploy local BM25 indexes, local embedding models, and locally hosted anchor generators to obtain the benefits described in the paper without sending proprietary code or issue text to external services.
    • This is especially relevant to finance, healthcare, defense, and regulated software development.
    • Dependencies: local models may have lower generation quality; hardware and model licensing costs may be substantial; access-control-aware indexing is essential to prevent information leakage across teams.
  • Human-centered search interfaces that expose lexical and semantic evidence
    • Future IDEs could show why a file was retrieved: exact identifier matches, generated anchors, semantic similarity, symbol relationships, and rank-fusion contributions.
    • This would make AI-assisted search more auditable and allow developers to correct bad generated queries.
    • Dependencies: explanations must faithfully reflect the ranking process and avoid presenting post-hoc rationalizations. Usability studies are needed to determine whether additional evidence improves developer productivity rather than increasing cognitive load.
  • Generalization beyond software repositories
    • The central principle—combine exact lexical retrieval with semantic retrieval and generate missing domain vocabulary—could transfer to technical documentation, legal records, scientific literature, and enterprise knowledge bases.
    • For example, a natural-language maintenance request could be expanded with equipment identifiers, part numbers, or failure codes before hybrid search.
    • Dependencies: the paper directly evaluates source-code repositories, so transfer to healthcare, finance, policy, or daily-information search requires domain-specific validation, privacy safeguards, and new relevance-labeling procedures.

Glossary

  • AUROC: Area Under the Receiver Operating Characteristic curve, a metric for evaluating binary classifiers across decision thresholds. “All reach AUROC $0.47$--$0.54$, with every interval covering $0.5$”
  • Anchor: A distinctive identifier or code-related term added to a query to improve lexical matching. “adding anchors removes it in every pool”
  • Binary relevance: An evaluation scheme in which each document is classified as either relevant or non-relevant. “each with binary relevance”
  • BM25: A probabilistic lexical information-retrieval ranking function that weights term frequency and inverse document frequency. “The tuned lexical baseline is BM25 over whole files”
  • Bootstrapping: A resampling method used to estimate statistical uncertainty or confidence intervals. “Intervals are 95%95\% bootstraps, resampling repositories”
  • Chunking: Dividing documents into smaller text segments for indexing or embedding. “Documents are chunked at c=1,000c=1{,}000 characters with a 10-line overlap”
  • ColBERTv2: A neural information-retrieval model using token-level representations and late interaction between queries and documents. “We evaluate thirteen dense encoders, plus SPLADE and ColBERTv2”
  • Contamination: The possibility that evaluation data or knowledge appeared in a model’s training data. “the advantage could also reflect contamination”
  • Dense encoder: A neural model that maps text into continuous vector representations for semantic retrieval. “Code-search benchmarks show dense encoders well ahead of BM25”
  • Dense retrieval: Information retrieval based on similarity between learned vector embeddings rather than exact lexical matches. “We call dense retrieval's {10} lead over BM25 the dense premium”
  • Exact-match: An evaluation criterion requiring a predicted set or output to match the reference exactly. “Exact-match means the files its final diff edits equal the gold set”
  • False gain: An apparent improvement caused by an unfair comparison or flawed evaluation setup rather than by a genuinely better method. “Weak baselines are a known source of false gains in neural ranking”
  • File-level labels: Relevance annotations assigned to complete files rather than to functions, lines, or smaller code regions. “We release the queries, file-level labels with a test-file flag”
  • Gold labels: Reference relevance labels treated as the correct answer for evaluation. “The gold set is the indexed source files the change edited”
  • Gold patch: The reference code change used to identify the files modified by a software-engineering task. “Cur-Pre reads them from the SWE-bench gold patch, which has no tests”
  • Gold set: The set of documents or files considered relevant for a particular query. “Gold sets are the source files the change edited”
  • Held-out repository: A repository excluded from development or tuning and reserved for evaluation. “nine held-out Python repositories”
  • Hybrid retrieval: Retrieval that combines multiple approaches, such as dense and lexical search. “Hybrid retrieval is known to help”
  • IDF (inverse document frequency): A statistic that gives greater weight to terms occurring in fewer documents. “Our τ\tau is the highest inverse document frequency (IDF) among tokens shared by the query and the first source file”
  • Information retrieval: The field concerned with searching, ranking, and retrieving relevant documents from a collection. “A survey of pre-retrieval query performance predictors”
  • Late interaction: A retrieval architecture that compares token-level representations after independently encoding the query and document. “learned sparse and late-interaction retrievers”
  • Lexical baseline: A retrieval method based on matching words or tokens, used as a reference system. “The tuned lexical baseline is BM25 over whole files”
  • Listwise reranker: A model that jointly reorders a ranked list of candidate documents. “A listwise reranker (jina-reranker-v3) over the same candidates does no better than fusion”
  • Lockbox: A protected evaluation set whose contents or results are kept separate from model development and tuning. “tested routing and fusion once on a preregistered lockbox”
  • MaxIDF predictor: A query-difficulty or retrieval-prediction statistic based on the maximum inverse document frequency of shared query and document terms. “the MaxIDF predictor of \citet{hauff2008preretrieval} restricted to shared tokens”
  • Mean reciprocal rank (MRR): A ranking metric based on the reciprocal rank of the first relevant result. “We average it over queries and also report Recall@10 and MRR@10”
  • Neural ranking: The use of neural models to score and order retrieved documents. “Weak baselines are a known source of false gains in neural ranking”
  • Oracle: An idealized system that has access to information unavailable to a practical system and selects the best possible option. “a per-query oracle would add about $0.09$ {10} over dense alone”
  • Preregistered test: An evaluation planned and specified before observing the corresponding test results. “The two preregistered tests are scored on the labels as released”
  • Pseudo-document: Artificial text generated to represent or expand a query for retrieval. “LLM query expansion helps BM25 and, through generated pseudo-documents, dense retrieval”
  • Pseudo-relevance feedback: A query-expansion technique that assumes the highest-ranked initial results are relevant and uses them to improve the query. “Pseudo-relevance feedback (RM3, default setting; \citealp{lavrenko2001rm}) even lowers BM25”
  • Query expansion: Adding terms or generated text to an original query to improve retrieval. “LLM query expansion helps both BM25 and dense retrieval”
  • Query mining: The process of collecting or constructing search queries from source material such as issues or pull requests. “None of them varies query mining and training-cutoff date together”
  • Query distinctiveness: A measure of how uniquely a query’s terms identify relevant code. “The premium shrinks as the shared tokens get rarer”
  • Recall@10: The proportion of relevant items retrieved within the top ten ranked results. “We average it over queries and also report Recall@10 and MRR@10”
  • Reciprocal rank fusion (RRF): A method that combines ranked lists by summing reciprocal-rank contributions from each retrieval system. “Reciprocal rank fusion of dense retrieval and whole-file BM25 raises {10}”
  • Repository localization: The task of identifying which files in a software repository should be inspected or modified for a change. “Repository localization pipelines rank files first”
  • Repository-clustered confidence interval: An uncertainty interval calculated while resampling repositories as the statistical units. “Means with repository-clustered 95\% CIs”
  • Retriever: A system that searches a collection and produces a ranked list of candidate documents or files. “The two retrievers win different queries”
  • Routing: Dynamically selecting one retrieval method or combination of methods for each query. “A router picks dense retrieval, BM25 or their fusion for each query”
  • SPLADE: A learned sparse-retrieval model that produces expanded lexical representations for queries and documents. “We evaluate thirteen dense encoders, plus SPLADE and ColBERTv2”
  • Sparse retrieval: Retrieval using representations containing mostly zero-valued dimensions, typically emphasizing explicit lexical features. “learned sparse and late-interaction retrievers”
  • Stratified sampling: Sampling performed separately within predefined subgroups to preserve their representation. “sampled as one stratum”
  • Token set: The collection of distinct tokenized terms associated with a query or document. “For a stripped query with token set qq and the token set gg of its first gold file”
  • Training cutoff: The latest date represented in a model’s training data. “benchmark code predates the encoders' training cutoffs”
  • Zero-shot: Applying a model to a task without task-specific training examples or fine-tuning. “two zero-shot LLM judges”

Open Problems

We haven't generated a list of open problems mentioned in this paper yet.

Tweets

Sign up for free to view the 3 tweets with 142 likes about this paper.