Files
lucisv/docs/052_implementation_plan.md

25 KiB
Raw Permalink Blame History

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):

  1. F1 (P2 Correctness): Split startup discovery duplicates modules behind directory aliases (symlinks), breaking startup/rescan equivalence and blocking valid renames until a full rescan.
  2. F2 (P2 Harness): Standalone scanload on a fresh storage directory includes an unprimed cold trial under a warm label (0 hits / 3,974 misses).
  3. F3 (P2 Harness): scanload completion and mid-scan classifications conflate client request window chatter with true scan completion.
  4. 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 KnownFacts reuse; 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 pick z_real without diverging from the canonical root walk which selects a_alias. The approved strategy is:

  1. Share directory identity (DirId) between the neighbourhood walk and root walk.
  2. 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), and crates/lucisv_core/src/walk.rs:121-164 (collect_files_below).
  • Mechanism:
    1. Regular single root walk maintains Walk.visited: HashSet<DirId> (DirId is (u64, u64) dev/ino on Unix, canonical PathBuf elsewhere). It enters each directory identity once and yields files under the first path spelling encountered.
    2. In first_scope, neighbourhood_files calls collect_files_below, which instantiates its own Walk with a fresh visited set. If z_real/tb.sv is open, it walks z_real, finding z_real/child.sv.
    3. first_scope records seen: HashSet<PathBuf> containing z_real/child.sv.
    4. Later, rest_of_scope runs collect_files_with from workspace root with another fresh visited set. The root walk visits a_alias first (alphabetically before z_real). It discovers a_alias/child.sv.
    5. Filtering in rest_of_scope only checks seen.contains(&found.path). Because a_alias/child.sv != z_real/child.sv, a_alias/child.sv is kept!
    6. The index now contains both z_real/child.sv and a_alias/child.sv. Definition returns two targets; prepareRename refuses because child is declared in multiple indexed files.
    7. On whole rescan, a single root walk runs (first_scope is bypassed for trace.number > 1), discovering only a_alias/child.sv. Thus startup and rescan disagree.
    8. Furthermore, HEAD_WALK_MAX fallback unconditionally calls files.extend(head), which unions the disjoint walks and reproduces the duplicate bug even when falling back.

2. F2: Standalone Warm Scanload Unprimed First Trial

  • Location: tools/perf/phases_r4.py:237-260 (load_cell), and tools/perf/lspclient.py:105-110 (Session.__enter__).
  • Mechanism:
    1. When running scanload standalone with --storage <dir>, load_cell sets cold=(cache == "cold").
    2. For cache == "warm", cold=False. Session.__enter__ calls os.makedirs(self.storage, exist_ok=True).
    3. If <dir> is newly created, it contains no index cache.
    4. Trial 1 runs cold (0 hits / 3,974 misses, 1,684 ms parse time) and populates the cache.
    5. Trial 2 runs warm (3,974 hits / 0 misses, 0 ms parse time).
    6. The harness groups Trial 1 and Trial 2 under the single warm label.

3. F3: Conflation of Scan Completion with Client Request Window

  • Location: tools/perf/phases_r4.py:128-139 (settled_at), consumed by summary (lines 178–205).
  • Mechanism:
    1. settled_at calls s.wait_quiet(QUIET) after the fixed request window (3,500 ms).
    2. In tools/perf/lspclient.py:334-355, wait_quiet checks len(self.notifications).
    3. A --verbose server emits window/logMessage lines for requests and timings. Furthermore, wait_quiet measures last - started, which due to clock reads is always > 0.0.
    4. Consequently, last = entered + more / 1000.0 if more > 0.0 else quiet_at always selects entered + more, anchoring the settle timestamp at ~3,406 ms regardless of whether the scan ended at 1,770 ms.
    5. In summary, responses are filtered with a["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.rs caches clean results (0.23 ms repeat).
    • First-after-edit costs 113.6 ms because crates/lucisv_server/src/state/mod.rs:715 invokes Document::new, which unconditionally runs tokenize, parse_tolerant, collect_defines, analyze, resolve_external, and LineIndex::new over the full 42,000-line buffer.
    • Work reduction must target tokenization/parsing/analysis allocations on edited buffers without breaking AST fidelity.
  • 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 mention clk_i, requiring 1,251 full parses and semantic analyses (2.88 s wall time, 1.8 GiB peak RSS).
    • Optimization target: Streamlined deserialization of KnownFacts and lighter-weight analysis retention for files whose AST is only needed for identifier occurrence verification.
  • 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 calls self.merge(None)—a full whole-index merge of all symbols and definitions across the entire workspace.
    • While PUBLISH_EVERY = 512 reduced publication frequency, each publication still incurs the ~70 ms whole-index merge. Reducing publication cost requires targeted incremental symbol merging in vlog_semantic.

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::walk API: Add a directory identity tracking type and update collect_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_files and PendingDiscovery:
    • neighbourhood_files passes a &mut DirectoryTracker into collect_files_below_tracked.
    • Store the populated DirectoryTracker in PendingDiscovery.
  • 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 index z_real without 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_MAX Fallback:
    • In first_scope (lines 450–459), when head.len() > HEAD_WALK_MAX: Do NOT union head and walked_rest! Instead, discard head and execute self.collect_sources(watch, HeldAnalyses::Wanted, trace), returning (sources, None).
  • Modify rest_of_scope:
    • Use the DirectoryTracker from PendingDiscovery during the root walk so any directory identity already visited in the neighbourhood walk is recognized and not re-entered under an alternate alias.
    • Filter walked files using both seen_paths and seen_dir_identities.
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): .gitignore excluding files inside aliased directories.
    • Fixture F (Open unsaved buffer): Unsaved buffer open at z_real/tb.sv with modified text.
    • Fixture G (True duplicates): Genuine duplicate module declaration in two distinct physical files. Verify ambiguity refusal is preserved!
  • Assertions:
    1. Index file paths after startup == index file paths after a whole rescan == index file paths after restart.
    2. Definition on child returns exactly 1 location.
    3. textDocument/prepareRename on child is accepted.
    4. True duplicate module refusal is still refused with identical diagnostic message.

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 from traces(s):
    • Extract hits = counts.get("hits", 0) and misses = counts.get("misses", 0).
    • In summary(runs): Include cache_hits: [run["hits"] for run in runs] and cache_misses: [run["misses"] for run in runs].
    • In cell_status(got): If cache == "warm", assert all(h > 0 for h in got["cache_hits"]). If any warm trial records 0 hits or unexpected misses, set status = "error" with diagnostic message.
