Developer tools · Research feature

Better Call Grep: Evaluating and Improving Grep-Like Lexical Retrieval for Repository-Level Code Completion

A study finds that lightweight, index-free lexical retrieval can match advanced methods in code completion, with improvements through targeted post-processing.

Adapted from research by Baoyi Wang, Xingliang Wang, Guochang Li and colleagues.

arXiv preprint revision · 2026-07-29 · Attribution & reuse
In this article
Editorial illustration of linked workflow.

Editor’s introduction

The research evaluates Naive GrepRAG, a method using simple lexical search commands like ripgrep to retrieve code context for completion tasks. It compares performance against graph-based retrieval systems and finds that despite lacking complex indexing, it achieves comparable results by capturing precise, spatially relevant code fragments. The study identifies key limitations, such as false matches from common keywords and context fragmentation due to fixed truncation points. To improve accuracy, the researchers introduce GrepRAG, which adds identifier-weighted re-ranking and structure-aware deduplication. Evaluations on CrossCodeEval and RepoEval-Updated show GrepRAG outperforms existing baselines by 7.04–15.58 percent in exact match scores. Analysis of 643 failure cases reveals that re-ranking failures dominate, especially in Python and Java, with 71.5% and 75.1% of cases respectively, indicating that post-processing is critical for robustness. The findings highlight the value of lightweight, developer-friendly retrieval methods in real-world code completion workflows.

Introduction

As a core feature of modern Integrated Development Environments (IDEs), code completion plays a pivotal role in enhancing development efficiency. In recent years, automated code completion driven by LLMs has demonstrated remarkable proficiency within single-file or single-function contexts. However, its performance often degrades significantly when applied to repository-level code completion. In large-scale repositories, relevant contextual information is typically fragmented across multiple files and directories due to modular code organization. As a result, crucial dependencies such as class definitions, utility interfaces, and global constants are frequently located outside the local file being edited. Given the limited context window of LLMs, it is infeasible to provide the model with the entire repository. Relying solely on intra-file context therefore misses essential cross-file dependencies.

RAG mitigates this contextual deficit by retrieving code snippets most relevant to the current logic at the repository level. Existing RAG methodologies can be primarily categorized into three streams. The first category comprises traditional similarity-based retrieval methods, which rank code snippets directly based on cosine similarity or BM25 scores relative to the code completion context. The second category involves structure-aware retrieval, which models the repository as a dependency graph via static analysis and leverages graph structural information to locate relevant context. The third category pertains to strategy-optimized retrieval; these methods employ Reinforcement Learning (RL) to train dense retrievers, thereby dynamically optimizing retrieval strategies based on end-to-end completion feedback.

Inspired by human developers, who commonly use simple lexical search tools such as Grep, Ctrl+F, or IDE features like Go to Definition and Go to Implementation during programming to locate class and method definitions or implementations across files. Such tools are also used to retrieve code fragments with similar naming patterns distributed throughout the repository. This structural or lexically similar information is essential for resolving cross-file dependencies in repository-level code completion. The observation motivates us to reconsider whether the potential of simple lexical retrieval has been fully explored before resorting to complex structural or semantic retrieval mechanisms. In parallel, modern agentic coding systems such as ClaudeCode and Windsurf have preliminarily demonstrated the feasibility of simple lexical matching by integrating Grep tools for multi-turn code question-answering tasks; however, the systematic application and evaluation of such techniques within the specific context of code completion remain unexplored.

Quantitative Analysis of Retrieval Latency and Scalability

While existing Vanilla-RAG and GraphRAG approaches demonstrate superior performance in enhancing completion accuracy, their retrieval latency can be substantial in practice. To systematically assess this cost, we measured the retrieval latency of BM25-based Vanilla-RAG and GraphCoder on the repositories of the RepoEval_Updated dataset.

Experimental Setup

Based on the aforementioned observations, we design a comprehensive experimental study to systematically evaluate the effectiveness and efficiency of grep_like lexical retrieval for repository-level code completion. This section introduces the experimental setup, including datasets, evaluation metrics, Naive GrepRAG, baseline methods, and implementation details.

Datasets

CrossCodeEval. We use the Python and Java subsets of CrossCodeEval to evaluate the model’s ability to handle scenarios that strictly require cross-file context for accurate code completion. The dataset includes 471 Python and 239 Java repositories, and applies static analysis to exclude samples that can be resolved using only intra-file context. This rigorous filtering ensures that all test cases depend on external context, allowing for a precise assessment of the retrieval module’s effectiveness in locating cross-file information.

RepoEval_Updated. To evaluate model performance on large-scale repositories, we employ the RepoEval_Updated dataset, derived from RepoEval. This dataset incorporates a task classification mechanism, categorizing tasks into Line-level for general coding and API-level for scenarios necessitating intra-repository API invocations. Comprising a total of 8,000 tasks across Python and Java, the dataset encompasses projects with substantial code volume (with some exceeding 500k LOC), thereby serving as an effective stress test for retrieval latency and scalability.

