REPOSITORY OBSERVATORY / MOCK 03

Code Intelligence & Drift Control

Design a multi-tenant platform that continuously maps many repositories into searchable symbols and detects when implementation stops matching approved intent.

30 MINUTES16 INTERVIEWER TURNSFULL Q & AINTERACTIVE LAB

The problem on the whiteboard

Read this once, then begin aloud. Spend the first two minutes establishing contract, actors, risk and what must remain authoritative.

Design CodeScope, a multi-tenant code-intelligence and drift platform. It connects read-only GitHub and GitLab repositories, incrementally indexes code across branches, exposes symbol-aware search, links code to approved requirements and blueprints, and comments on pull requests when a change appears to violate intent. A finding must carry enough evidence for a human to reproduce and dismiss it.
Central design thesis

The key decision is to separate authoritative artifacts and repository snapshots from derived indexes and probabilistic drift findings. Publication and permissions are strongly controlled; search and drift are rebuildable, version-labeled projections.

Scope before components

These are supplied mock numbers for sizing and follow-ups. Say your assumptions before using them.

Portfolio250 tenants · 8,000 repositories · 1.2B lines indexed
Change load25,000 push events/day · 15× burst after workday start
Freshness95% of changed symbols searchable in < 5 min; PR drift result < 7 min
Queries400 search QPS peak; p95 keyword < 250 ms, semantic < 700 ms
Trust99.9% query availability; no cross-tenant result; every finding reproducible

Actors

  • Engineer searching and reviewing a PR
  • PM or architect maintaining approved intent
  • Coding agent requesting scoped context
  • Tenant admin connecting repositories
  • GitHub/GitLab webhook and content APIs
  • Security or compliance auditor

Functional scope

  • Read-only repository onboarding and revocation
  • Incremental parse, symbol graph, lexical and semantic search
  • Trace links among artifact revisions, commits and symbols
  • Drift analysis with PR evidence and dismissal feedback
  • Tenant-aware freshness, audit, metering and backpressure

Explicitly out

  • Generating or merging code
  • Replacing the Git host
  • Compiling every language perfectly in v1
  • Proving semantic equivalence
  • Autonomous blocking of production merges

A traceable end-to-end path

Name the authoritative state, derived projections, asynchronous boundaries and the exact point where a business decision becomes durable.

Code Intelligence & Drift Control reference architectureSix stage architecture from Git host through Drift review.Git hostsigned eventsWebhook logdedupe + orderSnapshot fetchimmutable commitParse + graphAST / symbolsSearch indexeslexical + vectorDrift reviewevidence, not verdictaudit · policy · metrics · lineage
01Git hostsigned events
02Webhook logdedupe + order
03Snapshot fetchimmutable commit
04Parse + graphAST / symbols
05Search indexeslexical + vector
06Drift reviewevidence, not verdict

Keys that preserve history

The table is logical, not a mandate for one database. Choose physical stores after access patterns, transactions, retention and rebuildability are clear.

EntityPrimary / unique keyImportant fields and purpose
Repository(tenant_id, repo_id)provider_installation, encrypted_locator, default_branch, permission_epoch, state
CommitSnapshot(repo_id, commit_sha)parent_shas, observed_at, manifest_hash, index_state
FileVersion(repo_id, commit_sha, path_hash)blob_sha, language, parser_version, content_acl
Symbol(repo_id, commit_sha, symbol_id)qualified_name, kind, span, signature_hash
SymbolEdge(repo_id, commit_sha, from_id, type, to_id)calls/imports/implements/reads; extractor_version
ArtifactRevision(tenant_id, artifact_id, revision)approved_body_hash, schema_version, approval_state
TraceLink(artifact_revision, symbol_id, commit_sha)link_type, creator, confidence, evidence
DriftFinding(tenant_id, finding_id)analysis_run, rule/model versions, evidence spans, state, reviewer
POST /v1/repositories

Connect selected repo; idempotency-key required