3. Verification Test
  • Execute tools/perf/bench.py scanload with a brand-new, non-existent --storage directory.
  • 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 $/progress token with kind: "end".
    • In tools/perf/lspclient.py, record _scan_completed_at: the perf_counter timestamp when the reader thread parses the scan's final progress notification or timing: scan line.
    • In phases_r4.py: Replace the flawed settled_at logic 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
      
2. Response Partitioning in summary
  • Use scan_completed_ms to 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_ms and after_settle_median_ms
    • Retain raw a["at"] (arrival offsets) in results.jsonl.
3. Verification Test
  • Run a warm session where server scan duration is ~1,770 ms inside a 3,500 ms window.
  • Verify:
    • settled_ms reflects ~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 as after_settle_answers.
    • Extend window to 5,000 ms: verify scan completion remains unchanged (~1,770 ms) and after_settle_answers increases 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.sv is 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:
    1. Profile Document::new:
      • Tokenize: Measure time and allocations.
      • Parse tolerant: Inspect grammar node allocations.
      • Semantic analysis & external resolution.
    2. Optimize single-document re-tokenization / parsing:
      • Profile whether token vector reallocation in tokenize can reuse a pooled buffer.
      • Avoid cloning the token stream when passing from tokenize into parse_tolerant (e.g. transfer ownership or borrow).
    3. Verification:
      • Snapshot tests in vlog_formatter and vlog_parser.
      • offeredit benchmark phase comparing candidate vs 0.52.0 baseline.

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:
    1. KnownFacts Store Deserialization:
      • In crates/lucisv_server/src/index_cache.rs, benchmark facts_for.
      • Evaluate zero-copy / compact binary decoding for FileFacts to cut the 31 ms decode bottleneck.
    2. Retained Analyses Work:
      • In crates/vlog_refactor/src/scope.rs, investigate files in Class::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.
    3. Verification & Guardrails:
      • Verify byte-identical edits and warning sentences across all 8 rename shapes (renamewarn).
      • Monitor peak RSS under tools/guard.sh -m 8 to guarantee peak memory does not exceed the 1.8 GiB envelope.

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:
    1. Targeted WorkspaceIndex::absorb:
      • Currently, WorkspaceIndex::absorb calls self.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.
    2. Candidate Construction:
      • Benchmark candidate table construction during publication; avoid full re-indexing of unchanged completion words.
    3. Verification:
      • Fingerprint equivalence: WorkspaceIndex::fingerprint must be identical between incremental absorb and full rebuild.
      • scanload and scan benchmark phases under corrected F2/F3 harness.

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:

  1. alias_sorting_before_target: a_alias -> z_real. Index paths, definition targets, and prepareRename match between startup, whole rescan, and restart.
  2. alias_sorting_after_target: z_alias -> a_real. Same equivalence check.
  3. multiple_aliases: Multiple symlinks to single target directory do not produce duplicate entries.
  4. ancestor_cycle: Cyclic symlinks terminate safely without duplicate entries.
  5. genuine_duplicate_declarations: Genuine collisions in distinct files remain ambiguous and correctly refused.

Benchmark & Harness Verification for F2 and F3

  1. F2 Warm Priming Verification:
    tools/guard.sh -m 8 -t 1800 -- python3 tools/perf/bench.py scanload --storage /tmp/test-fresh-store --tries 2
    
    Assert that:
    • Untimed prime runs automatically.
    • Both Trial 1 and Trial 2 report ~3,974 cache hits and 0 misses.
  2. F3 Scan Completion Verification:
    tools/guard.sh -m 8 -t 1800 -- python3 tools/perf/bench.py scanload --tries 3
    
    Assert that:
    • settled_ms reflects server scan duration (~1,770 ms), not 3,400 ms.
    • Responses are partitioned correctly into mid_scan_answers and after_settle_answers.
    • Extending fixed window from 3,500 ms to 5,000 ms keeps settled_ms constant while increasing after_settle_answers.