Evaluating the Potential of Naive GrepRAG

In this chapter, we conduct a systematic empirical study to explore the potential of Naive GrepRAG in repository-level scenarios. We first evaluate its end-to-end completion performance against sophisticated baselines (RQ1), then dissect the mechanisms behind its success (RQ2), and finally diagnose its limitations to inform directions for optimization (RQ3).

Motivation

The primary objective of this research question is to quantitatively validate the feasibility of the Naive GrepRAG framework and to investigate whether simply using LLM-generated grep commands to retrieve code context can effectively improve end-to-end code completion performance. We conduct this preliminary validation on the CrossCodeEval benchmark.

Analysis of End-to-End Performance

Experimental results show that Naive GrepRAG consistently outperforms comparative baselines across all evaluated metrics. In the Python subset under the DeepSeek-V3.2-EXP setting, our method achieves an EM rate of 38.61%, substantially exceeding the traditional Vanilla RAG (24.99%) and RLCoder (36.59%). Similarly, in the Java subset, Naive GrepRAG establishes a new benchmark with an EM of 41.70%. Furthermore, it attains the highest scores on both identifier EM and F1 metrics, indicating that precise character-level matching via ripgrep provides superior accuracy over vector-based retrieval in locating definitions of identifiers, such as functions and variables.

The retrieval time column highlights the practical efficiency of ripgrep. Our method achieves an average retrieval latency of less than 0.02s, outperforming approaches such as GraphCoder and RepoFuse, and substantially reducing the computational cost of the retrieval process.

Failure Analysis of RAG-based Baselines

We next analyze re-ranking failures, which primarily stem from the baselines’ inability to prioritize precise identifier matches. Specifically, GraphCoder emphasizes structural similarity (e.g., similar loop patterns), which can be irrelevant to the actual completion target. RLCoder uses a fine-tuned retriever to encode semantic similarity. While it captures conceptually related code, it often fails to rank exact method or variable names highly and its results are less interpretable. RepoFuse combines BM25-based lexical retrieval with call-chain–based dependency signals. However, its re-ranking stage still lacks the precision of Naive GrepRAG in emphasizing local identifiers, resulting in weak attention to identifiers with identical names.

Motivation

In the Venn analysis of RQ1, we observe that the solution space of Naive GrepRAG does not fully cover that of the baselines, which means there exist scenarios where a baseline succeeds while Naive GrepRAG fails. This research question aims to investigate the limitations of Naive GrepRAG and provide insights for subsequent improvements.

Analysis Results

Based on the aforementioned classification criteria, we analyze 643 failure samples. The data reveals that re-ranking failure is the dominant factor, accounting for approximately 71.5% of Python cases and 75.1% of Java cases, while recall failure constitutes the remaining 28.5% and 24.9%, respectively. We perform open coding on these samples to identify typical failure scenarios. To ensure coding rigor, the first two authors independently annotated the samples, achieving a Cohen’s kappa of 0.82, indicating substantial agreement. Through this process, we categorize failures into three representative classes: two reflecting distinct patterns of re-ranking failure, and one corresponding to the fundamental limitation of recall failure.

Keyword Ambiguity and Re-ranking Failure: When queries involve high-frequency generic identifiers such as init, config, or run, ripgrep retrieves a large number of irrelevant documents containing identical keywords but lacking semantic relevance. In the presence of such noise, current Naive GrepRAG relies on Jaccard similarity to compute the token overlap rate between retrieved chunks and the query. This approach cannot effectively distinguish frequent stop words from task-specific identifiers. Consequently, noise chunks containing numerous frequent terms accrue artificially high Jaccard scores, displacing the code blocks that actually contain the relevant context from the Top-K candidates.

Implicit Dependencies: It represents a fundamental limitation of lexical retrieval. The failures mainly arise when the current context lacks explicit structural relationships, such as inheritance, making it difficult for the Naive GrepRAG to locate the critical context using ripgrep commands.

Overview

RQ3 reveals that although Naive GrepRAG exhibits an exceptionally high recall rate, the primitive Jaccard re-ranking mechanism is inadequate for addressing keyword ambiguity, resulting in distractor documents with identical keywords but low semantic relevance. Furthermore, the absence of a deduplication mechanism leads to context redundancy and fragmentation. Consequently, this section investigates whether an efficient post-processing module can be introduced to resolve ranking bottlenecks and redundancy issues.

Ablation Study: Dissecting the Improvement

GrepRAG w/o BM25: This variant retains the original Jaccard ranking while adding the deduplication module. It achieves a substantial performance improvement, reaching an EM of 41.93% on Python DeepSeek-V3.2-EXP—an increase of 3.32% over Naive GrepRAG. This gain is considerably larger than that obtained by merely replacing the ranking algorithm.

GrepRAG (Full): The complete configuration. This combination achieves the optimal performance (42.29%), demonstrating that once the deduplication mechanism secures information breadth, the precise ranking of BM25 further optimizes information precision. The two exhibit a favorable orthogonal complementarity.

Discussion