202 {repoId,indexRunId}
POST /v1/webhooks/{provider}

Verify signature; persist raw envelope before ack

202
GET /v1/search?q=&repo=&commit=&cursor=

Hybrid symbol/code search pinned to permission epoch

200 {hits,nextCursor,indexedThrough}
POST /v1/trace-links

Propose requirement-revision ↔ symbol-at-commit link

201 / 409 stale revision
POST /v1/pulls/{id}/analyze

Deduped by repo + head SHA + policy bundle

202 {analysisRunId}
POST /v1/findings/{id}/reviews

Confirm, dismiss, suppress, with reason and etag

200 {state,version}

The complete mock interview

Answers are written in a speakable first-person style. Turn on Practice Mode to hide them, answer aloud, then reveal one at a time.

INTERVIEWER

Design the system. Where do you start?

CANDIDATE

I will first pin the trust boundary and success measure. GitHub and GitLab remain the source of repository bytes; approved requirement and blueprint revisions remain the source of intent. Our indexes and findings are derived. The user journey is connect → index → search → change → drift review. I will design for deterministic provenance around a probabilistic classifier, not pretend the classifier is truth. I also want to know whether a drift finding blocks a merge.

INTERVIEWER

Clarify requirements and the first release.

CANDIDATE

V1 supports selected branches for five major languages, exact and semantic search, approved artifact-to-symbol links, webhook-driven incremental indexing, and PR findings with evidence. Admins can revoke a repository. A reviewer can confirm, dismiss, or suppress a finding and that decision becomes evaluation data. I exclude code writes, merge gating, full build execution, and semantic equivalence proofs. I would ask about retention after unlink; my default is immediate query revocation and a configurable asynchronous purge.

  • Hard invariant: tenant and repository authorization is checked before retrieval and again after ranking.
  • Product truth: every result states commit SHA and index freshness.
  • Safety: no autonomous merge blocking until calibrated per tenant.
INTERVIEWER

Do a back-of-the-envelope estimate.

CANDIDATE

The initial 1.2B LOC is a bulk backfill, so isolate it from the live lane. At a mock effective 20,000 LOC/s per parser worker, 100 workers parse 2M LOC/s: about 10 minutes of pure parse time, but fetch, language variance and graph writes dominate, so I budget hours and expose progress. The steady state is modest on average: 25,000 pushes/day is 0.29/s, but a 15× burst and large monorepos make per-event averages misleading. I size queues by changed bytes and files, not event count. Search at 400 QPS needs independently scalable replicas.

25,000 / 86,400 ≈ 0.29 pushes/s average
Burst ≈ 4.3 pushes/s
1.2B LOC / (100 × 20k LOC/s) ≈ 600 s raw parse floor
INTERVIEWER

Show your data model and access patterns.

CANDIDATE

Every repository record is tenant-scoped. CommitSnapshot is immutable and keyed by repository plus commit SHA. FileVersion references content by blob SHA so unchanged files deduplicate. Symbols are immutable within a commit; stable lineage is a separate mapping because a rename can break identity. ArtifactRevision is append-only after approval. TraceLink pins both an artifact revision and a symbol at a commit, never a moving branch. DriftFinding records the complete analysis manifest: input hashes, parser/rule/model versions, evidence spans and decision.

  • Search by tenant + authorized repo set + query + commit/default-branch projection.
  • Incremental index by repo + commit; compare parent manifest to enumerate changed blobs.
  • Audit by finding ID → analysis run → exact artifact revision and code spans.
INTERVIEWER

What APIs matter?

CANDIDATE

Repository creation and pull analysis are asynchronous and return durable operation IDs. Webhook ingestion acknowledges only after the signed raw envelope is durably persisted. Search accepts a commit or a branch projection and returns indexedThrough so clients can distinguish no match from stale index. Mutations use idempotency keys and optimistic etags. Review endpoints require a reason because dismissals are product signal, not just UI state.

INTERVIEWER

Walk one push end to end.

CANDIDATE

