Part 10 · Blueprint 67
AI Code Indexing & Repository Context Engine
14 min reading · Sources · Editorial review pending
An embedding cache hit does not prove the code or its access policy is current.
Page details
Published date · Last edited:
Draft edition. Editorial review and supplementary reading recommendations are still being completed.
Format: Architecture walkthrough. Prerequisites: the beginner bootcamp. Chapter prerequisites: Security Architecture, Zero-Trust & Multi-Tenancy, Search Engine & Real-Time Typeahead, Change Data Capture (CDC) & Outbox Pipelines (Debezium Scale).
Sixty-second mental model
Problem: An embedding cache hit does not prove the code or its access policy is current.
Use: Scope indexes to repository versions and synchronize deletions as well as edits.
Design boundary: Index repository content against a specific source tree and permission scope. Symbol boundaries, generated files, dependency versions and revision identity affect retrieval meaning.
Layer 1 · Intuition
Hypothetical scenario: Northwind is designing code indexing. Maya represents product requirements, Dev implementation and Priya reliability. The team must agree what one code chunk means and which component owns the repository and permission snapshot.
Think of a library catalog rebuilt only for changed book sections. Separate the requester from repository and permission snapshot, then identify the retained evidence needed after failure.
- Authority
- The entitled state owner.
- Invariant
- A rule preserved across concurrency and failures.
Architecture and worked reasoning
Design boundary: Index repository content against a specific source tree and permission scope. Symbol boundaries, generated files, dependency versions and revision identity affect retrieval meaning.
Responsibilities on the request path
Workload and limiting resource
Hypothetical 100,000 files averaging five chunks yield 500,000 chunks. A change affecting 1% of files requires reconsidering at least 1,000 files, plus dependency/symbol consequences; it does not prove only 1% of semantic references change.
Keep the units attached to each intermediate result. The assumptions above describe a hypothetical exercise, not observed vendor capacity. A real capacity decision also needs a measured service curve, skew, recovery traffic and an explicit admission policy for overload.
Mutation or publication path
- Resolve an immutable tree/revision.
- Parse/chunk with a versioned language configuration.
- Publish entries tied to source path, symbol and permission scope.
Observation and recovery path
- Query within authorized repository revisions.
- Return source locations and tree identity.
- Reject stale references or explain their revision.
Failure that changes the decision
Hypothetical scenario: A branch switch reuses chunks with the same path but different contents. Key by source identity/version and verify content rather than assuming path equality.
Attempt this decision before reading the explanation
Is incremental syntax parsing equivalent to a correct whole-program dependency graph?
No. Parsing improves local structure, while symbol resolution, build configuration and cross-file semantics require additional analysis.
Supporting mechanism analysis
Hypothetical scenario: Northwind. Maya represents product, Dev implementation and Priya reliability. The following workflow develops the underlying mechanism.
Hypothetical scenario. Northwind rebuilds search with a new analyzer while supplier permissions change and suggestion caches stay warm. Dev offers equal record counts as release evidence. Priya asks whether those records represent the same versions, eligible population and interpretation of a query.
Treat search configuration and source boundaries as a versioned release. Keep exact identifiers, discovery semantics and access eligibility intact through rebuild and recovery. The selected typing and update cohorts remain explicit, rather than silently changing catalogue demand.
Equal totals can hide different versions, missing recent changes or changed query interpretation. The release needs evidence about content and behavior, not only quantity.
This makes the transition reviewable. Include suggestion reuse and delayed changes so the old path cannot disclose content the new permissions prohibit.
Name the source boundary, schema, analyzer, query normalization and ranking configuration together. A document analyzer and query analyzer must interpret their intended fields compatibly. The same record count can hide omitted recent changes, obsolete withdrawals or a normalization change that breaks exact identifiers.
Build the candidate view alongside the current one under a declared ingestion boundary, then apply subsequent source changes without a gap. Compare the required query slices and inspect source-version coverage before switching readers. Keep the prior compatible release and a policy for writes and updates during rollback. An alias change cannot repair missing source history.
Hypothetical worked example. Choose twenty thousand completed search queries per day, each preceded by five suggestion requests. Suggestions add 20,000 × 5 = 100,000 requests. Combined query and suggestion work is 20,000 + 100,000 = 120,000 requests per day before retries. A completed-search count alone understates this selected serving workload.
Choose sixty thousand pending source updates, six thousand successful applications per minute and three thousand newly accepted updates per minute. Net recovery margin is 6,000 − 3,000 = 3,000 per minute. The backlog drains in 60,000 ÷ 3,000 = 20 minutes under constant rates and correct version application.
Hypothetical scenario. Build candidate index B from snapshot boundary S while index A continues serving. Capture every relevant source change after S, apply version-bound updates and removals, and expose B's applied watermark. A refresh makes applied records searchable; it does not prove that all source updates have arrived.
The switch rule requires a chosen completeness boundary, current permission enforcement and query evaluation. Counts can match while the candidate contains a deleted document and omits a new one. Permission or tombstone evidence must not regress when a late event arrives or the reader alias returns to A.
Retain compatibility for mixed readers during alias change. Queries in flight can finish on A while new queries reach B, so both must obey the disclosure contract. Rollback needs the post-S changes and removal evidence too; preserving A's files is insufficient if A stopped ingesting relevant updates. Track pending-update age and net catch-up capacity rather than treating rebuild completion as a single bulk-copy timestamp.
Elastic’s near-real-time search documentation distinguishes indexing from visibility through refresh. It supplies a concrete example of why acknowledgement and searchable observation are different facts. A documented refresh mechanism does not establish Northwind’s end-to-end permission or source-freshness rule.
A stale index can rank its available records correctly while omitting the current source. Track ingestion lag and version coverage separately from relevance. Source and access changes may need serving-time verification even when a full reindex is still running.
When changing analyzers, build a compatible new collection and compare it against held-out queries. Query normalization and document normalization must agree. A same-sized index or an unchanged API response shape does not establish behavioral compatibility.
Hypothetical failure scenario. An administrator searches for a confidential project. A shared cache stores the suggestion list under the query text alone. Another employee types the same prefix and sees the restricted name before submitting any search.
Scope suggestion eligibility and reuse to the authenticated reader's actual access contract. Avoid exposing sensitive query text through unrestricted logs or remote ranking services. A fast suggestion path must not bypass checks that the full result page enforces.
After a permission change, invalidate or revalidate affected derived results under the stated freshness rule. Record which cache and index version supplied the response so investigation can identify the failing boundary without assuming that the ranking function caused it.
“An index makes every query cheap.” The supported operators, candidate count and filtering pattern determine work. A broad prefix can still produce many candidates.
“No results means no matching source exists.” Ingestion, normalization, eligibility and candidate limits can all hide a record. Diagnose the path before changing ranking.
“A relevant result is an eligible result.” Relevance and permission are different predicates, and snippets and suggestions need both.
Start with reliable exact lookup and a measured topical baseline. Add bounded suggestions where they help users choose a query. Introduce additional spelling-correction behavior only when failure cases justify the extra ambiguity and evaluation burden.
Monitor query latency, candidate volume, filter rejection, empty results, source lag and slice-specific relevance. Limit short-prefix work and abusive repeated queries. Keep rebuilds and live updates within resource budgets that preserve the intended serving path.
Reject a single blended relevance score as proof of exact-identifier quality. Reject unbounded wildcard expansion and global suggestion caching without scope. A good search design is explicit about which query it understood and what its index can currently establish.
The interaction multiplier is a hypothetical request model. Query cost also depends on operators, selectivity, index representation and access filtering. Evaluate identity queries and ranked discovery separately; neither one favorable mean score nor a fast suggestion response establishes a correct access boundary.
An old source record can reappear when a rebuild replays a snapshot without subsequent withdrawals. Retain the change boundary and removal information needed to make the candidate current under its contract. If an obsolete update arrives after a newer removal, its version must not restore eligibility.
Layer 3 · Internals
A repository index binds chunks to a source-tree version, language interpretation and permission scope. Tree-sitter supplies incremental syntax parsing; syntax boundaries can guide chunks, but a function declaration alone does not include every imported symbol or behavioral dependency needed to answer a code question. Retrieval may combine symbol relationships, text search and embeddings.
A Merkle-style tree of content hashes helps identify changed subtrees, while content-addressed embedding reuse can avoid recomputing unchanged chunks. Hash equality proves only the relevant byte identity, not that two tenants may share the same retrieval result or metadata. Deletions, renames and branch switches must update the manifest as deliberately as edits. A request should identify the repository snapshot it intends to discuss so an answer does not silently mix code from incompatible branches. Privacy claims need a precise retention boundary: keeping embeddings, file paths or snippets can still retain sensitive information even if raw file bodies are not stored permanently.
Trade-offs and limits
| Approach | Provides | Requires |
|---|---|---|
| Semantic syntax chunks | Keeps many chunks aligned with code structure. | Syntax alone does not include all imports, symbols and runtime dependencies. |
| Fixed-size text windows | Simple, language-independent ingestion. | Chunk boundaries can split declarations and require more surrounding context. |
Recovery decision
Hypothetical scenario: A branch switch reuses chunks with the same path but different contents. Key by source identity/version and verify content rather than assuming path equality.
No. Parsing improves local structure, while symbol resolution, build configuration and cross-file semantics require additional analysis.
Write your design before revealing the review
Is incremental syntax parsing equivalent to a correct whole-program dependency graph?
Drafts and self-review are stored only in this browser. They are separate from reading completion.
Compare your decision
No. Parsing improves local structure, while symbol resolution, build configuration and cross-file semantics require additional analysis.
A branch switch reuses chunks with the same path but different contents. Key by source identity/version and verify content rather than assuming path equality.
Check your understanding
Is incremental syntax parsing equivalent to a correct whole-program dependency graph?
No. Parsing improves local structure, while symbol resolution, build configuration and cross-file semantics require additional analysis.
How would you recover from this failure: A branch switch reuses chunks with the same path but different contents. Key by source identity/version and verify content rather than assuming path equality.
Start with the exact boundary that failed. Resolve an immutable tree/revision. Parse/chunk with a versioned language configuration. Publish entries tied to source path, symbol and permission scope. Then recover evidence through the observation path: Query within authorized repository revisions. Return source locations and tree identity. Reject stale references or explain their revision. Preserve the distinction between a confirmed state change and an unavailable response.
Which assumption in the worked calculation would a burst or concentrated tenant invalidate first?
Hypothetical 100,000 files averaging five chunks yield 500,000 chunks. A change affecting 1% of files requires reconsidering at least 1,000 files, plus dependency/symbol consequences; it does not prove only 1% of semantic references change. Recompute the affected resource rather than multiplying unrelated storage and network budgets by the same factor. Index repository content against a specific source tree and permission scope. Symbol boundaries, generated files, dependency versions and revision identity affect retrieval meaning.
Which component in this topology could be removed from a smaller first deployment?
Repository snapshot, Syntax chunks, Code index, Authorized query name responsibilities, not a requirement for separate processes. Co-locate responsibilities when their transaction, trust and capacity boundaries permit it. Resolve an immutable tree/revision.
What evidence must a caller have before relying on the observation path?
Query within authorized repository revisions. Return source locations and tree identity. Reject stale references or explain their revision. No. Parsing improves local structure, while symbol resolution, build configuration and cross-file semantics require additional analysis.
45-minute interview rubric
- 00–05: scope code chunk and repository and permission snapshot.
- 05–12: identify the limiting resource and derive the domain workload above, retaining units and assumptions.
- 12–28: draw repository and permission snapshot, numbered writes and reads.
- 28–40: challenge recovery: Scope indexes to repository versions and synchronize deletions as well as edits.
- 40–45: defend repository_id placement, observations and remaining assumptions.
Go deeper
- Using Parsers - Tree-sitter · Primary document · tree-sitter.github.io. Scope indexes to repository versions and synchronize deletions as well as edits. Verified 2026-10-26.
- Near real-time search | Elastic Docs · Primary document · www.elastic.co. Scope indexes to repository versions and synchronize deletions as well as edits. Verified 2026-10-26.
Decision log
Scope indexes to repository versions and synchronize deletions as well as edits.
Preserve code chunk identity and repository and permission snapshot ownership.
Revisit changed workload, observations or recovery objectives.