# perf5-p3 — one parse for the CLI package census ## Goal `lucisv check` builds a project census before the first rule runs. When `unused-import` is enabled the census asked `vlog_linter::package_exports` for **every** file in the run, and that function built a one-file `WorkspaceIndex` — a lex, a parse, a full analysis and a fact read-off — even for a file that declares no package at all. The census had already parsed the same text a line earlier for the interface table, so every file paid for two whole-file parses and one analysis it almost never needed. Performance take 5 §P3 measured the price: the rule turns a 0.450 s all-style run on opentitan `hw/ip` into a 0.587 s one, **+137 ms (23.3 %)**, and peak RSS 177 → 217 MiB. This feature removes the duplication. The census parses each file once and derives both halves from that parse, and the package half opens with an **AST gate**: a file whose tree holds no `package` item contributes nothing and no index is built for it. On `hw/ip` that is 1 624 of 1 805 files. ## Assumptions - `ParsedSource::parse` and `vlog_semantic`'s `parse_and_collect` produce the *same* tree for the same text: both are `tokenize` + `parse_tolerant` on the lex-ok path and `parse_source_tolerant` on the lex-error path. The equality tests in `interfaces.rs` are what hold this true rather than the reading of two functions. - `collect_defines(&[])` equals `DefineTable::default()` (it is `Vec::new()` either way), and `words::harvest(&[])` / `harvest_raw(&[])` are empty — so the lex-error path of `FileFacts::from_analysis` gives the record `FileFacts::of` gives. - Only `bind_item`'s `ItemKind::Package` arm ever declares a `SymbolKind::Package`, so a tree with no `Package` item cannot produce a file-scope package unit. The gate additionally never fires on a **fragment** parse, which `walk_items` does not descend into. - `words::harvest_text(src)` equals `words::harvest(ParsedSource::parse(src) .tokens())`: `harvest_text` is `tokenize` + `harvest`, empty on a lex error, and a `ParsedSource` whose text did not lex holds no tokens. - A rayon worker in `lucisv` has `PARSE_STACK_SIZE` of stack (`main.rs::pool`), which is what lets the census analyse on it. This feature removes a parse from that thread and adds none. ## Handshakes ### Consumed - `vlog_semantic::{analyze, FileFacts::from_analysis, IndexBuilder::{new, add_facts, finish}, WorkspaceIndex::{units_of, members_of, reexported_packages}}` — the one-file index, now built from a parse the caller already has instead of from text. **No semantic change was needed:** `FileFacts::from_analysis` (added by perf5-p2 for the refactoring scope) already accepts exactly `(path, tree, defines, sem, src, lines, tokens)`, and `IndexBuilder::add_facts` + `finish` is what `WorkspaceIndex::build` itself does. `crates/vlog_semantic/` is untouched by this lane. - `vlog_parser::defines::collect_defines`, `vlog_parser::token::Token`, `vlog_parser::LineIndex` — the three inputs `from_analysis` wants that a `ParsedSource` does not already carry. ### Promised - `vlog_linter::package_exports_in(path, file, tokens, src)` — new, additive. Every package the parsed file declares, with the names it exports, `None` for one this file alone cannot answer for. **Byte-identical to `package_exports(path, src)` on the same text**, which is now a wrapper (parse, then `_in`) and stays the API for a caller holding only text. - `MentionOracle::package_exports`' answers are unchanged: the same duplicate-package `None`, the same `export q::*` `None`, the same conservative silence for an unknown package. ### Requested of the lead (not done by this lane — `docs/topo.md` is not ours) 1. `lucisv ──▶ vlog_linter`: add `package_exports_in` beside `ParsedSource` — the CLI census hands the linter its own parse for the package half, as it already does for the interface half (`module_interfaces`). 2. `vlog_linter ──▶ vlog_semantic`: the edge now also reads `FileFacts::from_analysis` + `IndexBuilder::{add_facts, finish}` to build the one-file package index from a parse the linter already has. `WorkspaceIndex::build` is still what the equality test compares against, so the two constructions are pinned equal. ## Status / TODO - [x] package exports from the census's existing parse; AST gate, never a textual `contains("package")` - [x] every-fixture equality test against the old `WorkspaceIndex::build` construction (15 fixtures, plus a gate-answer test and the duplicate pin) - [x] CLI regression: default `check` byte-identical, all-style keeps every `unused-import` finding — six new end-to-end tests, and the corpus run's five stdout captures `diff` clean - [x] paired three-configuration measurement on `hw/ip`, tracker filled - [x] `cargo fmt` / guarded `clippy --all-targets` / guarded `test --workspace` (4 250 → 4 262, 0 failed) - [ ] QA - [ ] lead: the two `docs/topo.md` edges requested above ## Work log ### 2026-09-07 — dev **The change, file by file.** - `crates/vlog_linter/src/interfaces.rs`. New public `package_exports_in(path: &Path, file: &SourceFile, tokens: &[Token], src: &str) -> Vec<(String, Option>)>` — the same three index queries as before (`units_of(Package)`, `reexported_packages`, `members_of`) over an index built two new ways. `package_exports(path, src)` is now `ParsedSource::parse` + `package_exports_in`, so a text-only caller is unaffected and the two forms cannot disagree. Two private helpers: `declares_a_package(file)` — the gate, `walk_items` looking for `ItemKind::Package`, deliberately a *superset* of "declares a package unit" (the walk descends into every container while only a file-scope binding becomes a unit), and never firing on a fragment parse; and `one_file_index(path, file, tokens, src)` — `collect_defines` + `analyze` + `LineIndex::new` + `FileFacts::from_analysis` + `IndexBuilder::{add_facts, finish}`, which is `WorkspaceIndex::build` with the lex and the parse deleted. - `crates/vlog_linter/src/lib.rs`. One line: `package_exports_in` joins the `interfaces` re-export. - `crates/lucisv/src/lint.rs`. `Census::of`'s rayon closure became a free `harvest_one(job, interfaces, packages) -> PerFile` (the `PerFile` alias moved to module scope with it), so `of` is a `par_iter` line plus the merge and both stay inside the size rule. `harvest_one` parses **once** when either half is wanted and feeds the word census, the interface table and the package table from that one parse; when neither is wanted it still only lexes, via `words::harvest_text`. Production lines (non-blank, non-comment, before `mod tests`): 495 → **494** — the census work moved rather than grew, well under the 600 mark. - `crates/lucisv/tests/cli.rs`. Six end-to-end tests (see below). **Why no `vlog_semantic` change.** The plan allowed an additive `FileFacts::from_parsed`. It was not needed: §P2b already added `FileFacts::from_analysis(path, tree, defines, sem, src, lines, tokens)` for the refactoring scope, and that is exactly the second half of `FileFacts::of`. `crates/vlog_semantic/` is byte-unchanged by this lane. **The gate, and why it is safe.** `SymbolKind::Package` is created in exactly one place, `bind/item.rs`'s `ItemKind::Package` arm, and only a binding in the *file* scope becomes an indexed unit. So a tree holding no `Package` item anywhere cannot yield a package unit, and returning empty for it is not an approximation. Erring the other way (opening the gate too often) costs an index and nothing else, which is why the fragment case is let through rather than reasoned about. **Tests.** `interfaces::package_tests` keeps the **pre-P3 body verbatim** as a `from_text` reference and asserts the new code equal to it over 15 fixtures: no package; one; two; `export *::*`; `export q::*`; a named re-export; a package behind an `` `ifdef``; a package after a module; text that does not lex; a parse error inside a package body; a class in a package; the word `package` in a string; the same in a comment; one name declared twice; an empty file. Three further tests pin what equality cannot see — `only_a_package_item_opens_the_gate` checks the gate's answer fixture by fixture (a gate that always opened would fail it), `the_unlexable_fixture_does_not_lex` stops that fixture going stale, and `a_name_declared_twice_in_one_file_answers_with_the_first` pins a pre-existing answer worth knowing: **within one file** a duplicate package name reports the *first* declaration's members, not `None`. The `None` is the cross-file rule and belongs to `Census::of`'s merge. That behaviour is unchanged by this lane and is not a finding against it, but QA should know it is there. The six CLI tests drive the real binary: an unused import reported and a used one not; a default `check` silent about imports; an import of a package outside the run silent; an import of a re-exporting package silent; an import of a package two files declare silent; and a run whose extra files write `package` only inside a string and a comment producing the identical finding set. There were **no** CLI-level `unused-import` tests before this lane. **Measurement** (full record: `docs/perf/take5-tracking.md`, experiment `P3-2026-09-07`; raw data `~/.cache/lucisv-perf/take5-p3/`). The owner's paired method — alternating binary order, `/usr/bin/time -l`, every child under `tools/guard.sh -m 8 -t 1800`, opentitan read-only and its `git status --porcelain` asserted after every single invocation. | `hw/ip` cell | reference 0.50.0 | trunk rebuilt here | candidate | |---|---:|---:|---:| | default `check` | 0.4183 s (median 0.420) | 0.4450 (0.420) | **0.4233 (0.420)** | | `--select error,warning,style` | 0.6333 | 0.6333 | **0.4817** | | the same, `--ignore unused-import` | 0.4750 | 0.4917 | **0.4767** | | the rule's paired increment | 158.3 ms | 141.7 ms | **5.0 ms** | | all-style peak RSS (max of 6) | 220.9 MiB | 219.1 | **202.0** | **96 % of the increment is gone** against the same-toolchain control, where the target was half. All-style falls **−23.9 %**; `hw/vendor` −22.2 % and `hw/dv` −18.5 % in a separate eight-trial pass. Every cell's stdout is **byte-identical** to the reference's, diffed as files: `hw/ip` default 445 findings, all-style 7 751 (17 of them `unused-import`), minus rule 7 734; `hw/vendor` 1 666; `hw/dv` 1 158. Two notes on honesty. First, the machine was loaded (one-minute load 3.6–9.9 against the §P0 baseline's 2.9–4.6), so absolute seconds here are higher than the tracker's REF cells for *both* binaries; only the paired difference is quoted. Second, the first eight-trial pass showed default `check` +4 % on the candidate, which no code path explains (a default run never asks for the package half). A **third binary** — the same trunk source rebuilt here — was added as a control and settled it: the trunk rebuild is +6.4 % on default against the cached reference while the candidate is +1.2 %, and all three medians are 0.420 s. The default cell is unchanged. **What remains.** The 5.0 ms left is the `unused-import` rule body's own `import_usage` plus the 181 surviving one-file index builds (now analysis and record only). The next measurable CLI duplicate is the **third parse** — the lint pass parses each of the 1 805 files again after the census has. Retaining the census's ASTs would remove it and would hold 1 805 trees of a 39 MB corpus alive at once against a 202 MiB peak; the plan told this stage to measure peak RSS before making that trade, and it is not made here. ## QA log ### 2026-09-07 — QA **Verdict: PASS.** All gates green, the AST gate independently attacked (9 fixtures beyond the dev's 15) and sabotage-tested, lint-silence parity diffed full-output on a fixture tree the dev did not build, all five corpus cells re-run and re-hashed to the exact quoted hashes, the timing claim reproduced within the noise this machine allows, and traceability numbers re-derived independently. No corruption/idempotency/comment risk: this lane touches only census bookkeeping, never emitted text. **Setup.** Worked in a fresh clone at `/private/tmp/.../scratchpad/qa-p3/clone` (branched from `5c9fdb2`, `git apply` of `git diff -- crates/ TODO.md` from the working tree — applied clean) plus an unmodified sibling clone `clone-head` at the same `5c9fdb2` for a true pre-P3 baseline. Every cargo/lucisv invocation below went through `tools/guard.sh -m 8 -t 1800`; zero guard kills anywhere in this pass. `git -C /Users/guoliangchen/repo/opentitan status --porcelain` was checked before this session and after every corpus/timing invocation — always exactly the three pre-existing files (`hw/ip/aes/dv/tb/tb.sv`, `hw/top_darjeeling/ip/ast/rtl/ast.sv`, `hw/top_earlgrey/ip/ast/rtl/ast.sv`). Machine load was elevated for part of this session (a 1-minute sample of 59 was observed mid-session, decaying to ~5 by the timing re-take; unrelated system processes, not a runaway — checked with `top`, nothing of mine was consuming it) — noted per instruction, and the timing section below reads only the paired difference for that reason. **1. Gates.** - `cargo fmt --all -- --check` on the clone: clean (exit 0). - `cargo clippy --all-targets` on the clone: clean, zero warnings (exit 0). `grep -n "#\[allow" crates/lucisv/src/lint.rs crates/vlog_linter/src/interfaces.rs`: no hits — no new `#[allow]`. - `cargo test --workspace --release` on the clone (candidate, P3 applied): **4262 passed, 0 failed** (summed across every binary's `test result:` line). Same command on `clone-head` (5c9fdb2, no P3): **4250 passed, 0 failed**. Difference is exactly **+12**, matching the dev's own count of new tests (6 `package_tests`/gate tests + 6 CLI tests); nothing existing was lost. - `cargo tree -p lucisv -e normal` on the clone: lists `lucisv_core`, `rayon`, `vlog_formatter`, `vlog_linter`, `vlog_parser` — `vlog_semantic` appears only nested under `vlog_linter`, never as a direct dependency of `lucisv`. Topology claim confirmed. - Production line count, non-blank/non-comment before `mod tests`: `crates/lucisv/src/lint.rs` **494** — confirmed by the same `awk`+`grep -c` method the dev used. Well under the 600 mark. - Binary provenance: rebuilding `5c9fdb2` unmodified in `clone-head` produced sha256 `81bb40a28802e713…` — an **exact match** to the dev's own recorded "trunk-rebuild" control binary. Rebuilding the clone with the P3 diff applied produced sha256 `2c16b321cb2d1083…` — an exact match to the dev's recorded candidate hash, and to `target/release/lucisv` in the main tree (no rebuild was needed there; used as-is for corpus/timing runs below). **2. THE AST GATE.** Read `declares_a_package` and `walk_items` (`crates/vlog_linter/src/visit.rs`): the gate is a `matches!(item.kind, ItemKind::Package { .. })` predicate over an AST walk that descends into modules, classes, packages, and every generate-region/if/for/case shape — never a text search. Macros are confirmed **not expanded** by this parser (`ItemKind::MacroItem(MacroCall)` holds the call, not a substituted body — `vlog_parser/src/ast/mod.rs:360`), so a `` `define P package p; endpackage `` followed by `` `P `` cannot manufacture a real `Package` item under either the old or the new construction — confirmed by test, not assumed. Nine fixtures beyond the dev's 15, appended as `qa_attack_tests` in the clone's `interfaces.rs` (not shipped; QA-only clone code) and run with `cargo test -p vlog_linter -- interfaces:: --nocapture`: **all 9 pass**, each asserting `package_exports(new) == from_text(old)` (old = the dev's verbatim pre-P3 `WorkspaceIndex::build` construction, duplicated into the QA module since it is private to `package_tests`): (a) package word only in a macro body never invoked, in a string spanning a line continuation, in a block comment, and in an invoked (but not expanded) macro — all agree, all empty; (d) `Package p; ... endpackage` (capital P) — not a keyword, agrees; (e) `program`/`interface`/`class`/`module` all named `package_x` — none is a package, agrees; (c) a parse error (`@@@`) before the first member inside the package body — agrees; (f) an empty package body — agrees, and is `Some(vec![])` not `None`; (g) a package followed by an unterminated second one — agrees; (h) CRLF line endings — agrees; (i) UTF-8 BOM prefix — agrees. **Sabotage.** Edited the clone's `declares_a_package` to `{ let _ = file; false }` (gate always closed) and reran `cargo test -p vlog_linter -- interfaces::`: **9 of the dev's+QA's package tests fail**, including the dev's own `every_fixture_answers_what_a_text_built_index_ answers`, `only_a_package_item_opens_the_gate`, and `a_name_declared_twice_in_one_file_answers_with_the_first`, plus 6 of the QA attack fixtures. The equality oracle catches a broken gate exactly as intended. `interfaces.rs` was restored byte-for-byte afterward (diffed against the pre-sabotage copy: clean) and the full suite re-run clean (23 passed under `interfaces::`, 0 failed). **(b) duplicate-in-one-file pin.** Independently re-derived, not just trusted: constructing `package p; A=1; endpackage package p; B=2; endpackage` by hand and calling `package_exports` gives `Some(["A"])` — the first declaration's members, not `None`. This matches the dev's documented pre-existing answer exactly; it is the one-file index's behavior (unchanged by this lane) and the CLI's cross-file `None` comes from `Census::of`'s merge, confirmed separately below. **`from_text` verbatim check.** `git show 5c9fdb2:crates/vlog_linter/src/ interfaces.rs` has no `package_tests` module (P3 added it), so the "verbatim" claim was checked against the actual pre-P3 production body instead: the current `package_tests::from_text` is character-for-character the same construction `package_exports` used to be at `5c9fdb2` (`let index = WorkspaceIndex::build(...)`, same two-step `units_of` + `reexported_packages`/`members_of` query) — confirmed by diffing the two snippets by hand. **3. LINT SILENCE PARITY.** Built a fixture tree the dev did not have (`scratchpad/qa-p3/fixtree`, 16 files) covering every shape the task named: a used import, an unused import, an import of an unknown package, an import of a package declared twice across files, an `a_pkg → b_pkg` re-export chain used through `b_pkg`, a second independent re-export chain (`c_pkg → d_pkg`) used through a wildcard, a package behind an `` `ifdef`` (never defined — the census still sees the package item, matching the dev's own "package behind a directive" fixture's finding: lucisv does not evaluate conditionals structurally), and a waiver file waiving `unused-import`. Ran `clone-head/target/release/lucisv` (pre-P3, sha `81bb40a2…`) and the candidate (`target/release/lucisv`, sha `2c16b321…`) over this tree: - `check --select error,warning,style`: stdout **byte-identical**, exit 1 both. 2 `unused-import` findings (`unused_import.sv`, `ifdef_import.sv`); the re-export/unknown/duplicate-package imports and the used imports are silent on both binaries, as expected. - `check` (default): stdout byte-identical, exit 1 both (package-filename and endif-comment findings only — `unused-import` is style-only, off by default on both). - `check --select error,warning,style --fix` on two copies of the tree: stdout identical once the two temp-dir paths are normalized out; **the fixed files themselves are byte-identical** (`diff -r` clean) — this answers the "does `unused-import` have a fix, and does `--fix` diff clean" question: yes, it deletes the whole `import` line (`Applicability::Safe`), and both binaries produce the same edit. - A waiver file (`waive --rule=unused-import --location=unused_import.sv`): both binaries silence the waived finding and exit 0, stdout identical (empty). **4. CORPUS.** Re-ran all five cells independently (not reusing the dev's saved captures) with `~/.cache/lucisv-baselines/lucisv-0.50.0` as reference and `target/release/lucisv` as candidate (sha confirmed matching the tracker beforehand, no rebuild). Captured stdout only (`2>/dev/null` — the `found N violations` summary is on stderr, `crates/lucisv/src/lint.rs:753`, which the first attempt without redirection discipline conflated; corrected before drawing conclusions). Every cell: reference and candidate stdout **byte-identical**, exit codes equal (1, 1, 1, 2, 1 — `hw/vendor` is 2 for both, a pre-existing format failure unrelated to this lane), and the hashes match the tracker's quoted values exactly: | Cell | sha256 | Lines | Matches tracker | |---|---|---:|---| | `hw/ip` default | `c2444712e23e…` | 445 | yes | | `hw/ip` all-style | `97201de03bca…` | 7751 (17 `unused-import`) | yes | | `hw/ip` minus rule | `58780c3e81b8…` | 7734 | yes | | `hw/vendor` all-style | `1ce51659c4ab…` | 1666 | yes | | `hw/dv` all-style | `d7913e5f5846…` | 1158 | yes | `git status --porcelain` on opentitan checked and unchanged after every one of these ten invocations. **5. TIMING.** Re-took `hw/ip` all-style / minus-rule, 3 trials alternating binary order, `/usr/bin/time -l`, both binaries as in §4, every child under `tools/guard.sh`. **Machine load was elevated** (1-minute sample 4.76–5.11 at run time, still carrying a 5-minute average around 22–23 from earlier work this session), so — per instruction — only the paired (all-style − minus-rule) increment is read, not absolute seconds: | | trial 1 | trial 2 | trial 3 | median | |---|---:|---:|---:|---:| | reference increment | +150 ms | +140 ms | +160 ms | **+150 ms** | | candidate increment | −30 ms | +30 ms | −20 ms | **−20 ms (noise floor)** | The reference's increment lands inside the dev's own reported range (141.7–158.3 ms across the dev's three binaries). The candidate's increment is indistinguishable from zero at `/usr/bin/time`'s ~10 ms rounding — fully consistent with the dev's claimed 5.0 ms residual, and independently confirms **well over 50 %** of the increment is gone (the target). Peak RSS, maximum of 3 trials: reference **211.0 MiB**, candidate **196.2 MiB** — not worse, matching the dev's direction (219–221 → ~196– 202 MiB across both passes). `git status --porcelain` on opentitan unchanged after all 12 timed invocations. **6. Traceability.** All hashes and counts in the tracker's P3 cells and experiment `P3-2026-09-07` were checked against `~/.cache/lucisv-perf/take5-p3/` and reproduce: `binaries.sha256` matches the two rebuilt QA binaries exactly; the five `stdout-*` capture files' sha256 match the hashes quoted in the README/tracker; `p3-threeway.jsonl` and `p3-results.jsonl` exist and are non-empty. Package-file counts re-derived with a plain `grep -lE '^[[:space:]]*package[[:space:]]+'` over each tree's `.sv`/`.svh` files (a different method than whatever the dev used, deliberately): `hw/ip` **181/1805**, `hw/vendor` **24/285**, `hw/dv` **40/365** — all three exact matches. **7. `harvest_one` lex-only path.** Read the function (`crates/lucisv/src/lint.rs:100-108`): the `if !interfaces && !packages` branch returns `words::harvest_text(&src)` before any call to `ParsedSource::parse`, so the neither-wanted path is lex-only by construction — not something that could regress silently without a diff touching this exact `if`. **Finding (non-blocking):** there is no test in `lint.rs`'s own `mod tests` pinning this contract, and adding one is not a one-liner — `Job` has no test constructor and its `config: vlog_formatter::Config` field has no `Default` impl, so a pinning test needs a small `Job`-building test helper first. Left as a finding rather than fixed in the main tree per the QA policy on non-trivial fixes; suggested for a future small addition (a `Job`-builder test helper plus one assertion that `harvest_one(job, false, false)` returns empty `declared`/`exports` and equals `words::harvest_text`). **Topology edges for the lead** (from the feature README's Handshakes, independently confirmed correct by the `cargo tree` check in §1 and the code reading in §2): apply both — `lucisv ──▶ vlog_linter` gains `package_exports_in`, and `vlog_linter ──▶ vlog_semantic` gains `FileFacts::from_analysis` + `IndexBuilder::{add_facts, finish}` as a read the CLI package half now depends on. **Nothing else was touched.** No production files were edited in the main tree; the sabotage and QA attack fixtures live only in the scratch clone (`/private/tmp/.../scratchpad/qa-p3/clone`), which is left in place as QA evidence rather than deleted. ## Review **2026-09-07 (lead).** Accepted. Read `package_exports_in`, `declares_a_package`, `one_file_index`, `harvest_one`, the equality test's verbatim pre-P3 reference, the six CLI tests, the tracker's P3 entry and both logs; QA's parity over a fixture tree (`check`, all-style, `--fix` outputs and fixed files, a waiver) against a HEAD build and its byte-diff of the five corpus cells are the acceptance. - The plan's own shape, delivered as written: one parse in the census, the package half read off it, the AST gate (never text) sparing the nine files in ten that declare no package, the one-file index assembled from the caller's parse through §P2's `FileFacts::from_analysis` — no new semantic API, the CLI still without a direct semantic dependency. - 96 % of the rule's increment removed (142 → 5 ms on `hw/ip`, RSS down 8.6 %) with every output byte-identical; the target was half. - The third parse (the lint pass's own) stays, deliberately: retaining 1 805 trees against a 200 MiB peak is the memory-for-time trade the plan says to refuse without a recorded case. Filed as a number, not taken. - QA's non-blocking finding — no test pins `harvest_one`'s lex-only path when neither half is wanted — noted; the code reads correctly and a test needs a `Job` constructor the module does not have. Loop-3 list. - The "duplicate package within one file reports the first declaration's members" answer is pre-existing and now pinned, which is better than before. Docs applied at merge: topo edges `lucisv ──▶ vlog_linter` (`package_exports_in`) and `vlog_linter ──▶ vlog_semantic` (`FileFacts::from_analysis` + `IndexBuilder`).