The edge verifies provider signature, installation ID and replay window, stores the envelope with provider delivery ID, then returns 202. A sequencer resolves the commit DAG rather than trusting webhook arrival order. The snapshot worker fetches changed manifests and blobs using a short-lived provider token, hashes all inputs, and publishes a CommitSnapshot. Language workers parse changed files in sandboxes, update symbol and edge segments, then atomically advance the branch IndexProjection from the parent commit to the new commit. Search fans out only to segments visible under the request permission epoch. Drift workers compare the PR diff and impacted symbol neighborhood against approved artifact revisions, run deterministic candidates first, then a bounded model judge, and persist evidence before posting one summary comment.

  • Control plane: tenants, connections, policies, operations.
  • Data plane: fetch, parse, index, analyze.
  • Reconciliation periodically compares host heads with branch projections.
INTERVIEWER

Deep dive: how is incremental indexing both fast and correct?

CANDIDATE

I use content-addressed blobs and immutable per-commit segments. For a normal commit, diff the manifest against indexed parents, parse changed blobs, recompute local symbols, then invalidate dependent edges using the prior reverse-dependency graph. A merge commit may require both parents; if ancestry is missing or a force-push occurs, mark the projection degraded and schedule a bounded subtree or full rebuild. Publishing is a compare-and-swap on branch projection: only point search to commit C after all required lexical, symbol and ACL segments for C are ready. Semantic embeddings may lag but advertise their own freshness.

  • Never mutate the only good index in place.
  • Use parser-version namespaces so a bad release can roll back.
  • Large generated/vendor paths follow explicit policy and are visibly excluded.
INTERVIEWER

Deep dive: what exactly is drift?

CANDIDATE

Drift is a typed, evidence-backed hypothesis. First, deterministic checks find broken contracts, removed referenced symbols, missing acceptance-test IDs or changed API schemas. Second, impact expansion retrieves the smallest symbol and artifact neighborhood. Third, a model may classify a semantic mismatch, but it must cite artifact clauses and diff lines. A calibrator thresholds per finding class and tenant; low-confidence cases are omitted or shown only in a dashboard. Dismissal reasons feed an offline labeled set. The PR comment is capped and links to a review page so the bot does not spam.

  • Precision matters more than recall for intrusive PR comments.
  • Evaluate by class, language and repository—not a single aggregate score.
  • Re-run must pin prompt, model snapshot when available, retrieval manifest and temperature.
INTERVIEWER

How do consistency and idempotency work?

CANDIDATE

Strong consistency is reserved for repository authorization, permission-epoch changes, artifact approval, branch projection publication, finding review and billing. Derived search indexes are eventually consistent and disclose freshness. Provider delivery ID dedupes webhooks; index work is keyed by repo + commit + parser bundle; analysis is keyed by repo + PR head SHA + policy bundle. Every stage writes outputs before committing its state transition, so at-least-once delivery is safe. A unique constraint and compare-and-swap close race windows.

INTERVIEWER

Failure injection: duplicate webhooks arrive out of order, then a force-push removes commits. Revise.

CANDIDATE

I do not sequence by arrival time. I ingest all valid envelopes, query the host for canonical refs, and construct the commit DAG. Duplicate delivery IDs are no-ops; a different event for an already indexed SHA can update observation metadata without rebuilding. On force-push, create a new branch projection generation and stop advertising the orphan head. Immutable orphan segments can remain for retention/audit but are unreachable from current search unless explicitly pinned. A reconciler detects gaps or missed webhooks by polling branch heads. The UI shows indexing state rather than serving the old head as current.

INTERVIEWER

How do you handle backpressure and giant monorepos?

CANDIDATE