Mitigating LLM Overhead for Retrieval Command Generation Although the physical retrieval cost of ripgrep is minimal (on the order of milliseconds), generating retrieval commands with a general-purpose LLM still incurs additional inference latency due to the model scale and output token length. To address this issue, we optimize the process from two complementary perspectives: output constraints and knowledge distillation.

Regarding output length, we observe that grep commands exhibit highly templated characteristics, such as fixed parameters and rigid formats. Accordingly, when fine-tuning Qwen3-0.6B, the model is tasked only with predicting the core retrieval keywords, while the remaining command structure is directly instantiated from a static template. This design substantially reduces the number of generated tokens and thus lowers inference latency. For distillation, since the quality of the teacher model directly determines the performance upper bound of supervised fine-tuning, we employ claude-opus-4-5-20251101, a model with strong code generation capabilities, as the teacher to construct high-quality training data.

Potential Data Contamination. A primary potential threat lies in the possibility that the pre-training corpora of LLMs may encompass portions of the evaluation benchmarks (CrossCodeEval/RepoEval_Updated), thereby introducing memorization bias into the assessment results. Although we cannot entirely rule out data overlap, the core conclusions of this study are premised on relative performance gains, rather than absolute scores. All baseline methods and our proposed approach utilize identical backbone models. The significant improvements observed in GrepRAG relative to baselines provide compelling evidence that the performance gains stem from more precise context retrieval, rather than knowledge leakage within the model parameters.

Comparison with Coding Agents. Although coding agents are designed for interactive repository-level software engineering rather than standalone code completion, we further compare GrepRAG with Claude Code under the same DeepSeek-V3.2 backbone. We evaluate on RepoEval_Updated (line-level and API-level) and CrossCodeEval. Due to the high time cost of running Claude Code on full datasets, we randomly sample from each full evaluation configuration. Specifically, RepoEval_Updated uses 372 samples for each task-language configuration, while CrossCodeEval uses 446 Python samples and 439 Java samples. These sample sizes satisfy a 95% confidence level with at most 5% margin of error.

Large Language Models for Code

The rapid evolution of LLMs has profoundly reshaped AI research, advancing natural language and multi-modal understanding while significantly boosting automated code completion and other software engineering tasks. Contingent upon the accessibility of model weights, existing technical paradigms are primarily categorized into two distinct classes: proprietary closed-source and open-source. Within this landscape, proprietary models, such as the GPT-5.2 series, Gemini3, and Claude Opus 4.5, are generally regarded as performance benchmarks for evaluating code generation capabilities. Simultaneously, the open-source community offers a plethora of robust alternatives, encompassing both general-purpose foundation models such as DeepSeek-V3 and Qwen 3, as well as domain-specific models explicitly optimized for programming languages, including Code Llama and StarCoder.

Repository-Level Code Completion

While the aforementioned models excel in handling intra-file logic, they struggle in repository-level scenarios. Due to the highly modular nature of code logic, critical class definitions, function interfaces, and global constants are typically dispersed across disparate files. Consequently, models constrained by limited context windows fail to capture global semantics. To address this challenge, RAG techniques have been introduced, aiming to retrieve relevant cross-file context from the global codebase to augment the generation process. Existing technical paradigms have evolved primarily along three distinct directions.

Early research predominantly adopted similarity-based retrieval paradigms, utilizing semantic or lexical matching to locate reference information. For instance, AceCoder and APICoder retrieve similar code snippets and API documentation, respectively, whereas RepoCoder dynamically expands query semantics through an iterative Generate-then-Retrieve loop. Although these methods extend the context window, their reliance on BM25 or vector similarity makes it difficult to capture the intrinsic logical dependencies of code. In response, structure-aware methods incorporate static analysis techniques, attempting to explicitly model the topological relationships of code. Works such as GraphCoder, RepoHyper, and Cocomic construct code context graphs or repository-wide dependency graphs to acquire structured information; RepoFuse further integrates noise filtering mechanisms upon this foundation. However, complex graph construction and traversal processes inevitably introduce high computational latency. Recent research has shifted towards strategy optimization and alignment, striving to bridge the objective gap between retrieval and generation tasks. RLCoder employs reinforcement learning for end-to-end fine-tuning of the retriever, utilizing generation probability as the optimization objective. Similarly, AlignCoder enhances query semantics by generating candidate completions and trains a dedicated retriever using feedback signals, thereby enabling the retrieval strategy to dynamically adapt to the inference requirements of downstream models.

Conclusion

This paper demonstrates the effectiveness of lightweight lexical retrieval for code completion. Our experiments show that Naive GrepRAG can achieve competitive performance by capturing explicit lexical dependencies, but suffers under noisy and fragmented contexts. To overcome these limitations, we propose GrepRAG, combining identifier-weighted re-ranking with structural deduplication. Experiments on CrossCodeEval and RepoEval_Updated demonstrate consistent improvements over strong baselines, establishing a new SOTA. Future work will investigate adaptive routing to better support implicit dependency scenarios.