crates/lucisv_mcp/src/cache.rs: at startup `--index-cache DIR/index-cache` (the language server's store) is read READ-ONLY — header CACHE_FORMAT/FACTS_FORMAT/version must match this build or the store is ignored with one stderr line; each record line's checksum verified, decoded, keyed by (record path, content hash) and used only for a discovered file whose bytes hash to it, through IndexBuilder::add_facts instead of a parse; the server never writes that file. Its own `index-cache-mcp` is written once at exit, atomically, in the same codec (a test pins the restated framing against index_cache.rs's source). opentitan: cold 1.9 s → warm 0.8 s (walk 210 ms + merge 204 ms are the floor). delete_item with force may remove an item holding `define/`undef, warning which macros went (M4's ruling); INSTRUCTIONS names the read tools, the edit tools, dry_run and diagnostics. Closing docs: docs/topo.md gains the lucisv_mcp node and its six edges, the mcp-packaging spawn/packaging rows, the read-only cache row and §2.9 rows 35–42 (MCP-5/6/7/8/10/11/12/13 and the parser leniency the M3.5 verifier exposed); repository-analysis map row and nine-crate count; README architecture row; CLAUDE.md measurement for the new crate. QA (Opus; interrupted by the owner moving the machine, verdict pass so far): swapped/stale/foreign/deleted/off-by-one-header/CRLF stores skipped, the editor's store byte-identical through a session, SIGKILL mid-write harmless, a 231 MB store linear, fingerprint parity over the whole checkout; two low items open — the README threat model reworded, and an orphaned `.tmp` after a kill between write and rename to be swept in the census round. Gates: fmt, clippy clean; lucisv_mcp 318 passed; the dev's workspace run 4 858 passed on the same code. Co-Authored-By: Claude Fable 5.1 <[email protected]>
23 KiB
mcp-cache-and-census
Lane M6 of the MCP block (TODO-MCP.md, docs/mcp/PLAN.md §6 and §8):
the index cache reuse, the startup and per-call timings, the M4 review's
rule-6 ruling, the first revision of the initialize instructions — and,
the lead's half, the token census and the closing release.
Goal
A coding agent's first question to lucisv-mcp pays for the index build:
1.9 s on opentitan, every session. The language server has already parsed
the same files and persisted one FileFacts record per file, keyed by the
file's content hash (lucisv_server::index_cache). This lane lets MCP
start from those records — read only, never written — and from a store of
its own in the same codec, so a warm start skips the parse of every file
whose bytes a record was read from. A record can only ever stand in for the
parse of exactly the bytes it was read from, so the cache is a performance
input and never a correctness one: a torn, damaged, foreign or stale record
costs a parse and nothing else.
Assumptions
- Where. Only
--index-cache DIRturns the caches on (the extension passes VS Code'sstoragePath, the directory the language server writesindex-cachein). No OS-cache-dir fallback: without the flag MCP starts cold, as before. The directory may not exist yet (M5 QA F4: VS Code createsstoragePathlazily) — that is a silent cold start. - Read. At startup
cache::Records::loadreadsDIR/index-cache-mcpand thenDIR/index-cache(so a record both hold is credited to the editor). A store is used only when its first line is exactly this build's headerlucisv-index-cache\t2\t<FACTS_FORMAT>\t<version>; any other first line ignores the store whole with one stderr line; a missing or empty file is silent. Each record line ishash\tfacts\tchecksum; a line whose hash or checksum is not 16 hex digits, whose checksum is not the FNV-1a of the facts field, or which is not UTF-8 is skipped — that covers a torn last line (a writer killed mid-append) and a record edited after it was written. Records are keyed by(record_path, content hash). - Use. For each discovered file, MCP reads and hashes the bytes (it
must anyway: the stamp and the freshness sweep need the hash). When
(canonical path, hash)has a record thatFileFacts::decodes to the same path,IndexBuilder::add_factstakes it instead ofadd_file. A record under another path (the language server's paths are whatever the editor handed it; MCP's are canonical) is a miss, not a translation. - Write — only our own store. On EOF (the host closes stdin) the
server writes
DIR/index-cache-mcp: the same header, then one record per indexed file — the facts the index holds, under the hash in the file's stamp (both come from the same read, so they describe the same bytes), in path order. Atomic: aindex-cache-mcp.<pid>.tmprenamed over the store; a failure removes the temp file and is one stderr line (cannot write the index cache: …); the session ends either way. The directory is created if missing, and gets a.gitignoreof*when it has none (the language server does the same).DIR/index-cacheis never opened for writing:cache.rshas no code path that names it exceptfs::read, andtests/cache.rshashes it before and after whole sessions. - Not written: a session that never answered a tool call (no project was built), or a session killed rather than closed. Two MCP servers on one directory each rename their own complete store over the file: last writer wins, both stores are whole.
- The stderr line is
lucisv-mcp: indexed N files in M ms (E from the editor's cache, O from its own)when--index-cacheis given, and the old line without the parenthesis otherwise.Mnow includes the index merge (IndexBuilder::finish), which the M1 line left out — the number went up by the merge's ~200 ms on opentitan; the build did not change. - The codec is restated, not shared.
index_cache.rs'sFILE,CACHE_FORMAT, header and line formats are private tolucisv_server(a binary crate MCP must not depend on — PLAN §4.1).cache.rsrestates them;cache::tests::the_codec_is_the_language_servers_ownreadscrates/lucisv_server/src/index_cache.rsat test time and fails if any of the five pinned source lines changes (Handshake MCP-14). - Rule 6, the M4 ruling.
delete_itemwithforce: truemay remove an item that holds`define/`undefentries (a module with a`definein its body, analwayswith one nested): the deletion passes rule 6 and the answer carries the warningdeleted macro definitions: Q, W (undef) — code after the item that used them will change meaning(each name once, in source order,(undef)for an`undef). Withoutforcethe refusal stands and now ends, or passforce: trueto delete it anyway.replace_itemandinsert_itemtake noforceand are unchanged. The verifier change is local:Expect::Nothing { force }, andOutcome::dropped_macros. - The instructions (
rpc.rs, 787 characters, pinned ≤ 900 by a wire test) name the read tools to prefer over reading files, that edits are verified, all-or-nothing, on disk withdry_run, the item tools vs the design-wide ones,diagnosticsto check, and the path/column units. The lead revises them after the census.
Handshakes
Consumed (unchanged, read only): vlog_semantic::{FileFacts::{encode, decode, path}, record_path, FACTS_FORMAT, IndexBuilder::{add_facts, add_file, finish}, WorkspaceIndex::{facts_for, fingerprint}};
lucisv_core::cache::content_hash; the byte format of
lucisv_server::index_cache (below).
Promised: Project::open_cached(roots, filelist, cache_dir) (the old
Project::open is now the tests' uncached shorthand), Project::save_cache,
Project::reuse. rpc.rs calls them in open_project and on EOF.
Filed:
- MCP-14 →
lucisv_server(informational + one request). MCP reads the server'sindex-cacheread-only (fs::read, never a write handle) and writesindex-cache-mcpbeside it in the same codec. Nothing in the server changes. Request (not blocking): the codec constants (FILE,CACHE_FORMAT,header(),line()/parse_entry) are private to a binary crate, so MCP restates them and pins the restatement against the source text; lifting the codec (not the store) intovlog_semanticorlucisv_coreas a pure move would let both sides share one definition and retire the pin. Until then, a change to the store's framing must bumpCACHE_FORMATand updatecrates/lucisv_mcp/src/cache.rs— the pin test fails otherwise. - MCP-7 →
vlog_refactor: status unchanged (open).renamestill hands the engine the whole set: 2.23–2.28 s per dry run on opentitan (below), the cost MCP-7'sKnownFactsvariant (or passing the index's facts torename_traced_with, which already takes&dyn KnownFacts) would remove. That is an M3 tools change, not this lane's. - Out-of-ownership edit, flagged for the lead:
tests/qa_m4.rsqa_recheck_a_define_item_may_be_inserted_but_not_nested_in_an_alwayspinned "a forced delete of a module holding adefine is refused" — the exact behaviour the M4 review ruled to change. The loop overforce ∈ {false, true}became the unforced refusal plus a forced dry run that must succeed and nameLOCAL(8 lines, comment says why). Without itcargo test -p lucisv_mcp` is red. - For the lead (docs outside this lane): the M1 README's Assumption
"
--index-cache DIRis accepted and stored, and unused until M6" is now stale;docs/mcp/PLAN.md§6 matches what was built.
Status / TODO
cache.rs: read-only reader of the editor's store (header, per-line checksum,record_path,decode), keyed by path + content hash- warm start:
add_factson a hit, parse on a miss; hit counts on the stderr startup line - own store
index-cache-mcp: same codec, written atomically on EOF, read on start; a write failure is one stderr line - F4: a missing directory is a silent cold start
- unit tests (
src/cache/tests.rs): the codec pin; warm from the editor's store = cold fingerprint; own store round trip = cold fingerprint; a changed file misses; torn / damaged / foreign records each a parse; a record under another path or hash not taken - wire tests (
tests/cache.rs): the editor's store byte-identical (hash + mtime) after a session that indexes, answers and edits, with a damaged and a torn record skipped; another version's store ignored with one line; missing directory → cold, own store written, next start warm from it, a changed file re-parsed and answered new; an unwritable directory (0555) → answers, one stderr line, nothing written - opentitan timings (
tests/opentitan.rs, ignored): cold / warm from own store / warm from the editor's store, exit write, stat sweep, whole-setrename - rule-6 ruling:
forcerelaxes rule 6 ondelete_itemwith the warning; wire test + attack test INSTRUCTIONSfirst revision (≤ 900 characters, wire-tested)docs/perf/README.mdMCP entry- token census, instruction revision after it, topo, CHANGELOG, release — the lead's
Timings
Release build (cargo test --release -p lucisv_mcp --test opentitan -- --ignored --nocapture opentitan_startup), macOS arm64, the whole opentitan
checkout (3 944 indexed files, 3 over 1 MiB skipped), two runs; the
checkout's git status --porcelain identical before and after. The stores
live in a scratch directory outside the checkout; the "editor's store" is
the own store renamed to index-cache — the same bytes the language server
would write (46.3 MB), which is what the codec pin guarantees.
| what | wall |
|---|---|
cold start, no store (first project_overview) |
1 854–1 887 ms (build 1 800–1 880 ms) |
| warm from its own store | 837–847 ms (build 821–840 ms, 3 944 hits) |
| warm from the editor's store | 821–832 ms (build 814–824 ms, 3 944 hits) |
exit, writing index-cache-mcp (46.3 MB) |
251–272 ms |
per-call freshness sweep (outline of a cached file, median of 21) |
5.6–6.1 ms |
— the transport floor (tools/list, median of 21) |
0.38 ms |
rename op_i → cipher_op_i at hw/ip/aes/rtl/aes_cipher_core.sv:123, dry_run, whole set |
2 227–2 276 ms (first and second call alike) |
Where a warm build's ~820 ms goes (one instrumented run, not committed): walk 210 ms, reading the store 87 ms, reading + hashing + decoding 3 944 files 318 ms (1 387 ms when each is parsed instead), the index merge 204 ms. The walk and the merge are the floor a cache cannot remove.
Token census (lead)
Work log
2026-09-23 (dev, Opus). Built as briefed, in the owned files plus the
two flagged edits (rpc.rs wiring beyond INSTRUCTIONS; tests/qa_m4.rs).
cache.rs(118 production lines):Records::load/take,write_own, the restated header/line codec,store_linesreading bytes a line at a time exactly as the language server does (a torn multi-byte character costs one line).Reusecounts hits by source.project/mod.rs:open_cached+ aloadhelper (read, stamp, take a record or parse);save_cachebuilds(stamp.hash, index.facts_for)per file;reuse(). Deviation: the build clock now stops afterfinish()— the old code read the clock before the merge ran inside the struct literal, so every "indexed in M ms" since M1 left out ~200 ms on opentitan.Project::openbecame#[cfg(test)](its only callers are tests; clippy's dead-code lint otherwise).rpc.rs:open_projectcallsopen_cachedand prints the counts;Line::EofcallsServer::finish, which saves (verbose: a line with the record count; failure: one line always). Deviation: the brief listedrpc.rsforINSTRUCTIONSonly, but the startup line and the EOF write live there; the change is those two call sites.verify.rs/item.rs: the rule-6 ruling (above);delete_item's description andforceparameter say so.- Unit tests live in
src/cache/tests.rs(the fingerprint oracle needsProject, which atests/file cannot reach in a binary crate). - The own store is rewritten on every exit even when unchanged (~260 ms on opentitan, after the last answer): simple, and a store the host kills us during is still the previous whole store.
- Tests:
lucisv_mcp290 → 302 passing (+5 unit, +4tests/cache.rs, +3 wire), ignored 2 → 3 (the opentitan timing test); workspace 4 846 → 4 858.
QA log
2026-09-23 (QA, Opus) — QA — interrupted (the session was cut off before the workspace gate finished; everything below was run and is recorded as measured).
The cache half of the M6 QA line. Verdict so far: pass;
no wrong record served, the editor's store never written. Two non-blocking
findings (one doc, one inherited leak). The census spot-check waits for the
census. Tests in crates/lucisv_mcp/tests/qa_m6.rs (16 pass, 1 ignored =
finding 2), each spawning the real binary over a scratch copy of the
design fixture.
Wrong-record hunt (blocking class — nothing found).
- Swapped records, checksums recomputed (
leaf.sv's hash carryingtop.sv's facts and the reverse): not served. The key is(record_path of the facts, hash)andtakecompares the decoded path again, so each lands under (other path, this hash) and matches no file — 5/7 hits, the probe's nine answers equal a cold start's. Also run on a copy of opentitanhw/ip/{aes,prim}with a real language-server store (prim_fifo_sync↔prim_fifo_async): 391/393 hits, both interfaces right. - Inherited, documented limit (not a finding against the code): a
record relabelled —
prim_fifo_async's facts withprim_fifo_sync.sv's path, underprim_fifo_sync.sv's real hash, checksum recomputed — is served (393/393 hits;unit_interface prim_fifo_syncanswers "not indexed") and is then re-laundered intoindex-cache-mcpwith a fresh checksum. The language server does exactly the same:index_cache.rs's module doc states the same-user/same-disk threat model (FNV-1a is not a MAC; whoever can write the store can write the sources). Accidental damage cannot produce this shape. See finding 1 for the doc. - Records for a deleted file and for a file outside every root (it exists
beside the root): neither module listed, neither record written back
(own store = header + 7). Two records for one path under two hashes
(the append log's normal shape): the one whose hash is the bytes on disk is
served, older or newer; two for one
(path, hash): the later line wins, as inIndexCache::open(tested with a checksum-valid wrong record first and the honest one last). - CRLF store:
\rstripped exactly as the language server strips it, 7/7 hits, answers = cold. Header near-misses — version patch + 1,FACTS_FORMAT± 1,CACHE_FORMAT1 and 3, a trailing space, a BOM, a fifth field: each ignored whole with exactly one stderr line, store byte-identical. Empty store, header-only store, a directory namedindex-cache: silent cold starts (stderr = the startup line only). - A 231 MB store (opentitan's 46 MB store + 4 copies under
/ghostNpaths, checksums valid), release build, 3 944 files: build 892 / 937 / 1 026 / 1 203 ms at 46 / 92 / 138 / 231 MB — linear (~1.7 ms/MB); peak RSS 407 → 750 MB (the store bytes plus every record's string are held until the load ends); the store byte-identical after each run.
Read-only promise and the own store's writes.
- The editor's store at mode 0444, in a live server's between-compactions
shape (reversed path order, a duplicate line, a torn line mid-file, a
checksum-failing line), through a session that indexes, answers, runs
format(writes a file) and ends: bytes, mtime and mode identical, 7/7 hits. On the realaes+primLSP store:shasumidentical after a warm session. Code:cache.rsnamesEDITOR_STOREonly inRecords::load→fs::read;write_ownwrites onlyindex-cache-mcp, its temp file and.gitignore(when missing — as the language server does). - Killed sessions (SIGKILL): after an answer and before EOF (fixture, with
a changed file that would have changed the store): the previous own store
byte-identical, no temp file, the next start re-parses the changed file.
On opentitan, killed at 20–350 ms after EOF (11 delays): own store
intact, no temp. Killed the instant
index-cache-mcp.<pid>.tmpappeared: store intact, a 9.4 MB temp file left behind for good → finding 2. --index-cachenaming a regular file: answers right, onecannot write the index cacheline, the file untouched. A directory namedindex-cache-mcp: silent read miss, one line at exit, no temp left. Cache directory mode 000 holding an honest store: cold start, the nine probe answers equal cold's, one line at exit, store untouched. (A startup that cannot read a store is silent — only the exit's write failure speaks. Acceptable for a performance input; noted, not filed.)
Parity.
- The nine-answer probe (
list_units, twounit_interface, twooutline,search_symbols,references,hierarchy,defines) is identical cold, warm from the editor's store and warm from the own store. - A real language-server store (release
lucisv-serverdriven over stdio on a copy ofhw/ip/{aes,prim},index.scope = workspace,storagePath= scratch; 393 records, 2.69 MB): MCP warm start 393/393 editor hits, and — the stronger check — a cold MCP session'sindex-cache-mcpover the same tree is byte-identical to the server'sindex-cache: same header, same facts, same order. WorkspaceIndex::fingerprint(throwaway unit test in a scratch copy of the crate, not committed): warm-from-LSP-store = cold onaes+prim(393 files); warm-from-own-store = cold on the whole opentitan checkout (3 944 files, fingerprint 37.2 MB); the checkout'sgit status --porcelainidentical before and after every run.- Same-size edit (
held→hold) since the store: re-parsed, the outline showshold; a new file since the store: indexed; 6/7 hits.
Rule 6 (the M4 ruling). A module holding `define LOCAL twice and a
nested `undef GONE, read by the module after it: without force
refused (names rule 6 and force: true), file byte-identical; forced: the
warning reads deleted macro definitions: LOCAL, GONE (undef) — … (each
name once, source order), every byte before and after the item's lines is
the original's. force on an item with no macro says nothing about
macros. The tests/qa_m4.rs diff is exactly the ruling's assertion swap
(the force ∈ {false, true} refusal loop → unforced refusal + forced dry
run naming LOCAL), nothing else. The code: Expect::Nothing { force };
for a deletion same_macros can only fail when the region held a
definition, which is exactly what dropped lists — force cannot excuse
anything else.
Instructions. 787 characters (≤ 900). Names unit_interface, outline,
read_item, list_units, search_symbols, definition, references,
hierarchy, the three item tools, rename, add_port, remove_port,
format, fix_lint, diagnostics — every one in tools/list, and no
snake_case word that is not a tool (dry_run aside); says disk-only,
root-relative paths, 1-based byte columns.
Sizes. Production lines: cache.rs 118, project/mod.rs 289, rpc.rs
265, tools/item.rs 389, tools/item/verify.rs 388 — all under 600.
Timings (release, whole opentitan, this machine, tests/opentitan.rs).
Cold 1 769 ms build (first call 1 776 ms); warm own 833 ms; warm editor's
807 ms; exit write 243–260 ms; sweep median 4.9–5.0 ms (floor 0.35 ms);
rename dry run 2 152–2 172 ms. Consistent with the dev's table.
Findings.
- (low, doc)
docs/features/mcp-cache-and-census/README.mdGoal: "a torn, damaged, foreign or stale record costs a parse and nothing else" overclaims — a forgery that recomputes the FNV-1a checksum is served (reproduction above; the language server has the same property by design). Fix: say "a torn, damaged, foreign or stale record", and add the threat-model sentence the server'sindex_cache.rsmodule doc carries (same user, same disk; the checksum catches damage, not intent) to Assumptions → Read. No code change. - (minor, inherited)
crates/lucisv_mcp/src/cache.rs:140-146(write_own): a process killed betweenfs::write(tmp)and the rename leavesindex-cache-mcp.<pid>.tmp(9.4 MB on opentitan) that no later session removes — one per crash, each up to the store's size. Harmless to correctness (only the exact store names are read). Same leak as the language server's, filed by its QA 2026-08-27 (an_orphaned_compaction_tmp_file_is_never_swept_up). Pinned byqa_an_orphaned_temp_file_is_swept_by_the_next_write(ignored). Fix: before writing, removeindex-cache-mcp.*.tmpfiles indirolder than a few minutes (a concurrent writer's live temp file is seconds old).
Gates (through tools/guard.sh, one at a time): cargo fmt --all -- --check clean; cargo clippy --workspace --all-targets clean (no
warnings); cargo test -p lucisv_mcp 318 passed, 0 failed, 4 ignored
(302 + 16 QA; ignored: 2 opentitan, M3 finding, M6 finding 2); the
opentitan tests (release, --ignored) 2 passed, checkout unchanged;
cargo test --workspace NOT completed — cut off after ~16 minutes, mid-run (reached vlog_refactor, corpus, inline test binaries; every result line captured before the cut-off was ok, no failure seen).
Not yet checked: the full cargo test --workspace count (needs ≥ 4 858 + 16 = 4 874 passing); the census transcripts spot-check (the census has not been run — the lead's half); a whole-opentitan store written by the language server itself (only aes+prim was; whole opentitan was checked with MCP's own store). The M6 QA box in TODO-MCP.md is left unticked.
Review
Lead, 2026-09-23 (M6, committed at the owner's move). The reader keys a
record on the file's content hash and the record's own path, never writes
the editor's store, and a warm start on opentitan halves the startup (1.9 s
→ 0.8 s; the walk and the merge are the floor). QA (interrupted by the move,
verdict pass so far): swapped, stale, foreign-path, deleted-file, off-by-one
header and CRLF stores all skipped; the editor's store byte-identical through
a session; SIGKILL mid-write leaves the previous own store intact; a
231 MB store loads linearly; fingerprint parity with a cold build over the
whole checkout. Two low items: the README's threat model now says
"damaged", not "forged" — a record with a recomputed checksum is used,
exactly as the language server uses it, because whoever can write the store
can write the sources; and an orphaned index-cache-mcp.<pid>.tmp after a
kill between write and rename is not swept (QA's ignored test
qa_an_orphaned_temp_file_is_swept_by_the_next_write) — to be fixed in the
first census round. The forced-delete ruling (rule 6) and the first
INSTRUCTIONS revision landed here; the census revises the instructions
again. The full workspace suite was still running when the machine moved;
the dev's run on the same code passed 4 858 and QA's crate suite 318.