Queues carry cost estimates such as changed bytes, file count and language, not only FIFO messages. Separate live PR, normal push and backfill pools with weighted fair scheduling per tenant. Cap concurrent fetches per provider installation to respect API limits. Chunk monorepos by dependency-aware directory partitions, checkpoint manifests, and coalesce superseded branch pushes while preserving every requested audit snapshot. Search capacity is isolated from indexing. If the seven-minute PR target is at risk, run deterministic checks on the diff first and label deeper semantic analysis pending.

  • Per-tenant token buckets prevent a single backfill from starving others.
  • Dead-letter only after bounded retries; retry from the last immutable checkpoint.
  • Circuit breakers protect provider and model APIs.
INTERVIEWER

Failure injection: access is revoked halfway through indexing. What changes?

CANDIDATE

Revocation increments the repository permission epoch in the strongly consistent control store. Query authorization immediately excludes the repo, caches key by permission epoch, and workers check the lease epoch before publishing. The fetch token is revoked and queued jobs are cancelled. Any output computed under an old epoch is quarantined and cannot advance a projection. Then a deletion workflow tombstones index segments, vector entries, cached snippets and model-context artifacts according to policy; an audit record proves completion. Logs retain identifiers and hashes without source content where regulation permits.

INTERVIEWER

Security and tenant isolation?

CANDIDATE

Use provider-app installation tokens with least privilege and short lifetime; never persist user PATs in workers. Encrypt repository locators and source at rest with tenant-scoped keys. A policy service returns authorized repo IDs and permission epoch; retrieval pushes that filter into lexical, vector and graph queries and post-filters results. Sandboxed parsers have no network and strict CPU/memory limits because repositories are adversarial input. Strip secrets before model calls, support provider allowlists or private inference, and defend against prompt instructions embedded in code by treating code as data. Audit admin connections, searches, exports and agent context assembly.

  • Isolation tests deliberately plant canary symbols across tenants.
  • Logs never contain raw source by default.
  • Signed outbound PR comments bind repo, PR and analysis run.
INTERVIEWER

What do you measure, and how do you roll this out?

CANDIDATE

Platform SLIs include webhook durability, head-to-search lag, queue age by lane, index publish success, query latency/availability, authorization denials, purge age and cost per changed KLOC. Quality uses a blinded labeled set: precision/recall by finding class, reviewer confirmation rate, time to decision, dismissal reason, comment suppression and reproducibility success. Roll out search first, then silent drift shadowing, then dashboard-only findings, then opt-in PR comments with a per-repo kill switch. Start with high-precision deterministic classes and expand after calibration.

  • Alert on freshness SLO burn, permission-fence violation, model drift and reviewer complaint rate.
  • Canary parser bundles on sampled repos before projection promotion.
  • Compare confirmed bugs found against reviewer fatigue.
INTERVIEWER

Name trade-offs and traps.

CANDIDATE

A graph database is not automatically required; commit-local adjacency segments plus a relational control plane may be simpler. Vector search alone loses exact identifiers and provenance, so hybrid retrieval wins. Reindexing the world on every push misses the incremental requirement. Mutating indexes in place makes rollback unsafe. Treating model output as drift truth creates false-positive fatigue. Hiding index freshness lies to users. Finally, unlinking a repo must have explicit visibility and deletion semantics—disconnect is not the same as purge.

INTERVIEWER

Give me your one-minute recap.

CANDIDATE

CodeScope stores immutable repository snapshots and approved artifact revisions, then builds versioned, tenant-fenced search and graph projections. Signed webhooks feed an at-least-once, cost-aware pipeline; content hashes and commit keys make it idempotent. Search always reports commit and freshness. Drift begins with deterministic evidence, uses models only as a reproducible classifier, and keeps humans authoritative. Permission epochs stop revoked data immediately; reconciliations repair missed events. I would ship search, shadow drift, dashboard findings, then carefully calibrated PR comments, measuring both SLOs and reviewer trust.

Two places to earn the strong hire

These mechanisms are the interview’s differentiators. Be able to redraw each from memory and defend its failure behavior.

01

Deep dive A · Versioned index publication

