25 KiB
Implementation Plan: 0.52.0 Performance Review Follow-Up
Executive Summary
An independent review of release 0.52.0 (commit 3ceba21) confirmed major performance improvements over 0.51.0 (e.g., unchanged menu filtering reduced from 24.3 ms to 0.32 ms, queued definition unblocked from 24.4 ms to 0.29 ms, no-symbol preflight reduced from 2.2 s to 0.22 ms, tail rename cut by 17.1%, and server-reported loaded scan time cut by ~58%).
However, the review uncovered one correctness defect (F1) and two benchmark measurement defects (F2, F3), alongside five architectural guidance points and three unmeasured candidate performance areas (N1, N2, N3):
- F1 (P2 Correctness): Split startup discovery duplicates modules behind directory aliases (symlinks), breaking startup/rescan equivalence and blocking valid renames until a full rescan.
- F2 (P2 Harness): Standalone
scanloadon a fresh storage directory includes an unprimed cold trial under a warm label (0 hits / 3,974 misses). - F3 (P2 Harness):
scanloadcompletion and mid-scan classifications conflate client request window chatter with true scan completion. - Architectural & Performance Next Actions (Items 3–5 & N1–N3):
- Item 3 / N1: Retain the lint snapshot; target the remaining 114 ms first-after-edit cost via dirty-buffer lexer/parser/analysis work reduction.
- Item 4 / N2: Retain engine-owned preflight and content-tied
KnownFactsreuse; target the 163 ms scope construction (31 ms store decode) and the 1,251-file / 2.88 s common-port rename (clk_i). - Item 5 / N3: Retain startup ordering and publication cadence (subject to F1); target publication merge cost (
WorkspaceIndex::absorb) before considering tighter publication intervals.
This plan details the technical design, contracts, verification matrix, and sequencing to address these findings without regressing existing performance or breaking repository invariants.
User Review Required
Important
Zero Source Code Changes in This Planning Phase: As requested, no source code, test, or harness files have been modified. Execution requires explicit approval of this implementation plan.
Warning
F1 Fix Strategy (Directory Identity & Path-Selection Contract): Split startup discovery was introduced to provide immediate responsiveness (78 ms cold / 114 ms warm first answer) by leading with open buffer folders. When a directory has symlink aliases sorting before its real path (e.g.
a_alias -> z_real), split discovery cannot unilaterally pickz_realwithout diverging from the canonical root walk which selectsa_alias. The approved strategy is:
- Share directory identity (
DirId) between the neighbourhood walk and root walk.- If an alias sorting before the target is detected (or equivalent path selection cannot be proven ahead of the root walk), execute a bounded fallback to the full single root walk (which runs in <1 ms on test fixtures and ~158 ms on OpenTitan), ensuring 100% path and declaration equivalence across startup, rescan, and restart.
Technical Analysis of Findings & Next Actions
1. F1: Split Startup Discovery Duplicates Modules Behind Directory Aliases
- Location:
crates/lucisv_server/src/state/discover.rs:429-560(first_scope,neighbourhood_files,walked_rest,rest_of_scope), andcrates/lucisv_core/src/walk.rs:121-164(collect_files_below). - Mechanism:
- Regular single root walk maintains
Walk.visited: HashSet<DirId>(DirIdis(u64, u64)dev/ino on Unix, canonicalPathBufelsewhere). It enters each directory identity once and yields files under the first path spelling encountered. - In
first_scope,neighbourhood_filescallscollect_files_below, which instantiates its ownWalkwith a freshvisitedset. Ifz_real/tb.svis open, it walksz_real, findingz_real/child.sv. first_scoperecordsseen: HashSet<PathBuf>containingz_real/child.sv.- Later,
rest_of_scoperunscollect_files_withfrom workspace root with another freshvisitedset. The root walk visitsa_aliasfirst (alphabetically beforez_real). It discoversa_alias/child.sv. - Filtering in
rest_of_scopeonly checksseen.contains(&found.path). Becausea_alias/child.sv != z_real/child.sv,a_alias/child.svis kept! - The index now contains both
z_real/child.svanda_alias/child.sv. Definition returns two targets;prepareRenamerefuses becausechildis declared in multiple indexed files. - On whole rescan, a single root walk runs (
first_scopeis bypassed fortrace.number > 1), discovering onlya_alias/child.sv. Thus startup and rescan disagree. - Furthermore,
HEAD_WALK_MAXfallback unconditionally callsfiles.extend(head), which unions the disjoint walks and reproduces the duplicate bug even when falling back.
- Regular single root walk maintains
2. F2: Standalone Warm Scanload Unprimed First Trial
- Location:
tools/perf/phases_r4.py:237-260(load_cell), andtools/perf/lspclient.py:105-110(Session.__enter__). - Mechanism:
- When running
scanloadstandalone with--storage <dir>,load_cellsetscold=(cache == "cold"). - For
cache == "warm",cold=False.Session.__enter__callsos.makedirs(self.storage, exist_ok=True). - If
<dir>is newly created, it contains no index cache. - Trial 1 runs cold (0 hits / 3,974 misses, 1,684 ms parse time) and populates the cache.
- Trial 2 runs warm (3,974 hits / 0 misses, 0 ms parse time).
- The harness groups Trial 1 and Trial 2 under the single warm label.
- When running
3. F3: Conflation of Scan Completion with Client Request Window
- Location:
tools/perf/phases_r4.py:128-139(settled_at), consumed bysummary(lines 178–205). - Mechanism:
settled_atcallss.wait_quiet(QUIET)after the fixed request window (3,500 ms).- In
tools/perf/lspclient.py:334-355,wait_quietcheckslen(self.notifications). - A
--verboseserver emitswindow/logMessagelines for requests and timings. Furthermore,wait_quietmeasureslast - started, which due to clock reads is always> 0.0. - Consequently,
last = entered + more / 1000.0 if more > 0.0 else quiet_atalways selectsentered + more, anchoring the settle timestamp at ~3,406 ms regardless of whether the scan ended at 1,770 ms. - In
summary, responses are filtered witha["at"] <= run["settle"]. All 105 responses fall inside 3,400 ms, classifying 100% of responses as "mid-scan" and 0 as "after-settle".
4. Implementation Assessment Items 3, 4, 5 and Candidate Experiments N1, N2, N3
- Item 3 & N1 (First Action After Edit):
- Lint snapshot in
crates/lucisv_server/src/lint_snapshot.rscaches clean results (0.23 ms repeat). - First-after-edit costs 113.6 ms because
crates/lucisv_server/src/state/mod.rs:715invokesDocument::new, which unconditionally runstokenize,parse_tolerant,collect_defines,analyze,resolve_external, andLineIndex::newover the full 42,000-line buffer. - Work reduction must target tokenization/parsing/analysis allocations on edited buffers without breaking AST fidelity.
- Lint snapshot in
- Item 4 & N2 (Scope Construction, Facts Decode & Common-Port Rename):
- Tail rename scope stage: 163 ms total, with 31 ms in
known.facts_for(store deserialization) and ~100 ms parsing the 134 kept files. - Common port rename (
clk_i): 1,251 files mentionclk_i, requiring 1,251 full parses and semantic analyses (2.88 s wall time, 1.8 GiB peak RSS). - Optimization target: Streamlined deserialization of
KnownFactsand lighter-weight analysis retention for files whose AST is only needed for identifier occurrence verification.
- Tail rename scope stage: 163 ms total, with 31 ms in
- Item 5 & N3 (Quiet Scan & Publication Cost):
- A startup scan under load publishes staged records via
crates/lucisv_server/src/state/mod.rs:1183(publish_scan). - Each publication calls
WorkspaceIndex::absorb, which callsself.merge(None)—a full whole-index merge of all symbols and definitions across the entire workspace. - While
PUBLISH_EVERY = 512reduced publication frequency, each publication still incurs the ~70 ms whole-index merge. Reducing publication cost requires targeted incremental symbol merging invlog_semantic.
- A startup scan under load publishes staged records via
Detailed Implementation Plan
Phase 1: Correctness Fixes & Harness Repairs (F1, F2, F3)
[Phase 1 Sequencing]
┌─────────────────────────────────────────────────────────────┐
│ Step 1.1: Fix F1 (lucisv_core::walk & server discover state)│
└──────────────────────────────┬──────────────────────────────┘
│
┌──────────────────────────────▼──────────────────────────────┐
│ Step 1.2: Fix F2 (Harness warm priming & cache hit counters)│
└──────────────────────────────┬──────────────────────────────┘
│
┌──────────────────────────────▼──────────────────────────────┐
│ Step 1.3: Fix F3 (True scan-completion & response partition)│
└─────────────────────────────────────────────────────────────┘
Step 1.1: Fix F1 — Directory Identity and Path Selection Across Split Discovery
1. Handshake & Architecture Amendments (docs/topo.md)
- Amend
lucisv_core::walkAPI: Add a directory identity tracking type and updatecollect_files_below/collect_files_with:// In crates/lucisv_core/src/walk.rs #[derive(Debug, Clone, PartialEq, Eq)] pub struct WalkIdentity { pub dir_id: DirId, pub canonical_path: PathBuf, } /// Shared directory identity tracker across walks. #[derive(Default, Debug)] pub struct DirectoryTracker { visited: HashMap<DirId, PathBuf>, } impl DirectoryTracker { pub fn new() -> Self; pub fn is_visited(&self, dir: &Path) -> bool; pub fn record_or_check(&mut self, dir: &Path) -> Option<&PathBuf>; } pub fn collect_files_below_tracked( root: &Path, input: &Path, exclude: &[String], gitignore: bool, tracker: &mut DirectoryTracker, found: &mut dyn FnMut(PathBuf, Option<u64>), warn: &mut dyn FnMut(Warning), ) -> Result<(), String>; pub fn collect_files_with_tracker( input: &str, exclude: &[String], gitignore: bool, tracker: &mut DirectoryTracker, found: &mut dyn FnMut(PathBuf, Option<u64>), warn: &mut dyn FnMut(Warning), ) -> Result<(), String>;
2. Server Discovery Repair (crates/lucisv_server/src/state/discover.rs)
- Modify
neighbourhood_filesandPendingDiscovery:neighbourhood_filespasses a&mut DirectoryTrackerintocollect_files_below_tracked.- Store the populated
DirectoryTrackerinPendingDiscovery.
- Pre-check Path Selection Equivalence:
- When inspecting the workspace roots, check if any directory entry in the root is a symlink pointing to an ancestor/sibling of the neighbourhood directory that sorts before the neighbourhood path.
- If an alias sorting before the target exists (such as
a_alias -> z_real), split discovery cannot unilaterally indexz_realwithout violating the root walk's canonical path choice. - In this case, trigger the bounded fallback: discard the partial neighbourhood and execute a single root walk (
self.collect_sources(...)), returning(sources, None).
- Repair
HEAD_WALK_MAXFallback:- In
first_scope(lines 450–459), whenhead.len() > HEAD_WALK_MAX: Do NOT unionheadandwalked_rest! Instead, discardheadand executeself.collect_sources(watch, HeldAnalyses::Wanted, trace), returning(sources, None).
- In
- Modify
rest_of_scope:- Use the
DirectoryTrackerfromPendingDiscoveryduring the root walk so any directory identity already visited in the neighbourhood walk is recognized and not re-entered under an alternate alias. - Filter
walkedfiles using bothseen_pathsandseen_dir_identities.
- Use the
3. Regression Test Fixture (crates/lucisv_server/src/server/tests/startup.rs)
- Add automated integration tests replicating the review's reproduction:
- Fixture A (Alias sorting before target):
workspace/a_alias -> z_real,workspace/z_real/{child.sv, tb.sv}. - Fixture B (Alias sorting after target):
workspace/z_alias -> a_real,workspace/a_real/{child.sv, tb.sv}. - Fixture C (Multiple aliases):
a_alias -> target,m_alias -> target,target/{child.sv}. - Fixture D (Ancestor cycle):
workspace/sub/up -> ... - Fixture E (Ignore rules):
.gitignoreexcluding files inside aliased directories. - Fixture F (Open unsaved buffer): Unsaved buffer open at
z_real/tb.svwith modified text. - Fixture G (True duplicates): Genuine duplicate module declaration in two distinct physical files. Verify ambiguity refusal is preserved!
- Fixture A (Alias sorting before target):
- Assertions:
- Index file paths after startup
==index file paths after a whole rescan==index file paths after restart. - Definition on
childreturns exactly 1 location. textDocument/prepareRenameonchildis accepted.- True duplicate module refusal is still refused with identical diagnostic message.
- Index file paths after startup
Step 1.2: Fix F2 — Standalone Warm Harness Priming & Cache Counters
1. Untimed Priming in Harness (tools/perf/phases_r4.py)
- In
load_cell(cache, buffers, rate, params, where=""):def prime_storage(storage_name, extra): """Perform an untimed session to prime the index cache before warm trials.""" with session("workspace", cold=False, verbose=True, storage_name=storage_name) as s: s.initialize() open_buffers(s, extra) s.wait_quiet(1.5) s.take_notifications() # Inside load_cell: if cache == "warm": # If cache store does not exist or has no valid store file: store_path = os.path.join(ARGS.storage, "r4-load") if not os.path.exists(store_path) or not os.listdir(store_path): prime_storage("r4-load", extra)
2. Cache Counters Recording & Assertion
- Inspect
counts = scans[0].get("counts", {})parsed fromtraces(s):- Extract
hits = counts.get("hits", 0)andmisses = counts.get("misses", 0). - In
summary(runs): Includecache_hits: [run["hits"] for run in runs]andcache_misses: [run["misses"] for run in runs]. - In
cell_status(got): Ifcache == "warm", assertall(h > 0 for h in got["cache_hits"]). If any warm trial records 0 hits or unexpected misses, setstatus = "error"with diagnostic message.
- Extract
3. Verification Test
- Execute
tools/perf/bench.py scanloadwith a brand-new, non-existent--storagedirectory. - Verify:
- Untimed prime runs cleanly.
- Trial 1 and Trial 2 both report ~3,974 hits and 0 misses.
Step 1.3: Fix F3 — Decoupling Scan Completion from Client Request Window
1. Scan-Specific Completion Timestamp (tools/perf/phases_r4.py)
- Capture True Scan Completion:
- The server outputs
timing: scan <n> stages (...) total=<ms>upon scan completion, and sends$/progresstoken withkind: "end". - In
tools/perf/lspclient.py, record_scan_completed_at: theperf_countertimestamp when the reader thread parses the scan's final progress notification ortiming: scanline. - In
phases_r4.py: Replace the flawedsettled_atlogic with:def scan_completed_ms(s, origin): """Milliseconds from `origin` to the scan's actual completion.""" if s.scan_completed_at is not None: return (s.scan_completed_at - origin) * 1000.0 # Fallback to server-reported scan total if notification timestamp unavailable: sc = traces(s) if sc and "stages" in sc[0]: return sc[0]["stages"].get("total", 0.0) return None
- The server outputs
2. Response Partitioning in summary
- Use
scan_completed_msto partition responses:inside = [a["ms"] for run in runs for a in run["answers"] if a["at"] <= run["scan_completed_ms"]] after = [a["ms"] for run in runs for a in run["answers"] if a["at"] > run["scan_completed_ms"]] - Expose both in row output:
mid_scan_answers = len(inside)after_settle_answers = len(after)mid_scan_median_msandafter_settle_median_ms- Retain raw
a["at"](arrival offsets) inresults.jsonl.
3. Verification Test
- Run a warm session where server scan duration is ~1,770 ms inside a 3,500 ms window.
- Verify:
settled_msreflects ~1,770 ms (NOT 3,406 ms).- Out of 35 requests, requests arriving before 1,770 ms (~17 requests) are categorized as
mid_scan_answers, and requests arriving after 1,770 ms (~18 requests) are categorized asafter_settle_answers. - Extend window to 5,000 ms: verify scan completion remains unchanged (~1,770 ms) and
after_settle_answersincreases proportionally.
Phase 2: Performance Follow-Ups (Addressing Assessment Items 3–5 & N1–N3)
Once Phase 1 is verified and merged, the three performance investigation lanes will proceed conditionally:
[Phase 2 Lanes]
┌─────────────────────────────────────────────────────────────┐
│ Lane N1: Lexer/Parser & Dirty-Buffer Analysis Work (Item 3) │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ Lane N2: Retained-Analysis Parse Work & Scope Decode (Item 4│
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ Lane N3: Quiet Scan Decode/Merge & Publication Cost (Item 5)│
└─────────────────────────────────────────────────────────────┘
Step 2.1: Lane N1 — Lexer/Parser & Dirty-Buffer Analysis (Addressing Item 3 & N1)
- Baseline: First-after-edit on
pinmux_reg_top.svis 113.6 ms (repeat median 0.23 ms via lint snapshot). - Target: Reduce first-after-edit time by ≥15% (stretch: <95 ms) while maintaining exact AST/diagnostic output.
- Approach:
- Profile
Document::new:- Tokenize: Measure time and allocations.
- Parse tolerant: Inspect grammar node allocations.
- Semantic analysis & external resolution.
- Optimize single-document re-tokenization / parsing:
- Profile whether token vector reallocation in
tokenizecan reuse a pooled buffer. - Avoid cloning the token stream when passing from
tokenizeintoparse_tolerant(e.g. transfer ownership or borrow).
- Profile whether token vector reallocation in
- Verification:
- Snapshot tests in
vlog_formatterandvlog_parser. offereditbenchmark phase comparing candidate vs 0.52.0 baseline.
- Snapshot tests in
- Profile
Step 2.2: Lane N2 — Retained-Analysis Parse Work & Scope Decode (Addressing Item 4 & N2)
- Baseline: Tail rename: 324.6 ms (163 ms scope stage, including 31 ms store decode). Common-port rename (
clk_i): 2,883.7 ms, 1,251 parses, 1.78 GiB peak RSS. - Target: Reduce scope build store decode time (<20 ms) and reduce common-port parse overhead without increasing peak RSS.
- Approach:
- KnownFacts Store Deserialization:
- In
crates/lucisv_server/src/index_cache.rs, benchmarkfacts_for. - Evaluate zero-copy / compact binary decoding for
FileFactsto cut the 31 ms decode bottleneck.
- In
- Retained Analyses Work:
- In
crates/vlog_refactor/src/scope.rs, investigate files inClass::Kept: - Instead of building full redundant ASTs for files where only identifier occurrence validation is needed, evaluate whether occurrence checking can run against a lighter token stream while strictly preserving warning and refusal semantics.
- In
- Verification & Guardrails:
- Verify byte-identical edits and warning sentences across all 8 rename shapes (
renamewarn). - Monitor peak RSS under
tools/guard.sh -m 8to guarantee peak memory does not exceed the 1.8 GiB envelope.
- Verify byte-identical edits and warning sentences across all 8 rename shapes (
- KnownFacts Store Deserialization:
Step 2.3: Lane N3 — Quiet Scan & Incremental Publication Merge (Addressing Item 5 & N3)
- Baseline: Warm quiet scan 1,064.7 ms, cold quiet scan 2,886.6 ms, warm loaded scan 1,771 ms.
- Target: Reduce warm quiet scan below 1,000 ms and reduce publication merge overhead.
- Approach:
- Targeted
WorkspaceIndex::absorb:- Currently,
WorkspaceIndex::absorbcallsself.merge(None), rebuilding symbol tables across all 3,976 files. - Implement incremental symbol table merging in
crates/vlog_semantic/src/workspace/update.rs, only updating symbol tables for files added/modified in the batch.
- Currently,
- Candidate Construction:
- Benchmark candidate table construction during publication; avoid full re-indexing of unchanged completion words.
- Verification:
- Fingerprint equivalence:
WorkspaceIndex::fingerprintmust be identical between incremental absorb and full rebuild. scanloadandscanbenchmark phases under corrected F2/F3 harness.
- Fingerprint equivalence:
- Targeted
File Modification Map
| Component / Layer | Action | Target File | Description |
|---|---|---|---|
lucisv_core (Walk) |
[MODIFY] |
crates/lucisv_core/src/walk.rs |
Add DirectoryTracker and expose directory identity (DirId) tracking across walks |
lucisv_server (State) |
[MODIFY] |
crates/lucisv_server/src/state/discover.rs |
Use DirectoryTracker, fix first_scope, repair HEAD_WALK_MAX fallback, ensure alias equivalence |
lucisv_server (State) |
[MODIFY] |
crates/lucisv_server/src/state/scan.rs |
Update PendingDiscovery to hold DirectoryTracker |
lucisv_server (Tests) |
[MODIFY] |
crates/lucisv_server/src/server/tests/startup.rs |
Add F1 symlink regression matrix (alias before/after, cycle, ignores, unsaved buffer) |
| Documentation | [MODIFY] |
docs/topo.md |
Record amended lucisv_server ──▶ lucisv_core walk handshake |
| Perf Tools (Harness) | [MODIFY] |
tools/perf/phases_r4.py |
Fix F2 (untimed warm priming & cache counters) and F3 (scan completion timestamping & response partition) |
| Perf Tools (Client) | [MODIFY] |
tools/perf/lspclient.py |
Record reader-thread scan completion instant _scan_completed_at |
| Performance Tracking | [MODIFY] |
docs/perf/take5-tracking.md |
Update experiment logs and status for F1, F2, F3 |
Verification & QA Plan
Automated Correctness & Quality Gates
Every step will be verified using the repository's runaway guard:
# Code formatting
cargo fmt --all -- --check
# Strict Clippy validation
tools/guard.sh -m 8 -t 1800 -- cargo clippy --workspace --all-targets --locked -- -D warnings
# Full workspace test suite (must meet or exceed 4,374 passed, 0 failed, 45 ignored)
tools/guard.sh -m 8 -t 1800 -- cargo test --workspace --locked
Specialized Correctness Assertions for F1
Run the dedicated startup test suite:
tools/guard.sh -m 8 -t 1800 -- cargo test -p lucisv_server --test server_tests startup
Assert that:
alias_sorting_before_target:a_alias -> z_real. Index paths, definition targets, andprepareRenamematch between startup, whole rescan, and restart.alias_sorting_after_target:z_alias -> a_real. Same equivalence check.multiple_aliases: Multiple symlinks to single target directory do not produce duplicate entries.ancestor_cycle: Cyclic symlinks terminate safely without duplicate entries.genuine_duplicate_declarations: Genuine collisions in distinct files remain ambiguous and correctly refused.
Benchmark & Harness Verification for F2 and F3
- F2 Warm Priming Verification:
Assert that:
tools/guard.sh -m 8 -t 1800 -- python3 tools/perf/bench.py scanload --storage /tmp/test-fresh-store --tries 2- Untimed prime runs automatically.
- Both Trial 1 and Trial 2 report ~3,974 cache hits and 0 misses.
- F3 Scan Completion Verification:
Assert that:
tools/guard.sh -m 8 -t 1800 -- python3 tools/perf/bench.py scanload --tries 3settled_msreflects server scan duration (~1,770 ms), not 3,400 ms.- Responses are partitioned correctly into
mid_scan_answersandafter_settle_answers. - Extending fixed window from 3,500 ms to 5,000 ms keeps
settled_msconstant while increasingafter_settle_answers.