Accelerating Code Retrieval for Coding Agents: Practices and Trade-offs

    Coding agents rely on dozens or even hundreds of search operations per task, so retrieval latency compounds quickly. This article explains why naive linear scanning becomes a bottleneck at scale, how trigram-based inverted indexes accelerate code search, the key architectural components of an indexed retrieval system for agent scenarios, and the trade-offs and risks teams should evaluate before adoption.

    1. Background: Why Search Latency Gets Amplified

    When a coding agent handles a development task, it rarely receives the full context upfront. Instead, it acquires context incrementally, on demand. A typical workflow includes: locating where a function is defined, tracing which modules call it, finding where a configuration field is read or written, and tracing back relevant code from an error message. Every step depends on retrieval, and a single task may accumulate dozens or even hundreds of search operations.

    This means retrieval latency is not a one-time cost—it is charged repeatedly across multiple rounds of tool calls. Suppose a single search takes 2 seconds and a task performs 60 searches: the retrieval phase alone consumes 2 minutes. No matter how long model inference, reading, and editing take, they all queue behind this waiting time. The larger the codebase, the more pronounced this cumulative effect becomes.

    This article discusses general bottlenecks in the retrieval phase and is not tied to any specific product. The problem applies to all agent tools that depend on search.

    2. The Cost Model of Linear Scanning

    The most naive retrieval approach is to read files one by one and match line by line using strings or regular expressions. It is simple to implement, requires no extra state, and produces correct results immediately after any file change. The cost is that every query’s overhead is proportional to the total bytes in the repository:

    • As the number of files grows, so do directory traversal and file-open operations at the OS level;
    • As data volume grows, so does the amount read from disk or memory;
    • As query count grows, the same files are repeatedly read and matched.

    At a scale of a few hundred thousand lines, a full scan with warm caches is usually acceptable. Once the codebase grows to tens of millions of lines, the growth in file count and total bytes makes each search noticeably more expensive. A slight slowdown per query gets amplified across many rounds of calls.

    A representative naive implementation looks like this:

    1. def naive_search(repo_root, pattern):
    2. results = []
    3. for path in iter_all_files(repo_root): # Traverse all files on every query
    4. with open(path, "rb") as f:
    5. for lineno, line in enumerate(f, 1):
    6. if pattern.search(line):
    7. results.append((path, lineno))
    8. return results

    The main problem with this code is that iter_all_files and file reading involve no reuse whatsoever. The work between two queries is entirely duplicated, even if the queries differ by only a single character.

    3. How Indexed Retrieval Works

    The idea behind indexed retrieval is to replace “scan every file” with “narrow down candidates first, then verify precisely.” At its core is a pre-built mapping from text fragments to files—an inverted index.

    One common approach is the trigram index. During construction, each file’s content is split into all consecutive three-character fragments, and the index records which files each fragment appears in. When querying the string parseConfig, the system extracts all of its trigrams, intersects the file sets corresponding to those trigrams, and obtains a set of candidate files. Only the candidates need to be actually read and precisely matched.

    1. from collections import defaultdict
    2. def build_index(files):
    3. index = defaultdict(set) # trigram -> set of file IDs
    4. for file_id, text in files:
    5. for i in range(len(text) - 2):
    6. index[text[i:i+3]].add(file_id)
    7. return index
    8. def candidate_files(index, literal):
    9. if len(literal) < 3:
    10. return None # Query too short; fall back to full scan
    11. grams = {literal[i:i+3] for i in range(len(literal) - 2)}
    12. return set.intersection(*(index.get(g, set()) for g in grams))

    Two points deserve attention here. First, the candidate set is only a filtering result and may contain false positives, so candidate files must still undergo exact matching. Second, the index must never miss files that truly match, so query preprocessing must preserve semantics and must not rewrite the query content.

    For regular expressions, the idea is the same, but literals that must appear in any match need to be extracted from the expression first. For example, foo and bar in foo\w+bar can serve as filter conditions. If the expression contains no extractable literals—patterns like .*—the system can only fall back to a full scan.

    4. Architecture Design Considerations

    An indexed retrieval system suitable for agent scenarios typically includes the following components.

    4.1 Index Construction and Incremental Updates

    The index needs to be built in full when a repository is first onboarded, then updated incrementally as files change. Implementation should focus on the following:

    • Compute increments via file-change watching or version-control diffs;
    • Use batched writes and atomic swaps to prevent queries from reading a half-built index;
    • Record the mapping between index versions and repository commits to help troubleshoot inconsistent results.

    4.2 Query Path

    A query typically goes through three stages: candidate filtering, exact verification, and result assembly. Candidate filtering relies on the index, and its cost correlates with the number of candidates. Exact verification reads only candidate files. Result assembly includes ranking, deduplication, and truncation at a configured limit.

    4.3 Agent-Oriented Result Design

    Retrieval results go directly into the model’s context, so the output format needs to be restrained. Recommendations:

    • Return file paths, line numbers, and the necessary context lines instead of entire files;
    • Set a cap on result count and indicate in a structured field whether truncation occurred;
    • Provide statistics such as the number of matched files and total matches to help the agent decide whether to refine the query.

    4.4 Ignore Rules

    Repositories contain large amounts of content unrelated to source code, such as binary files, build artifacts, dependency caches, and auto-generated code. The indexing phase should honor the ignore configuration from the version control system and skip or specially handle oversized files. The more reasonable the ignore rules, the more controllable the index size and build time.

    5. Trade-offs and Risks

    Indexing also has costs, and teams should evaluate the following before adoption:

    • Storage and memory: Index size relates to total text volume and fragment type; there is a trade-off between space overhead and recall capability.
    • Data consistency: A stale index causes missed matches, which in turn affects the agent’s judgment of the code. The system must have freshness checks and fall back to full scanning when the index is untrustworthy.
    • Short-query degradation: Single-character or high-frequency fragments produce large candidate sets with limited filtering benefit; such queries should go directly down the scanning path.
    • Overly broad regex: Expressions from which no literals can be extracted bypass the index; the tool layer can surface hints for such queries.
    • Concurrency and locking: Index updates and queries may run concurrently, so synchronization must be handled carefully.