A branch name is mutable; a commit is not. Build immutable commit segments, then publish one small branch pointer only after the required segment set is complete.

  1. Manifest diff identifies changed blobs
  2. Parser namespace isolates extractor versions
  3. CAS prevents an older run overwriting a newer head
  4. Lexical, graph and semantic freshness can advance separately
  5. Reconciler compares host refs with projections
02

Deep dive B · Evidence ladder for drift

Move from high-precision deterministic facts toward probabilistic semantic judgments, preserving the input manifest at every rung.

  1. Broken trace or API contract
  2. Impacted symbol neighborhood
  3. Retrieved approved clauses
  4. Bounded model classification with citations
  5. Human review and suppression feedback

Revise, do not hand-wave

When the interviewer injects a fault, restate the violated assumption, change state or protocol, and name the new invariant.

InjectionRecovery mechanismTempting wrong answer
01Webhook replay/out of orderProvider delivery dedupe + resolve canonical DAGDuplicate business effect
02Force-pushNew projection generation; keep orphan snapshots per retentionOld head shown as current
03Parser regressionVersioned namespace, canary, rollback projectionCorrupting only good index
04Provider rate limitToken bucket, jitter, live/backfill lane isolationRetry storm
05Repo revokedPermission epoch fence, synchronous hide, async purgeData survives in vector/cache
06Model unavailableServe deterministic checks; mark semantic analysis pendingBlocking PR workflow

Calculate before you provision

Use orders of magnitude to expose the bottleneck. State what this simple model omits.

Index freshness lab

Change mock workload and see whether the live indexing lane can meet the five-minute target.

Estimated raw parse timeChange an input to recalculate.
Fetch
Parse
Graph
Publish

Prove quality in production

A system is incomplete without observable user outcomes, staged deployment, rollback and an answer to “how will we know?”

Scoreboard

  • Head-to-search lag p50/p95/p99
  • Search p95 and zero-result rate
  • Finding precision by class
  • Reviewer confirmation and suppression
  • Permission-fence violations (target zero)
  • Cost per changed KLOC

Rollout ladder

  1. 01Exact symbol search on two languages
  2. 02Incremental indexing + visible freshness
  3. 03Silent deterministic drift evaluation
  4. 04Dashboard-only mixed findings
  5. 05Opt-in capped PR comments
  6. 06Tenant-specific calibration and expansion

Corrections worth memorizing

Use these as flash cards. The right column is the compact sentence you want available under pressure.

TrapBetter move
Calling a branch authoritativePin snapshots and links to commit SHA.
One giant mutable indexPublish immutable versioned segments.
Vector search for identifiersHybrid lexical, symbol and semantic retrieval.
Trusting webhook orderReconcile against the host commit graph.
“Exactly once” hand-waveAt-least-once transport + idempotent effects.
No revocation storyPermission epochs plus complete derived-data purge.

Vocabulary without fog

Define the term, then connect it to a concrete invariant in this design. Avoid dropping vocabulary as a substitute for reasoning.

AST
Abstract syntax tree: a parser’s structured representation of source.
Symbol
Named program element such as a class, function, type or constant.
Projection
Rebuildable current view derived from immutable source events/snapshots.
Permission epoch
Monotonic version fencing caches and workers after access changes.
Drift
Evidence-backed mismatch hypothesis between approved intent and implementation.
Content addressing
Identifying bytes by a cryptographic hash to deduplicate and verify them.
CAS
Compare-and-swap: update only if the expected version is still current.
Reconciliation
Periodic comparison of desired/canonical state with derived state.

Close with a decision, not a component list

CodeScope stores immutable repository snapshots and approved artifact revisions, then builds versioned, tenant-fenced search and graph projections. Signed webhooks feed an at-least-once, cost-aware pipeline; content hashes and commit keys make it idempotent. Search always reports commit and freshness. Drift begins with deterministic evidence, uses models only as a reproducible classifier, and keeps humans authoritative. Permission epochs stop revoked data immediately; reconciliations repair missed events. I would ship search, shadow drift, dashboard findings, then carefully calibrated PR comments, measuring both SLOs and reviewer trust.

Rehearse again