AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

How Sourcegraph Cody Indexes Massive Codebases Without Token Limit Bottlenecks

Natalia Amaral · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

Enterprise codebases do not fit into context windows. A production monorepo can easily span tens of millions of lines of code across tens of thousands of files. Even if an LLM boasts a theoretical 1-million-token context window, dumping an entire repository into a prompt is an architectural dead end. It is painfully slow, prohibitively expensive, and plagued by the "lost-in-the-middle" attention degradation that causes models to hallucinate APIs or ignore critical business logic.

At 365Finds, we frequently encounter engineering teams who assume AI coding assistants rely purely on dense vector databases—chunking millions of files, calculating embeddings, and hoping cosine similarity finds the right lines. Sourcegraph Cody actually started down that path during its early development. Then, Sourcegraph realized that pure vector retrieval breaks under real-world enterprise conditions.

To index massive codebases without suffocating large language models or blowing through token budgets, Sourcegraph Cody deploys a hybrid retrieval architecture. It combines trigram keyword indexing via Zoekt, structural code intelligence, selective semantic search, and aggressive snippet-level token budgeting. Here is how Cody solves the codebase scale problem without hitting token limits, and what engineering leaders need to know before deploying it.


The Failure of Pure Vector Embeddings at Scale

During Cody's early beta phases, Sourcegraph relied heavily on dense vector embeddings (such as OpenAI's text-embedding-ada-002) to handle retrieval-augmented generation (RAG). On paper, vector embeddings sound ideal: turn code into mathematical vectors and match natural-language queries to conceptually similar code blocks.

In enterprise environments with tens of thousands of repositories, this pure-vector approach ran into three critical barriers:

  1. The Compliance and Security Gate: Calculating embeddings for billions of tokens meant streaming proprietary source code to third-party embedding APIs. For regulated industries and security-conscious enterprises, this was an immediate blocker.
  2. Operational Overhead and Stale Indexes: Repositories move fast. Every commit, merge, and branch rebase invalidates parts of the vector index. Re-indexing tens of millions of lines continuously incurs immense computational costs and creates lag between committed code and AI awareness.
  3. The Lexical Precision Problem: Code is not natural language. Code punishes fuzzy similarity. If a developer searches for an exact function signature, an unusual error constant, or an obscure interface name, cosine similarity often returns semantically related prose while missing the exact symbol definition. Furthermore, arbitrary chunking splits function definitions from their call-sites, destroying syntactic relationships.

Recognizing these limitations, Sourcegraph pivoted. Instead of forcing vector databases to do a job they were never designed for, Sourcegraph connected Cody directly to its existing, battle-tested enterprise search engine.


The Engine Room: Zoekt Trigram Search Meets Code Graph

The core technical advantage of Sourcegraph Cody is Zoekt, an open-source, high-performance trigram code search engine originally developed by Han-Wen Nienhuys and heavily maintained by Sourcegraph.

Zoekt does not store high-dimensional floating-point vectors. Instead, it builds an inverted index based on character trigrams (sequences of three consecutive characters) mapped into memory using memory-mapped files (mmap). This allows Zoekt to execute exact token matching, regular expressions, and structural symbol queries across petabytes of code in sub-second time.

When Cody indexes a massive codebase, it constructs a multi-layered search index:

By making Zoekt and structural graph indexing the primary retrieval layer, Cody avoids the multi-gigabyte vector index overhead and keeps latency within interactive editor tolerances.


The Context Pipeline: How Cody Beats Token Limits

Indexing massive repositories is only half the battle. The other half is packing the most relevant pieces of that index into a strict LLM token window. Cody accomplishes this through a deterministic five-stage context funnel.

[ Developer Prompt ]
       │
       ▼
[ Query Rewriting & Token Extraction ]
       │
       ▼
[ Hybrid Retrieval: Zoekt + SCIP + Local Workspace ]
       │
       ▼
[ AST-Level Snippet Extraction & Pruning ]
       │
       ▼
[ Relevance Scoring & Greedy Token Budget Packing ]
       │
       ▼
[ Augmented Prompt to LLM (Claude / GPT-4o) ]

1. Query Rewriting and Token Extraction

When you ask Cody a question in your IDE, it does not send your raw prose directly to an LLM. Cody's client and server inspect the prompt, extract potential code identifiers, parse file path hints, and formulate optimized search queries tailored for Zoekt.

2. Multi-Source Retrieval

Cody simultaneously queries two distinct environments:

3. AST-Level Snippet Pruning

A common mistake in naive RAG tools is injecting whole files into the prompt. If Cody identifies an 8,000-line controller file as relevant, sending that entire file would consume half of a typical context window and introduce immense noise.

Instead, Cody parses the file's syntax tree to extract only the target function definition, its immediate docstring, relevant import headers, and surrounding type signatures. Unrelated methods in the same file are aggressively discarded.

4. Strict Token Budgeting and Greedy Packing

Cody operates with a strict, pre-allocated token budget for its prompt payload. The budget is segmented into distinct buckets:

Cody scores all retrieved code snippets using a modified BM25F ranking algorithm combined with structural proximity scores. It then greedily packs the highest-scoring snippets into the context pool until the token ceiling is reached. Any lower-ranked snippets are cleanly dropped. This ensures the LLM receives maximum signal density without overflowing the context window.

5. Explicit Context Steering (@-mentions)

Heuristic retrieval can occasionally miss nuances in complex, cross-module refactors. Sourcegraph mitigates this by giving developers deterministic override controls via @-mentions:

When a developer uses an @-mention, Cody bypasses speculative search and prioritizes those exact tokens in the budget allocation.


365Finds Institutional Evaluation

365Finds favors Sourcegraph Cody's architectural direction over the vector-only RAG patterns popular in earlier AI assistants. Sourcegraph made the pragmatic choice: code is structured, exact, and hierarchical, and Zoekt's trigram indexing paired with AST pruning provides far more reliable grounding than high-dimensional cosine similarity.

However, engineering teams should evaluate two critical caveats:

Sourcegraph Cody proves that conquering token limits does not require brute-forcing million-token context windows. By combining trigram indexing, structural code intelligence, and disciplined token budgeting, Cody indexes enterprise-scale codebases efficiently while delivering precise, hallucination-resistant answers.

References