Embeddings vs. Grep: Rethinking the Dense Advantage in Code Search
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.
Paper Prompts
Sign up for free to create and run prompts on this paper.
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:
- 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.
- 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?
- 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, orparse_config. - Can an AI improve keyword search by adding missing code words?
- Should a system choose one search method for each question, or combine both methods?
- 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.
Adding code terms made BM25 as good as, or better than, dense search
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:
- Use a fair keyword-search comparison. BM25 should be allowed to search whole files, and the same rules should be used for all systems.
- Combine dense search with BM25. The two systems are good at finding different kinds of answers.
- 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
grepwith 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.
- Give autonomous software-engineering agents access to both semantic search and shell-style lexical search rather than replacing
- 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
grepor 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/
grepfor 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.
- Developers can combine ordinary
- 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 bootstraps, resampling repositories”
- Chunking: Dividing documents into smaller text segments for indexing or embedding. “Documents are chunked at 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 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 and the token set 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”



