Feature docs for the responsiveness round, and a perf record

Three new feature READMEs — change-debounce, port-detail-spans,
interactive-latency — each with the mandated sections, dev work logs,
QA findings and their dispositions, and the lead's review. Plus
`docs/perf/README.md`, the record of what was measured, on what, on
which machine, and with which command, so a later round can say
whether it made something faster or only different.

`topo.md` is added to the tree: the dependency topology the round was
planned against, with this round's new edges — the `detail_span` and
`symbols_named` handshake between the server and `vlog_semantic`, and
the facts-format edge to index persistence.

The perf record keeps its losses as well as its wins. A keystroke
followed by nothing now publishes at 164 ms rather than one
reanalysis, because it waits out the quiet period; a perf document
that only records improvements is not a perf document.

Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
lucioandClaude Opus 5 committed 2026-08-28 03:16:54 -07:00
1 parent 12d0bbad51
commit 574ab833e3
9 files changed
+2436 -11

No files matched your search

+290
View File
@@ -0,0 +1,290 @@
# change-debounce
## Goal
Stop paying a full reanalysis for every keystroke. Before this round each
`textDocument/didChange` notification ran `set_document` immediately — lex,
parse, `analyze`, `resolve_external`, lint, publish — so a burst of ten
keystrokes cost ten of everything and nine of those answers were thrown away
before anyone could read them. A `didChange` now only records the buffer's new
text as *dirty*; the analysis runs at the first moment anything actually needs
it: the next request, the next non-`didChange` notification, or a 150 ms
quiet-period timer in the message loop. The buffer's **text** is still exactly
current after every notification — only the analysis of it is deferred — so
nothing that reads `didChange` results out of order can see a stale buffer.
On a 10 000-line file one deferred keystroke saves 31 ms of work
(`docs/perf/README.md`); a ten-keystroke burst saves nine of them.
## Assumptions
- **A client sends a burst, not a single change.** Typing produces
notifications faster than 150 ms apart; the debounce only pays off while
that is true, and costs at most 150 ms of latency when it is not.
- **150 ms is short enough not to be felt and long enough to coalesce a
burst.** It is the same order as the debounce every mainstream language
server uses. It is a constant (`CHANGE_DEBOUNCE` in `server.rs`), not a
setting: a knob here would be one more thing to get wrong, and no user has
asked for one (`TODO.md` §7, "no option explosion").
- **Diagnostics are the one answer nobody requests.** A pushing client never
asks for them, so waiting for "the next request" alone would leave a file
undiagnosed indefinitely for a user who types and then stops. That is the
whole reason the timer exists, rather than flushing only on demand.
- **A flush is cheap to trigger from anywhere.** `flush_dirty` returns
immediately when nothing is dirty, so the calls at the top of `request` and
`notification` cost a `Vec::is_empty` on every message.
- **Order within a burst does not matter, order across buffers does.** Dirty
buffers are flushed oldest-first (`mark_dirty` replaces an entry in place
rather than moving it to the back), so the sequence of `publish` calls a
client sees for two edited files is the order they were first edited in.
- **Losing an unanalyzed change with its buffer is correct.** `didClose`
drops the buffer's pending text: there is nothing left to flush it into,
and the client is not looking at the file any more. The drop happens at the
*top* of `notification`, ahead of the universal flush — doing it in the
`didClose` arm is too late, because the flush has already run by then (QA,
CD-1). Closing one buffer says nothing about the others, so every other
dirty buffer flushes on that same notification exactly as before.
## Handshakes
- **Amends `docs/features/incremental-sync/README.md`'s pinned invariant.**
That round promised "one `didChange` = one `set_document` = one generation
bump, however many ranges". The promise is now: **one *flush* is one
`set_document`, one generation bump and one `publish` per dirty buffer** —
however many ranges *and however many notifications* were coalesced into it.
Everything the old promise protected still holds: the generation counter
(which is `docs/features/pull-diagnostics/README.md`'s whole `resultId`)
never moves twice for work that happened once, and never fails to move for
a buffer whose text changed. `incremental-sync`'s own test,
`one_notification_is_one_generation_bump_however_many_ranges`, still passes
unchanged, because the test helper flushes after each notification — which
is exactly the quiet-period timer firing.
- **Observable consequence, pinned in `crates/lucisv_server/tests/e2e.rs`**
(`incremental_changes_are_advertised_and_applied_over_the_wire`):
**intermediate diagnostics states are no longer published**. Two changes
arriving back to back — the first breaking a line, the second finishing it
— used to produce three publishes (open, broken, fixed) and now produce two
(open, composed). Every state that *is* published is a state the buffer
really passed through; there are simply fewer of them. That test asserted
the old count and now asserts the new one, with the reason written beside
it.
- **Consumes `sync::apply_changes` unchanged.** Ranged changes are composed
against the newest text the server holds, which while a buffer is dirty is
the *pending* text, not the last analyzed one. `Server::notification` looks
in `dirty` before `workspace.document`. Nothing in `sync.rs` moved.
- **Consumes `lsp_server`'s queue as a `std::sync::mpsc` receiver.** The
timer is `Receiver::recv_timeout` on the queue `cancel-request` already
introduced (`docs/features/cancel-request/README.md`); no thread and no
timer object was added. A `Disconnected` receiver ends the loop exactly as
the old `while let Ok(..)` did.
- **Promises every request still sees the client's own changes.** The flush
at the top of `Server::request` runs before dispatch, so a request answered
after a `didChange` is answered from that change's analysis — the order
contract the loop always had. The large-file fast path is behind that
flush, not in front of it.
- **No protocol change, no settings change, no index change.** The
capabilities advertised at `initialize` are byte-identical.
## Status / TODO
- [x] `dirty: Vec<(Uri, String)>` on `Server` — newest text per buffer, in
first-dirtied order.
- [x] `mark_dirty` replaces in place, so a burst does not reorder buffers.
- [x] `flush_dirty` — one `set_document` + one `publish` per dirty buffer.
- [x] `didChange` composes ranges against the pending text when there is one.
- [x] Flush on every request, before dispatch.
- [x] Flush on every notification that is not a `didChange`.
- [x] `CHANGE_DEBOUNCE` (150 ms) quiet-period flush in `run`, via
`recv_timeout`, only while something is dirty.
- [x] `didClose` drops the buffer's pending change — before the flush, so the
drop is real (QA, CD-1), pinned by
`closing_a_dirty_buffer_discards_its_change_and_leaves_the_others_alone`.
- [x] Test: a burst is one reparse
(`a_burst_of_changes_coalesces_into_one_reparse`).
- [x] Server tests drive one notification at a time, so the test helper
`change()` flushes — documented there as the timer firing.
- [x] e2e: the publish count and the reason for it.
- [ ] Not done: a flush for a *long* burst that never pauses (a paste-and-hold
or a client replaying a file's history sends changes closer together
than 150 ms forever). Today such a burst is analyzed when it ends or
when the next request arrives. A "flush after N pending changes"
backstop is the obvious answer if anyone ever reports it; it is not
written because no client behaves that way and an untested backstop is
worse than none.
## Work log
**2026-08-28 — dev.** Implemented as part of the LSP performance round
(plan: "Improve LSP performance + hover accuracy", part A1).
- The deferral is a `Vec`, not a `HashMap`: it holds one entry per *dirty*
buffer, which is one in practice and two while a user alt-tabs. A linear
scan of that is cheaper than hashing a `Uri`, and the `Vec` gives the flush
order for free.
- Deferred **analysis only, never text**. The alternative — deferring
`apply_changes` too and keeping a queue of unapplied changes — was
rejected: every reader of `Document::text` would then need to know about
the queue, and the ones that forgot would be silently wrong. Composing the
text eagerly keeps the pending state to exactly one `String` that only
`didChange` and `flush_dirty` know about.
- The flush points were chosen to be exhaustive rather than clever: *every*
request and *every* notification except the one being deferred. Anything
that needs analysis is downstream of one of those two, so there is no
handler that has to remember to flush for itself.
- `run` only arms the timeout while something is dirty, so an idle server
still blocks in `recv()` and wakes for nothing.
- The server unit tests drive notifications one at a time through a helper
rather than through the loop, so no burst ever forms and nothing would
flush them; the helper flushes explicitly, which is the timer's behavior.
Three tests that hand-rolled a `didChange` notification were moved onto
that helper.
**2026-08-28 — dev (QA fix).**
- **CD-1 — fixed.** The `didClose` arm's `dirty.retain` was dead code: the
universal flush at the top of `notification` had already drained `dirty`
through `std::mem::take` by the time the arm ran, so a buffer closed
mid-edit paid a full `Document::new` and published its real diagnostics one
line before the close cleared them. The retain moved to the top of
`notification`, *ahead* of the flush, guarded on the method name; the arm's
comment now says where the drop happened instead of pretending to do it.
- The uri has to be read without consuming the notification, since
`extract` takes it by value and the arm below still needs it. That is a
four-line `closing_uri` beside `extract`, deserializing a clone of the
params — a `didClose`'s params are a single uri, so the clone is not
worth avoiding with a peek into the raw `Value`. `None` (params that do
not parse) drops nothing, which is exactly what the arm below already
does with the same params.
- The "flush on every notification but `didChange`" rule is unchanged: the
flush still runs for `didClose`, and every *other* dirty buffer still
goes through it. What changed is only that the closing buffer is no
longer in `dirty` when it does.
- Pinned by `closing_a_dirty_buffer_discards_its_change_and_leaves_the_others_alone`
(`server.rs`): two buffers dirtied with text that would diagnose, one
closed with no request in between; the generation bumps exactly once (the
buffer still open), the closed buffer gets exactly one publish and it is
the clearing one, and the other buffer's pending edit is published as
usual. Verified the test fails on the pre-fix code — `left: 5, right: 4`
on the generation assertion — before keeping it.
## QA log
**2026-08-28 — QA.** Gates run and green: `cargo fmt --check`,
`cargo clippy --all-targets --workspace -- -D warnings`, `cargo test
--workspace` (0 failed everywhere; `lucisv_server`: 1179 passed, 19 ignored
perf tests), `cargo test -p vlog_formatter` (114 passed). All findings below
were reproduced with temporary `#[test]`s added to `server.rs`, run, and then
removed once confirmed — none are left in the tree.
- **Finding CD-1 (medium — contradicts a checked-off invariant, wastes work,
does not corrupt anything).** `didClose` does **not** actually drop a
buffer's pending dirty change before analyzing it. `Server::notification`
(`server.rs:1247`) flushes unconditionally for any non-`didChange` method
(`server.rs:1253`, `if method != DidChangeTextDocument::METHOD { self
.flush_dirty(); }`) — and `didClose` is such a method. That flush runs
*before* the `match` statement even reaches the `DidCloseTextDocument::
METHOD` arm (`server.rs:1407`), so by the time `self.dirty.retain(|(pending,
_)| *pending != uri)` executes (`server.rs:1413`), `flush_dirty` has already
drained `self.dirty` via `std::mem::take` — the retain is a no-op in the
normal flow. Net effect: closing a buffer that was mid-edit costs one full,
wasted reparse + `publish` of the real (about-to-be-discarded) diagnostics,
immediately followed by the close handler's own `send_diagnostics(uri,
Vec::new())` clearing them — **two** publishes instead of the zero extra
ones the design claims. This directly contradicts both the checked-off
status-line "`[x]` `didClose` drops the buffer's pending change" and the
code comment beside the (dead) retain: "there is nothing left to flush it
into" — there is, and it does get flushed.
- Repro (temporary test, `server.rs`, removed after confirming): open a
clean buffer (`module m;\nendmodule\n`), drain the open publish, note
`generation`, send one `didChange` to `module m;\n wire ;\nendmodule\n`
(introduces a parse error, buffer stays dirty — `generation` provably
unchanged, `dirty` non-empty), then send `didClose` with **no** request
in between (`session.notify`, which calls `Server::notification`
directly, exactly the production path — no manual flush helper
involved). Observed: `generation` bumps by exactly one during the
`didClose` call (`2` → `3`), and `session.published()` returns **2**
messages: one carrying the real parse-error diagnostic
(`"expected identifier (found \";\")"`), then one with `diagnostics: []`.
- Not a data-corruption bug — the client ends up with the correct final
state (empty diagnostics for a closed file) — but it is a real,
reproducible functional gap in exactly the case the debounce is supposed
to help most: a user who edits and then immediately closes a buffer pays
the full analysis cost the feature exists to avoid, silently. Left
unfixed (not small/unambiguous — the right fix wants a decision about
whether the top-of-`notification` flush should special-case `didClose`,
or whether `didClose` should remove its own `dirty` entry *before* that
flush runs, which touches the "flush on every notification but
`didChange`" rule this round explicitly checked off).
- **Attack angles from the brief, checked and clean:**
- *An un-flushed edge, generally.* Every request and every non-`didChange`
notification flushes at its own top (`server.rs:1253` for notifications,
the equivalent at the top of `request`), so the only genuinely
un-flushed state is "nothing has asked for analysis yet" — which is
exactly what the quiet-period timer exists to bound at 150 ms, and the
documented, un-checked TODO item (a burst that never pauses) is real but
already honestly disclosed, not silently missing.
- *`didChange` on a file the client never opened.* `mark_dirty` does not
require a prior `didOpen`, and neither did the pre-debounce
`set_document` call it replaces — `flush_dirty`'s `set_document` creates
the buffer exactly as before. No new behavior here.
- *`didChange` racing `didSave`.* `didSave` is not `didChange`, so it
flushes first (`server.rs:1253`) — a save's reindex always sees the
latest edited text analyzed, never a stale buffer racing a fresh disk
scan.
- *Version-number ordering.* The server does not track LSP version numbers
at all (`publishDiagnostics`'s own `version` field is hard-coded `None`
at `server.rs:1848`, unchanged by this round) — nothing new to get out of
order.
- *Pending vs. analyzed text observed inconsistent by a request.* Cannot
happen: `request` flushes before dispatch (`server.rs`'s `fn request`),
so a request is always answered from the analysis of whatever is
currently held, dirty or not.
- *The `e2e.rs` publish-count change (3 → 2).* Confirmed the buffer
genuinely passed through both published states and no diagnostic was
lost: traced `incremental_changes_are_advertised_and_applied_over_the_wire`
— the two `didChange` notifications and the `textDocument/formatting`
request all arrive in one write to the mock transport, so the request's
own top-of-`request` flush (or the burst's internal ordering) coalesces
both notifications into the one flush that produces publish #2; publish
#1 is the clean `didOpen`. The removed middle publish (the transiently
*broken* half-edited state) was never a state a real, unhurried client
would see anyway — it is the debounce's whole point.
- *`a_burst_of_changes_coalesces_into_one_reparse`.* Re-derived by hand:
`generation` provably does not move across the two-notification burst,
then moves by exactly one at the first request after it, and `dirty` is
empty afterward — matches the claimed semantics exactly.
- **Perf claims (A1's "before/after" in `docs/perf/README.md`).** Arithmetic
over already-measured numbers, not a separate measurement — reviewed there,
no finding.
## Review
**2026-08-28 — lead.** Accepted. Gates re-run independently of both agents:
`cargo fmt --check` clean, `cargo clippy --all-targets --workspace -D
warnings` silent, `cargo test --workspace` green.
The shape is right. Deferring analysis while applying text immediately is the
standard split, and flushing before every request and before every
non-`didChange` notification means no handler ever reads a stale buffer —
today's correctness guarantee is preserved exactly, and only keystroke-storm
reparses are coalesced. The quiet-period timer in `run()` matters as much as
the coalescing: diagnostics are the one answer a client never asks for, so a
burst that ends in silence still gets drawn.
QA's CD-1 was a real finding and correctly diagnosed: the universal flush ran
*before* the `didClose` arm, so the arm's `retain` was dead and a buffer
closed mid-burst paid a full `Document::new` and published diagnostics for a
file the user had stopped looking at, only to clear them a line later. The
fix drops the pending text ahead of the flush rather than special-casing the
flush, which keeps "every other dirty buffer still flushes" true by
construction. The dev verified the pinning test fails on pre-fix code before
keeping it; that is the right standard.
The one honest cost is recorded in `docs/perf/README.md` and is not hidden: a
keystroke with *nothing* following it now publishes at 164 ms rather than one
flush, because it waits out the 150 ms quiet period. Any request flushes
early, so a real editor sees 4.35 ms / 37.6 ms instead — but the regression
is real for a client that asks for nothing, and the number is written down
rather than argued away.
@@ -59,6 +59,11 @@ entirely whenever it could be the wrong line.
is the only thing that colours a hover card.
- Nothing is added to `Def`, to the facts file, or to `FACTS_FORMAT`; a cache
written before this round is still current after it.
**Superseded 2026-08-28 by `docs/features/port-detail-spans/README.md`**,
which adds `Def::detail_span`, writes it in every declaration record and
bumps `FACTS_FORMAT` 2 → 3, so a store written before *that* round is
discarded. This round's own promise held while it was this round's to
make; the index is text-free either way (a span is not text).
- The heading line `**label** — declared in `file:line`` is unchanged, so a
client (or a test) reading only that half sees exactly what it saw before.
@@ -119,6 +124,13 @@ The character cap counts `char`s and cuts on a boundary.
- Not done, deliberately: no facts/cache change, nothing in `vlog_semantic`,
no TODO.md edit (no existing checklist item covers this; §8's hover items
are all already checked, and inventing one is out of scope).
- [x] **2026-08-28**: one disk read per file per hover (`disk_view` memo);
QA finding 4 closed.
- [x] **2026-08-28**: `live_symbol` (and `nav::indexed_references`) look a
name up instead of scanning every symbol, with the first-match
tie-break pinned by test.
- [x] **2026-08-28**: a CRLF file's snippet no longer carries an interior
`\r` into the fence; QA finding 2 closed.
## Work log
@@ -164,6 +176,77 @@ The character cap counts `char`s and cuts on a boundary.
| `a_declaration_spanning_many_lines_is_cut_at_the_line_limit` | the line cap, via an open module whose `decl_span` is its body |
| `two_files_declaring_one_name_each_get_their_own_snippet` | ambiguous name: both headings, both snippets |
### 2026-08-28 — dev (performance: one disk read, one name lookup)
Parts A2 and A3 of the "Improve LSP performance + hover accuracy" round.
Behavior of every card is unchanged; both items are the same answer, reached
with less work. Numbers in `docs/perf/README.md`.
- **A2 — one read per file per hover.** A hover into a *closed* file used to
read that file and build a `LineIndex` over it twice: once in
`locate::line_number` for the `file:line` heading, once in
`declaration_snippet` for the fenced lines. This is QA's finding 4 below,
and it is now closed. `symbol_hover` holds a per-request memo — one
`(path, text, LineIndex)` in `disk_view` — that the heading and the snippet
both read, and `declaration_snippet` no longer touches the disk at all: it
is now the *open-buffer* path only, with the closed-file path inlined in
`symbol_hover` beside the heading it shares a read with. The
`spells_exactly` guard applies on both paths exactly as before. A card
naming one file twice (two declarations in one file) now pays for one read,
not two, which is why the memo is keyed by path rather than being a single
`Option` per candidate.
- Measured: 34 ms → 16.3 ms on QA's own 31.7 MB measurement, and 141 µs of
a 148 µs hover at 10 000 lines is that one read. See `docs/perf`.
- QA's measurement test was renamed
`hovering_into_a_large_closed_file_reads_it_twice` →
`..._reads_it_once`, since the doubling it was named for is gone. The QA
log below still names the old spelling; that section is QA's to amend.
- **A3 — `live_symbol` stops scanning every symbol.** Walking the whole
buffer's symbol table and calling `nav::indexed_def_for_symbol` (two index
lookups) on every symbol whose name happened to match — and reaching every
symbol whose name did not — became a name-keyed lookup:
`vlog_semantic::Semantics::symbols_named(name)`, two binary searches over a
side table of symbol ids sorted by name, built once during `analyze`. Only
same-named declarations are probed. A side table rather than a
`HashMap<String, Vec<SymbolId>>` so that `Semantics` — which is cloned per
document — does not carry a second copy of every name it already holds;
four bytes per symbol against a `String` per symbol.
- **The tie-break is preserved.** The map's lists are built by walking the
symbols in order, so `symbols_named` yields declaration order — the same
order, and the same first match, the old `symbols().iter().find(..)`
made. Pinned by `looking_a_name_up_answers_exactly_what_scanning_every_symbol_would`
in `crates/vlog_semantic/tests/semantics.rs`, which compares the two
answers directly and asserts the earlier declaration comes first. QA's
`duplicate_live_declarations_of_one_name_pick_the_first_one_silently`
(finding 3 below) still passes, unchanged.
- `nav.rs`'s `indexed_references` had the same scan-by-name for the
declaration's live span; it is the same swap and was made in the same
change, for the same reason.
- `vlog_refactor::ports.rs:1154` has a third one (`symbols().iter()
.position(|s| s.name == port && …)`). It is not a trivial swap — the
predicate carries a kind and a span test and the code wants the
*position* as a `SymbolId` — and it is in another crate, so it is left
alone and recorded here rather than done.
- Cost: four bytes per symbol. Measured saving on the lookup alone:
8.41 µs → 133 ns over a 5 001-symbol file (`docs/perf/README.md`).
### 2026-08-28 — dev (CRLF, closing QA finding 2)
- Finding 2 below — a CRLF file's multi-line snippet keeping an interior
`\r` inside the fence — is **fixed**, as part of `port-detail-spans`' PDS-4.
Every line a card shows now goes through `attached_lines`, which strips a
trailing `\r` as it composes each line; that covers both this feature's
snippet path and `local_text`'s in-file path, which QA named as having the
same property, because both reach it through `fenced_sections`. Display
text only: no buffer is written.
- QA's pinned regression test was named for the old behaviour
(`a_crlf_multiline_snippet_keeps_interior_carriage_returns`) and asserted
it; it is now `a_crlf_multiline_snippet_carries_no_carriage_returns` and
asserts the opposite, plus that the lines read as written. The QA log below
still names the old spelling; that section is QA's to amend.
- No other change to this feature. `spells_exactly`, the caps and the
disk/live split are untouched.
## QA log
### 2026-08-27 — QA
@@ -277,6 +360,12 @@ charter's "note it, don't redesign" rather than attempted.
`hovering_into_a_large_closed_file_reads_it_twice`, `hover.rs:1325`. Run
with `cargo test --release -p lucisv_server large_closed -- --ignored
--nocapture`.
- **Amended 2026-08-28 — QA.** Closed by A2 (`docs/perf/README.md`):
`symbol_hover`'s `disk_view` memo now shares one read + one `LineIndex`
between the heading and the snippet. Re-ran the same measurement (now
named `..._reads_it_once`): **17.0 ms**, against the documented
"34 ms → 16.3 ms" — matches within the run-to-run noise `docs/perf/
README.md` itself calls out. No longer an open finding.
**Verified, no finding** (angles from the charter that turned up nothing):
UTF-8 multi-byte content before a declaration, on the same file, does not
+9
View File
@@ -75,6 +75,15 @@ slice that can panic.
and no bump would let a changed buffer answer "unchanged". One notification =
one reparse = one stamp = one `publish`. Pinned by
`one_notification_is_one_generation_bump_however_many_ranges`.
**Amended 2026-08-28 by `docs/features/change-debounce/README.md`**: a
`didChange` now records the composed text as dirty and the analysis runs at
the next flush, so the promise reads **one *flush* is one `set_document`,
one generation bump and one publish per dirty buffer** — however many
ranges *and however many notifications* it coalesced. What the promise
protects is unchanged: the counter never moves twice for work done once and
never fails to move for a buffer whose text changed. The test above still
passes as written; its helper flushes after each notification, which is the
quiet-period timer firing.
- **Changes what the client is told at `initialize`.**
`text_document_sync` moves from `Kind(FULL)` to `Options { open_close: true,
change: INCREMENTAL, save: { include_text: false } }`. The `open_close` and
+440
View File
@@ -0,0 +1,440 @@
# interactive-latency
## Goal
Make the request and notification paths a user *feels* — the ones that run
while they type and move the cursor — cost what they have to cost and no
more, and say with measured numbers where the rest of the time goes. Round 1
(`docs/perf/README.md`) established the baseline and named the open question
it could not answer from inside the crate: what a `didChange` →
`publishDiagnostics` round trip actually takes over the wire. This round
answers that, breaks one flush down stage by stage, and takes the
identity-safe wins the breakdown justifies — which turned out to be six token
lookups that were sweeping the whole buffer for something a binary search
answers in twenty nanoseconds. Nothing on the parse path was touched: the
measurements say the remaining cost is lexing and parsing, and that is a
change this round deliberately does not make.
## Assumptions
- **The token stream rises and never overlaps.** Every binary search added
here rests on one property of `Document.tokens`: the lexer emits tokens in
source order, so `end[i] <= start[i+1] <= end[i+1]` and both
`span.start < offset` and `span.end < offset` are monotone predicates over
the vector. That is the whole precondition `partition_point` needs, and it
is pinned by `state::tests::the_token_stream_rises_and_never_overlaps` —
the test that would fail first if the lexer ever changed shape. Nothing
here assumes tokens are non-empty: the `Eof` sentinel is zero-width, and
every argument below survives it.
- **No benchmark dependency**, unchanged from round 1: `std::time::Instant`,
`#[ignore]`d tests, no `criterion`. `CLAUDE.md` requires a written
justification for a new dependency and there is none to write.
- **A measurement asserts nothing about duration.** A test that fails when
the machine is busy is a test that gets deleted.
- **The e2e round trip is a real session.** It spawns the shipped binary and
speaks framed JSON-RPC at it, so the number includes the pipes, the JSON,
the debounce timer and the flush. It cannot be taken from inside the crate,
which is exactly why round 1 could not take it.
- **The generated module is uniform, and real RTL is not.** Both generators
build the same repeated four-line block. The numbers are a scale, not a
prediction for any given file.
## Handshakes
- **`vlog_parser` → this crate (consumed, unchanged).** The binary searches
consume the ordering property of `tokenize`'s output described above.
Nothing was asked of `vlog_parser` and nothing in it changed. If it ever
emits tokens out of order, the pinning test in `state.rs` fails before any
handler answers wrongly.
- **`state.rs` → `selection.rs`, `on_type.rs`, `completion.rs` (new,
internal).** Two free functions, `first_token_reaching` and
`first_token_from`, are published from `state.rs` beside `Document`. They
are the single place the monotonicity argument is written down; every call
site is one comparison on top of one of them. `inline.rs` uses a third
predicate (`span.end <= offset`) written at its own call site, because it
has one user and its own local proof.
- **`e2e.rs`'s `Live::finish` now returns the publish count** it saw on the
way out. Existing callers ignore the value, which compiles unchanged. The
count is what turns "the debounce coalesces a burst" from arithmetic into a
measurement.
- **Two copies of one generator.** `perf::generated_module` and the copy in
`tests/e2e.rs` must stay the same shape, or the in-crate table and the
over-the-wire table in `docs/perf/README.md` stop being readable against
one another. `lucisv_server` is a binary crate, so an integration test
cannot import the original; the copy is commented as such at both ends.
- **Nothing was asked of `vlog_linter`.** The lint pass costs 1.40 ms of a
32 ms flush at 10 000 lines and walks the tree once per rule; that is
recorded in `docs/perf/README.md` as a future round's work, not requested
here.
## Status / TODO
- [x] Phase 1 — a stage-by-stage breakdown of one flush at 1k and 10k lines:
`tokenize`, `tokens.clone()`, `parse_tolerant`, `collect_defines`,
`analyze`, `resolve_external`, `LineIndex::new`, and the
`diagnostics::all` pass a publish runs (which is *not* inside
`Document::new`, and which round 1's table did not account for).
`perf::breaking_down_one_flushed_keystroke`.
- [x] Phase 1 — the end-to-end round trip round 1 listed as its own open
TODO: `didChange` → `publishDiagnostics` against the real binary, for a
single change, for a burst of ten, and for the change-then-request
shape a real editor produces.
`tests/e2e.rs::a_keystroke_round_trip_over_the_wire`.
- [x] Phase 2 — six token lookups swapped from a sweep to a binary search,
each with a test that walks **every byte** of a buffer written to have
plenty of touching tokens and asserts the search returns exactly what
the sweep returned.
- [x] Phase 2 — the three sweeps that are inherent left alone, with the
reason written down (below).
- [x] Phase 3 — decided against every change the breakdown did not justify,
with the number for each (below).
- [x] Phase 4 — `docs/perf/README.md` refreshed: both of round 1's open
TODOs resolved or restated, every figure re-measured on this machine.
Not done, deliberately, and each with the number that would justify it — the
list lives in `docs/perf/README.md`'s *What it would take to go faster* so it
sits beside the measurements rather than in a feature's checklist.
## The Phase 2 call sites, one by one
The predicate each site wants is *not* always "the token containing this
offset", so `Document::token_at` is not a drop-in for any of them. Each swap
below is argued from the ordering property, and each argument is pinned by a
test that compares the new expression against the old one at every byte of
`state::mixed_buffer(20)` — a buffer written with `a=b;`-style adjacent
punctuation, comments and strings precisely because the bytes that could tell
a search from a sweep are the ones two tokens share.
**Changed and proven.**
| site | wanted | now | test |
|---|---|---|---|
| `selection.rs` `enclosing` | the first token with `start <= offset <= end` | `first_token_reaching`, then one `covers` check | `selection::tests::the_innermost_step_is_the_token_the_sweep_returned_at_every_offset` |
| `on_type.rs` `statement_edit` | the token with `end == offset` | `first_token_reaching`, then one `==` | `on_type::tests::the_token_ending_at_the_cursor_is_the_one_the_sweep_returned` |
| `on_type.rs` `first_on_line` | the first non-`Eof` token with `start >= content` | `first_token_from`, then `find` over the tail | `on_type::tests::the_first_token_on_a_line_is_the_one_the_sweep_returned` |
| `completion.rs` `is_procedural` | the *index* of the token with `start == offset` | `first_token_from`, then one `==` | `completion::tests::the_scope_gates_answer_what_their_sweeps_answered` |
| `completion.rs` `balanced` | every token whose start is in `[from, at)` | a slice between two `first_token_from`s | the same test |
| `inline.rs` `triggered` | the **last** non-`Eof` token with `end <= offset` | `partition_point`, then `rposition` over the prefix | `inline::tests::the_last_token_before_the_cursor_is_the_one_the_reverse_sweep_found` |
Two of these deserve their reasoning spelled out, because they are the two
where a careless swap would have changed an answer:
- **`selection.rs` takes `span.end` inclusively.** At a byte two adjacent
tokens share, `find(covers)` returned the *earlier* of the two, while
`Document::token_at` — which uses `TextRange::contains`, end exclusive —
would return the later one. `first_token_reaching` returns the earlier one,
which is why it is the right primitive here and `token_at` is not.
- **`completion.rs`'s `balanced` was sweeping the whole buffer.** Its filter
had no upper bound to break on, so a cursor anywhere in a 10 000-line file
walked all 94 961 tokens to reach a window a few dozen tokens wide. It is
the largest of the six by some way: 130 µs → 36 ns.
**Left alone, with the reason.**
- **`signature.rs` `enclosing_list` (:138) and `active_entry` (:231).**
Inherent. Both maintain a parenthesis-depth stack, and a depth at the
cursor is a function of *every* bracket before it — there is no prefix a
binary search may skip without recomputing what it skipped. Both already
break at the cursor rather than running to the end of the buffer, so
neither is a whole-buffer sweep; bounding the loop with a binary search
instead of the `break` would save one comparison per token and change
nothing else, which is not worth the edit.
- **`pairs.rs` `analyze` (:230).** Inherent, and not a position query at
all: it matches *every* scope keyword in the stream and returns the whole
pair set. There is no offset to search for.
- **`completion.rs` `in_comment_or_string` (:553).** Left, and its existing
doc comment already says why: comments are lexer trivia hanging off
whichever token happens to follow or precede them, so the token whose
`leading` holds a comment at a given byte is not the token a search for
that byte would find. A correct search would have to reason about
attachment; a wrong one would offer a completion list inside a comment.
This is the one remaining per-keystroke whole-buffer walk, and it is
recorded as such in `docs/perf/README.md` rather than guessed at.
- **`completion.rs` `word_tier` (:355), `candidates.rs` (:218),
`folding.rs` (:58).** Inherent: each needs every token in the file, not a
token at an offset.
## Work log
**2026-08-28 — dev (round 2).**
*Phase 1, measured first.* Added
`perf::breaking_down_one_flushed_keystroke` and
`perf::finding_one_token_against_sweeping_the_stream` to the existing
`perf.rs` module, and `a_keystroke_round_trip_over_the_wire` to `e2e.rs`.
The e2e measurement reuses the `Live` session helper that already existed in
that file for the watched-files test rather than adding a second one; the
only change to shared code is that `Live::finish` now returns the number of
`publishDiagnostics` it saw while shutting down. That count is the point: a
buffer left dirty by a burst is flushed before the next *request* is
answered, so by the time `shutdown` comes back every publish the burst was
going to produce has arrived. A burst of ten keystrokes produces **one**.
The breakdown decided everything that followed. At 10 000 lines a flush is
31 ms, and 24.5 ms of it is `tokenize` plus `parse_tolerant`. `analyze` is
11 %, the diagnostics pass another 4 % on top of the flush, and
`resolve_external` — which the round's brief named as a possible target — is
**49 µs, one part in six hundred**. There is nothing to skip there.
*Phase 2.* Six sweeps became binary searches, on the strength of the
`finding_one_token` measurement: 77 µs → 20 ns for a cursor lookup at 10 000
lines, and 130 µs → 36 ns for `balanced`'s window. The two primitives live in
`state.rs` beside `Document::token_at`, which is where the one-paragraph
monotonicity argument they all rest on is written; `inline.rs`'s third
predicate is written at its own call site because it has one user.
Every swap is pinned by a test that compares it against the code it replaced
at every byte of a shared awkward buffer (`state::mixed_buffer`, whose one
job is to have plenty of tokens that touch). Two of the six are *not* what
`Document::token_at` would have answered, and the table above says which and
why; a seventh candidate, `completion.rs`'s comment gate, was left alone
because no search of the token stream answers the question it asks.
*Phase 3 — nothing, on purpose.* The breakdown does not justify a change:
- Lex and parse are 79 % of a flush. Making them incremental is the only
lever left, and it is a large change under `CLAUDE.md`'s hard invariants 1
and 2. Written up in `docs/perf/README.md` with the number that would pay
for it; not attempted.
- `tokens.clone()` is 2.40 ms, 7.7 % of a flush, and is **load-bearing**:
`parse_tolerant` takes its token vector by value and steals the comments
out of it (`std::mem::take(&mut self.tokens[pos].leading)`,
`self.tokens[pos].trailing.take()`), so `Document.tokens` cannot be the
same vector — folding, the on-type comment test and completion's comment
gate all read that trivia. The clone is also already a win: before the
one-lex change it was a second `tokenize`, which this round measures at
12.5 ms. Removing it needs a cheaply-clonable `Token`, which is a
`vlog_parser` type change reaching the formatter. Written up, not
attempted.
- The lint pass walks the tree once per rule (`vlog_linter::lint`'s
`for rule in enabled`), but it is 1.40 ms against a 32 ms flush. Fusing the
walks is a `vlog_linter` refactor for 4 %. Written up, not attempted.
- `resolve_external` is 49 µs. Skipping it when the index generation has not
moved would save one part in six hundred of a flush and add a cache
invalidation rule to a path that currently has none. Not attempted, and
the number is the reason.
*The finding worth acting on is not a code change.* Over the wire, a lone
keystroke's round trip is 156 ms at 1 000 lines — of which 150 ms is the
change debounce's own quiet period, and 4.8 ms is the work. The same
keystroke followed by a request, which is what a real editor sends, is
**4.8 ms at 1 000 lines and 37 ms at 10 000**. So for the editors that ask
for anything after a change (VS Code asks for semantic tokens, inlay hints
and highlights), the debounce timer never runs and the flush is the whole
cost; for a client that asks for nothing, the felt latency is the timer.
`CHANGE_DEBOUNCE` is a product decision the previous round made deliberately
at 150 ms, so it was not touched — but it is now a measured number rather
than an assumed one, and `docs/perf/README.md` says so.
## QA log
**2026-08-28 — QA.** Verdict: **SHIP WITH FIXES noted, none applied** — one
methodology finding on the e2e measurement (not shipped code a user can hit),
one informational note verified harmless. Everything else attacked and held.
Gates, verbatim:
- `cargo fmt --check` — clean, no output.
- `cargo clippy --all-targets --workspace -- -D warnings` — clean, no
warnings.
- `cargo test --workspace` — every crate green: lucisv_server's unit binary
1192 passed / 21 ignored, its `e2e` integration binary 55 passed / 1
ignored (the perf test, run separately below), every other crate green
too. No `FAILED`, no `error[`.
- `cargo test -p vlog_formatter` — 31 + 1 + 4 + 6 + 2 + 22 + 114 + 0 passed
across its binaries, 0 failed.
- `cargo test --release -p lucisv_server perf:: -- --ignored --nocapture --test-threads=1`
— 12 passed. Numbers reproduced within the noise the README itself budgets
(see below).
- `cargo test --release -p lucisv_server --test e2e a_keystroke -- --ignored --nocapture --test-threads=1`
— 1 passed: `1000 lines: one change alone 161.9ms, a burst of ten 160.4ms
for 1 publish(es), one change a request follows 4.7ms` /
`10000 lines: one change alone 205.7ms, a burst of ten 199.0ms for 1
publish(es), one change a request follows 38.5ms` — matches
`docs/perf/README.md`'s 156/205/157/205/1/4.76/37.4 within reason.
**Attack angle 1 (identity claims).** All six call sites re-derived from the
source and checked against their sweep predicates by hand (`selection.rs`
`enclosing`, `on_type.rs` `statement_edit` and `first_on_line`,
`completion.rs` `is_procedural` and `balanced`, `inline.rs` `triggered`).
Every one of the existing per-site tests already walks **every byte** of
`mixed_buffer(20)` (not just a handful of offsets), so the exhaustive-diff
form the brief asked for is already what shipped, not something to widen.
Checked by hand and confirmed safe at the edges the brief named: offset 0,
the last byte, the `Eof` sentinel, an empty file, a file that fails to lex
(empty `tokens`), and a large-file fast-path document — `on_type.rs`'s own
`OnTypeFormatting::METHOD` arm in `server.rs:832` answers the empty edit list
before `level_at`/`first_on_line` ever run on a large doc; `completion.rs`'s
`completions` guards `doc.tokens.is_empty()` at `completion.rs:154` before
`is_procedural`/`balanced` are reachable; `inline.rs`'s `inline_completions`
guards the same at `inline.rs:237`; `selection.rs`'s `enclosing` and the two
`first_token_*` primitives themselves degrade safely on an empty slice
(`partition_point` on `&[]` is `0`, `.get(0)` on an empty `Vec` is `None`).
`selection.rs`'s inclusive-`covers`/exclusive-`token_at` distinction is real
and correctly *not* used — traced through `first_token_reaching` +
`covers` by hand at a shared boundary byte and it does return the earlier of
two touching tokens, matching the sweep it replaced.
**Attack angle 2 (the precondition).** `state::tests::the_token_stream_rises_and_never_overlaps`
exercises exactly one hand-written buffer
(`mixed_buffer(20)`), which is narrow on its own — no macros, no directives,
no unterminated constructs. Delegated to a sub-agent to read
`vlog_parser`'s lexer directly rather than trust the docstring's claim.
Finding: `vlog_parser`'s own `tests/spans.rs::assert_covers_source` already
asserts the same invariant (non-overlap, source order, full byte coverage,
comments included) over 40+ deliberately adversarial fixtures — macros,
`` `ifdef``/`` `include`` interleaving, attributes, CRLF, BOM, multi-byte
UTF-8 in strings and comments — and `tests/error_recovery.rs` fuzzes every
byte-prefix and every single-byte deletion of a corpus without panicking.
Every lexer error path (`skip_string`, `skip_block_comment`, the attribute
scanner) returns `Err` rather than a partial, possibly-violating `Vec<Token>`,
and `TextRange::new` clamps `end` to `max(start)` structurally. No plausible
gap found: the one narrow test in `state.rs` is sufficient because it rests
on an invariant `vlog_parser` proves far more thoroughly one layer down, and
the docs correctly point there rather than re-arguing it.
**Attack angle 3 (the e2e measurement's methodology) — one finding.**
- **IL-1 (medium) — the burst's "1 publish(es)" figure is not the robust,
order-independent count the code and the docs describe.**
`crates/lucisv_server/tests/e2e.rs:4696-4727`. `published` is computed as
`1 + live.finish()` (line 4727): the `1` is an unstated assumption that the
lone `wait_for(|m| m["method"] == "textDocument/publishDiagnostics")`
right after the burst (line 4704) consumed *exactly* the burst's own
publish and nothing else, and `live.finish()`'s count only starts
accumulating after the "one change a request follows" loop ten lines later
(4714-4725) has already run — ten more iterations, each with its own
generic `wait_for(|m| m["method"] == "textDocument/publishDiagnostics")`
(line 4722) that accepts *any* publish, not specifically the one its own
request just triggered. A stray or duplicate publish arriving from the
burst in that window would be silently absorbed by one of those ten waits
and never increment `published` or surface anywhere in the printed line.
The doc comment above the burst (line 4696-4699: "the count below is that
claim measured rather than reasoned about: any publish still to come
arrives before `shutdown` does") is true of `live.finish()`'s own drain —
nothing gets past *that* point unnoticed — but it is not true of the
window between the burst and the drain, which is exactly where a second
publish would have to be counted to falsify "exactly one". As written, the
test would print "1" whether the burst produced one publish or secretly
produced two, which is indistinguishable from the claim it's supposed to
be checking. In practice the debounce is understood to always coalesce to
one flush, so this is a soundness gap in the *measurement*, not evidence
of a real double-publish — but it means the "counted rather than reasoned
about" claim is itself partly reasoned about. Not fixed: closing it cleanly
means either running the burst as its own `Live` session finished
immediately after (so nothing else can absorb a stray), or having
`wait_for` tally every `publishDiagnostics` it ever passes over for the
life of the session — both are design choices for the dev, not a
QA drive-by edit.
- Everything else in this angle held. `Live::finish`'s drain (`e2e.rs:2231`)
really does read to `shutdown`'s response before returning, so nothing
published after the last explicit `wait_for` in a test is lost *at that
point* — it is specifically the mid-test absorption above that is the gap.
The 150 ms figure in the lone-keystroke row is the timer and not a stall:
reproduced at 161.9 ms / 205.7 ms against a documented 150 ms
`CHANGE_DEBOUNCE` plus a single flush (2.6 ms / 31.2 ms measured
separately), which accounts for the total without residue.
**Attack angle 4 (duplication) — one informational note, verified harmless.**
`perf::generated_module` (`crates/lucisv_server/src/perf.rs:42-57`) and its
copy in `crates/lucisv_server/tests/e2e.rs:4634-4649` are not byte-identical:
the `e2e.rs` copy appends ` // typing\n` before `endmodule` that the
original does not have, so the test has a stable, comment-only line to land
keystrokes on. The doc comment on the copy ("The two must stay the same
shape, or the two tables ... stop being readable against one another")
slightly overstates it — they differ by one line. Verified harmless: a
comment is lexer trivia and is never its own token, so `tokens.len()` is
identical between the two generators at the same `lines`, and the added ~12
bytes is noise against 29 KB / 309 KB files. The two perf tables do stay
readable against one another; no fix needed.
**Attack angle 5 (perf honesty).** Every figure in `docs/perf/README.md`'s
round-2 tables reproduced within the noise the document itself budgets for,
on a fresh `--release` run (see gates above for the two exact commands and
their output). Spot check on "the breakdown sums to `Document::new`'s
31.1 ms" — a claim the brief asked about but which, checked directly, is
**not actually written anywhere in either README**; nowhere does the text
assert the eight-stage breakdown sums to the `Document::new` figure. As a
sanity check anyway: summing this run's own breakdown stages inside
`Document::new` (tokenize 12.512 + parse_tolerant-with-clone 14.149 +
collect_defines 0.115 + analyze 3.174 + resolve_external 0.012 +
`LineIndex::new` 0.105 ≈ 30.07 ms) against the dedicated `Document::new`
figure from the same run (31.22 ms) leaves about 1.15 ms — 3.7% —
unaccounted for, which is consistent with the README's own caveat that the
breakdown "runs eight measurements back to back on one heap" and should be
read as *shares*, not as a sum that has to close exactly. No finding, since
no stronger claim than that is actually made.
**Attack angle 6 (regression sweep).** `cargo test --workspace` exercises
every one of the four handlers' existing suites unchanged and green
(selection.rs, on_type.rs, completion.rs, inline.rs — see gates above).
Adversarial shapes the brief named are already covered by name in the
existing suites and were spot-read to confirm they exercise the *changed*
code paths and not just the surrounding handler: `on_type.rs`
`a_semicolon_the_lexer_never_saw_ends_no_statement`,
`a_semicolon_at_eof_with_no_trailing_newline_still_lays_out_its_line`,
`a_crlf_line_ending_is_never_touched_by_the_edit`; `completion.rs`
`a_buffer_that_does_not_lex_is_declined`; `inline.rs`
`a_buffer_that_does_not_lex_is_declined_rather_than_guessed_at`,
`a_trigger_at_the_true_end_of_file_still_offers_a_ghost`,
`crlf_line_endings_still_trigger`; `selection.rs`
`a_file_that_does_not_lex_still_answers_the_file_range`,
`an_empty_file_still_answers_one_degenerate_chain`.
**PDS-1..4 and CD-1, spot-checked in code rather than trusted from the
README.** `hover.rs:361` (`only_a_closer_on`) and `:373` (`is_closer_word`)
exist and `another_port_on`/`is_port_grammar_word` are gone — PDS-1 real.
`hover.rs:292-295` strips a trailing `\r` in the one line reader all three
`attached_lines` collections pass through — PDS-4 real. `server.rs:1247-1262`
(`notification`): the `dirty.retain` for `DidCloseTextDocument::METHOD` sits
*above* the `if method != DidChangeTextDocument::METHOD { self.flush_dirty() }`
call, guarded on the method name via a borrowed, cloned `closing_uri`
(`server.rs:2214`, reads `params` without consuming the notification) — CD-1
genuinely closed, not dead code any more. PDS-2/PDS-3 not independently
re-derived (no code-shape claim to check beyond what PDS-1/PDS-4 already
verify the same file's discipline on); taken on the strength of the named
tests, which are present and green.
## Review
**2026-08-28 — lead.** Accepted, with one methodology fix applied by me
(below). Gates re-run independently: fmt clean, clippy silent, workspace
tests green, formatter snapshot + idempotency suite green, the twelve `perf::`
measurements and the wire measurement both reproduce.
This round did the thing that makes a performance round worth anything: it
measured first and then declined to optimise three of the four things it had
been pointed at, with a number for each refusal. `resolve_external` at 49 µs
of a 31 ms flush disproved the brief's own hypothesis, and saying so is a
better outcome than a speculative cache on a path that has no invalidation
rule today. Lex and parse at 79 % is the real answer, and leaving incremental
parsing to a planned round rather than starting it opportunistically is
right — that work lands directly on hard invariants 1 and 2 and is not
something to attempt as the tail of a perf sweep.
The Phase 2 swaps are the part I looked at hardest, because six "obviously
identical" rewrites is exactly where a silent behaviour change hides. The
dev found the one that was *not* identical: `selection.rs`'s `covers` treats
`span.end` inclusively, so at a byte two tokens share, the sweep returned the
earlier token and `Document::token_at` would have returned the later one.
Building `first_token_reaching` instead of reaching for the existing helper
is the correct instinct, and differential-testing each new expression against
the predicate it replaced at every byte of a purpose-built buffer is the
right proof. Three call sites were left alone with reasons — signature help's
paren depth is inherently a prefix scan, `pairs.rs` is not a position query,
and completion's comment gate cannot be answered by any search of the token
stream because comments are trivia. Recording the last of those as the
remaining per-keystroke whole-buffer walk is more useful than a forced fix.
**Fix applied at review.** QA's IL-1 was right and I closed it directly
rather than spending another round: the burst-of-ten publish count was
`1 + finish()`, but the ten-iteration request loop sat between the burst and
the drain, and each of its `wait_for`s accepts *any* publish — so a second
publish the burst had produced would have been absorbed there and the figure
would still have read "1". The burst now runs last, immediately before the
drain, with the keystroke versions renumbered to stay monotonic. Re-measured
after the change: still exactly one publish at both sizes, and the row is now
counted rather than assumed. IL-2's overstated doc comment is corrected in
place — the two `generated_module` copies differ by one trivia line, which is
not a token and does not move a number.
+13 -11
View File
@@ -21,15 +21,15 @@ looks like language knowledge in here is a bug or a `Handshake` request.
| `textDocument/rangesFormatting` | `vlog_formatter::format_range` | LSP 3.18's multi-range form of the line above, and literally its `n`-range case: the ranges become one sorted, merged `LineRanges` and one engine call, so the all-or-nothing contract is over the union rather than per range. `range_formatting` is now defined as the one-element call of it, and the reply, the refusal and the config warning are the same values. Advertised by widening `documentRangeFormattingProvider` from `true` to `{ "rangesSupport": true }` — **only for a client that sent `textDocument.rangeFormatting.rangesSupport`**, so a 3.17 client sees exactly what it always saw; the handler itself is unconditional. `lsp-types` 0.97 spells neither half, so both go through JSON. See `docs/features/lsp-318-extras/README.md` |
| `textDocument/onTypeFormatting` | `vlog_formatter::format_range` (for `;`); the token stream (for `\n`) | Two triggers, and only two. `;` range-formats the statement it ended, through the *same* engine `rangeFormatting` runs, over the `;`'s own line. `\n` re-indents the line it opened from block nesting — new logic outside the verified engine, so its edit can structurally only replace that one line's leading whitespace with spaces, and a corpus-wide agreement test forbids it from ever disagreeing with the printer. **Never speaks**: a refusal is `[]` with no `showMessage`, and a broken `lucisv.toml` is not reported here either (the dedup is re-armed by the `didChange` every keystroke produces). Advertised unconditionally — the client's own `editor.formatOnType` is the opt-in. See `docs/features/on-type-formatting/README.md` |
| `textDocument/willSaveWaitUntil` | `vlog_formatter::format_source` | Format-on-save, protocol-native, for the editors that have no format-on-save of their own. **Off unless `lucisv.formatOnSave` is pushed**, and the decline is `null` — a capable client asks before every save, and a client with its own format-on-save would otherwise format twice. When on it is `textDocument/formatting` with a different trigger: the same engine, the same all-or-nothing edit, and the settings ladder minus its `tabSize` rung (the request carries no `FormattingOptions`). See `docs/features/will-save-wait-until/README.md` |
| `textDocument/publishDiagnostics` | `vlog_parser::parse_source_tolerant` | Pushed on `didOpen`/`didChange`/`didSave`, once per notification — **only for a client that does not pull**. See `docs/features/pull-diagnostics/README.md` |
| `textDocument/didChange` | `sync::apply_changes` | Incremental sync: the ranges are applied in order to the buffer the server holds, then one `set_document` + one `publish`. A rangeless change still replaces the whole buffer, so a full-sync client is unaffected. See `docs/features/incremental-sync/README.md` |
| `textDocument/publishDiagnostics` | `vlog_parser::parse_source_tolerant` | Pushed on `didOpen`/`didSave` once per notification, and for a `didChange` once per **flush** (a typing burst publishes once, not once per keystroke — `docs/features/change-debounce/README.md`) — **only for a client that does not pull**. See `docs/features/pull-diagnostics/README.md` |
| `textDocument/didChange` | `sync::apply_changes` | Incremental sync: the ranges are applied in order to the buffer the server holds, and the composed text is held **dirty** — one `set_document` + one `publish` per *flush*, which is the next request, the next other notification, or a 150 ms quiet period. A rangeless change still replaces the whole buffer, so a full-sync client is unaffected. See `docs/features/incremental-sync/README.md` and `docs/features/change-debounce/README.md` |
| `textDocument/diagnostic`, `workspace/diagnostic` | the same parse+lint pass | The 3.17 pull model, served to a client that advertised `textDocument.diagnostic` — which is then pushed nothing at all. `resultId` is one generation counter, bumped by a buffer change and by an index rebuild; the workspace report covers the **open buffers**. Same feature README |
| `textDocument/selectionRange` | `Document.tokens`, AST spans, `pairs::analyze` | Expand-selection: one strictly nesting chain per requested position, token → statement → block → item → file. No expression step. See `docs/features/selection-range/README.md` |
| `textDocument/semanticTokens/full` | `vlog_parser::tokenize` + `Semantics` | Delta-encoded, split at line boundaries. Stamped with a `resultId` since 2026-08-26, so a delta can name it. **Declined with an error on a buffer over `lucisv.largeFile.threshold`** (2026-08-27): VS Code marks a model whose document provider answered *anything* as complete and then never asks its range provider again, so an empty answer would cost a 100 MB file all of its colour — see `docs/features/large-file-mode/README.md` |
| `textDocument/semanticTokens/range` | the same classification pass | The visible lines only, for the first paint of a large file. A **self-contained** answer: the tokens overlapping the range, kept whole, re-encoded from the start of the document. No `resultId` — a partial view is not what a delta is computed against. See `docs/features/semantic-tokens-delta/README.md`. On a buffer over `lucisv.largeFile.threshold` this is the **only** request that colours anything, and it lexes the window itself (0.25 ms for a viewport of a 100 MB file) rather than filtering a token stream that was never built |
| `textDocument/semanticTokens/full/delta` | the same classification pass | What changed since the answer the client names: one edit replacing everything between the common prefix and the common suffix (the suffix capped so the two cannot overlap — identical lines of Verilog encode identically, which is exactly the trap). An id the server does not hold, including one from before a `didClose`, is answered in full. Same feature README |
| `textDocument/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex`, `includes::IncludeGraph`, `expand` | Macro body, or declaration kind + snippet. A macro this file does not define is answered from the workspace: the definition it **reaches through its `` `include``s** when exactly one is reachable, and every candidate otherwise. A macro card also shows what the hovered use **expands to in one step** — the body with this call's arguments substituted — when that says more than the body already does; a nested `` `INNER`` is left as written, an argument count that does not match expands nothing, and several candidates expand nothing. See `docs/features/macro-expansion/README.md`. A **cross-file** answer carries the declaration's own source line(s) under its `file:line` heading — `input logic [7:0] addr`, not just where it lives — read at hover time from the live buffer when that file is open and from disk otherwise, and omitted whenever the text and the span disagree: `docs/features/hover-declarations/README.md` |
| `textDocument/definition` | `includes::IncludeGraph`, then `Semantics`, then `ExternalResolutions` | A cursor on an `` `include`` line jumps to the resolved file's first byte; otherwise the in-file symbol table, then the workspace overlay, whose `Ambiguous` answer returns every location. See `docs/features/include-nav/README.md` |
| `textDocument/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex`, `includes::IncludeGraph`, `expand` | Macro body, or declaration kind + snippet. A macro this file does not define is answered from the workspace: the definition it **reaches through its `` `include``s** when exactly one is reachable, and every candidate otherwise. A macro card also shows what the hovered use **expands to in one step** — the body with this call's arguments substituted — when that says more than the body already does; a nested `` `INNER`` is left as written, an argument count that does not match expands nothing, and several candidates expand nothing. See `docs/features/macro-expansion/README.md`. A **cross-file** answer carries the declaration's own source line(s) under its `file:line` heading — `input logic [7:0] addr`, not just where it lives — read at hover time from the live buffer when that file is open and from disk otherwise, and omitted whenever the text and the span disagree: `docs/features/hover-declarations/README.md`. A **non-ANSI port** — named in the module header, completed in the body by `input signed [31:0] data_in;`, and likewise an old-style task or function argument — shows both places as two fenced sections, each carrying every comment that documents it (above, beside and below, where nothing else claims them): `docs/features/port-detail-spans/README.md` |
| `textDocument/definition` | `includes::IncludeGraph`, then `Semantics`, then `ExternalResolutions` | A cursor on an `` `include`` line jumps to the resolved file's first byte; otherwise the in-file symbol table, then the workspace overlay, whose `Ambiguous` answer returns every location. A non-ANSI port answers two locations, its body declaration first — the same two the hover card shows, in the same order (`docs/features/port-detail-spans/README.md`). See `docs/features/include-nav/README.md` |
| `textDocument/typeDefinition` | `type_def`, then `nav::definition` | The same jump one token to the left: from a name to where its **type** is declared — a `typedef`, an `interface`, a `class`, or the module an instance name stands for. The tree says which declaration a position is in and where its type name is written; the answer is then `definition` of *that* name, so cross-file resolution, ambiguity and position conversion are all the ones F12 already uses. One hop on an alias chain, an empty list for a built-in. See `docs/features/type-definition/README.md` |
| `textDocument/linkedEditingRange` | `linked`, over `Document.tree` | SV's closing labels, edited as one name: the cursor on either half of `module m ... endmodule : m` (and of `endfunction`/`endtask`/`endclass`/`endpackage`/`endinterface`/`endclocking`, a named `begin`/`fork`, a generate block, and the prefix-labelled `b : begin ... end : b`) answers **both** ranges plus the SV `wordPattern`. The pair comes off one AST node — `name_span` with `end_label_span` — never off a text match, so four identical names at two nesting levels still pair syntactically. Two `null`s on purpose: a closer with **no** label (nothing to co-edit, and this never offers to create one) and a **mismatched** one (the spec requires identical text; linking would silently rewrite broken code). Escaped identifiers are excluded. See `docs/features/linked-editing/README.md` |
| `textDocument/documentLink` | `includes::IncludeGraph` | One link per **resolvable** `` `include``, covering the quoted path, target already resolved (`resolveProvider: false`). Search order: the including file's own directory, then each `+incdir+` of the configured filelist in order; the `<angled>` form skips the first rung. An include nothing answers to gets no link and no error. Same feature README |
@@ -233,17 +233,19 @@ reasoning and the measurements: `docs/features/cancel-request/README.md`.
| layer | rebuilt when | cost |
|---|---|---|
| a document's `Semantics` + tokens + diagnostics | every `didOpen`/`didChange` — **once per notification**, however many ranges it carried | one file, full recompute |
| a document's `Semantics` + tokens + diagnostics | every `didOpen`, and every **flush** of the buffers a `didChange` left dirty — once per flush, however many ranges *and* however many notifications it coalesced (`docs/features/change-debounce/README.md`) | one file, full recompute — 2.6 ms at 1 000 lines, 31 ms at 10 000 (`docs/perf/README.md`) |
| the `WorkspaceIndex` | `initialize`, every `didSave`, every `textDocument/didOpen` that **widens the scope**, every `workspace/didChangeWatchedFiles`, every `workspace/didChangeWorkspaceFolders` that moves the root set, and a changed `lucisv.exclude`/`lucisv.filelist`/`lucisv.index.maxFileSize`/`lucisv.index.scope`/`lucisv.index.scopeDepth` (pushed **or** pulled) | full re-scan of the scope — **except when the trigger names exactly one file the index already holds** (a `didSave`, a one-file watcher event), where only that file's contribution is replaced and the result is provably the index a full re-scan would have given (`docs/features/incremental-index/README.md`) |
| the `` `include`` graph | with the `WorkspaceIndex`, from the same file list | a line scan per file (~6ms over the 860-file corpus). An open buffer's *own* includes are re-resolved on every request instead, so a line just typed is clickable before the next save |
| the **index cache** on disk | appended to as a whole rescan parses each file, rewritten when that rescan ends, and written through by every incremental one-file update | one `write` per parsed file. It is read at the start of every whole rescan and answers for every file whose content it already holds, which is what makes a reopened workspace cost the reads and not the parses (`docs/features/index-persistence/README.md`) |
**Per-file recompute on every keystroke** is the strategy TODO.md §6 states
("per-file recompute is fine at Verilog file sizes"); salsa is explicitly
deferred there. Incremental *sync* did not change that: the wire now carries
ranges, but a `didChange` still throws the whole `Document` away and builds a
new one — one reparse per notification, which is also the one generation bump
the pull-diagnostics `resultId` depends on.
**Per-file recompute** is the strategy TODO.md §6 states ("per-file recompute
is fine at Verilog file sizes"); salsa is explicitly deferred there.
Incremental *sync* did not change that: the wire carries ranges, but a flush
still throws the whole `Document` away and builds a new one. What changed on
2026-08-28 is *how often*: a `didChange` no longer triggers that recompute
itself, so a typing burst costs one reparse and one generation bump — still
exactly one of each per flush, which is what the pull-diagnostics `resultId`
depends on (`docs/features/change-debounce/README.md`).
**Which files exist: the folder scope, since 2026-08-27** (index-scope). The
index no longer walks the whole workspace by default. The ladder, highest
+448
View File
@@ -0,0 +1,448 @@
# port-detail-spans
## Goal
A non-ANSI port is declared in two places: the header names it (`data_in,`)
and a body declaration finishes it (`input signed [31:0] data_in;`). Every
fact a reader wants — direction, signedness, width — is in the second place,
and until this round hover and go-to-definition both pointed only at the
first, so hovering a port of an older-style module showed a bare name and a
comma. `vlog_semantic` now records, on the header symbol, the span of the body
declaration that completes it (`Symbol::detail_span`); the server shows both
in one hover card and offers both as definition locations, detail first. The
same field travels through the workspace index and its on-disk facts, so a
*cross-file* hover into a closed file gets the same two sections. Attached to
that, because a card that shows a declaration should show what the author
wrote about it: each section carries the comment that documents it.
## Assumptions
- **One name, one symbol, per scope.** `bind::declare` already turns a second
declaration of a name into a *reference* to the first, which is exactly how
a non-ANSI body declaration attaches to its header port. `detail_span` rides
on that existing mechanism; nothing new decides what "the same port" means.
- **First writer wins.** If a header somehow names a port twice, the first
body declaration to arrive records its span and later ones are ignored. The
result is deterministic, which is what matters here; a duplicated port is
the linter's complaint to make, not hover's.
- **`detail_span` is `None` for everything else.** An ANSI port, a wire, a
module — anything complete where it is named — has no detail site, and both
consumers render exactly the card they always did.
- **A real span is never empty**, so `(0, 0)` is free to mean `None` in the
facts codec. `bind_port_decl` only ever records a declaration's own span.
- **Comment attachment is textual, and errs towards attaching nothing.** The
disk path of a cross-file hover has no parse to ask, so the attachment rules
work on lines. Only `//` lines and single-line `/* … */` count as
comment-only; the interior of a multi-line block comment is
indistinguishable from code without lexing, and a hover card that guessed
would be the wrong-line lie the snippet guards exist to prevent.
- **A comment below a declaration belongs to the *next* declaration unless
nothing else could claim it.** `only_a_closer_on` answers that with a
whitelist, not a blacklist: the block attaches only when every word on the
line after it is a block terminator (`end`, `endmodule`, `endinterface`,
`endtask`, `endfunction`) — which includes a line with no words at all
(`);`, a blank line, punctuation) — or when there is no line after it at
all. Everything else, a bare `input` on the first line of a *wrapped*
declaration included, reads as another declaration. The bias is the whole
point: a false "another declaration is here" only ever declines to attach a
comment, the direction that cannot lie, while a false "nothing here" shows
one declaration's comment on another's card. (QA, PDS-1: the previous
keyword-blacklist form got that backwards and did lie.)
- **The three comment sources are independent**, as the owner's rule states
them: a declaration takes the comment on its own line *and* the block above
it *and* the block below it, each guarded on its own. Order is source
order. (QA, PDS-2: the first implementation ran them as a priority chain
and dropped a below-comment nothing else claimed.)
- **Comment attachment renders, it never rewrites.** A CRLF file's line ends
before its `\n` but after its `\r`, so `attached_lines` strips that `\r` as
it composes each line — display text only; no buffer is touched (QA,
PDS-4).
## Handshakes
- **`vlog_semantic::Symbol` gains a field** — `detail_span:
Option<TextRange>`. Additive, like `refactor-rename`'s `Target::Declaration`
before it (§2.6 of `topo.md`): every existing reader of `Symbol` compiles
and behaves identically, and the two struct literals that build a `Symbol`
(`bind.rs`) set it. `bind_port_decl` is where it is written.
- **`vlog_semantic::Def` gains the same field**, carried by the index's
internal `Decl`. `Def` is what `lucisv_server` navigates by, so this is the
wire that makes a *cross-file* hover show the body declaration. `Def`
derives `PartialEq`; two `Def`s that differ only in `detail_span` cannot
arise, because both come from the same `Decl`.
- **`facts.rs`'s on-disk format changes** — every declaration record now
carries two more numbers, written unconditionally (`0 0` for the `None`
that every ordinary declaration has) so the stream stays flat and the
reader stays a straight sequence of `num()`s. **`FACTS_FORMAT` is bumped
(2 → 3)**, so a store written by an earlier build is discarded whole:
`index_cache.rs`'s header line carries the number, and a header that is not
this build's means the file is not read at all. Without the bump an old
record would be *reinterpreted* — every field after a declaration's name
span shifted by two — rather than dropped, and only the reader's `done()`
check would stand between a shifted parse and a wrong answer. Dropping the
store costs one rescan, once, which is what the persistent index is for
(`docs/features/index-persistence/README.md`); it is the
`vlog_semantic/src/workspace.rs` choke-point rule in `topo.md` §3.3.
- **`nav.rs` and `hover.rs` agree, by construction.** Hover shows two
sections — header, then detail — and `nav::definition` returns two
locations in the same order, detail first, so "jump" lands where the card's
second block is and the card's first block is the second location. Both
read `symbol.detail_span`; there is no second rule for what a port's
declaration is. An empty detail span is filtered out in `nav.rs` rather
than trusted.
- **Consumes `hover-declarations`' guards unchanged.** `spells_exactly` still
gates every snippet read out of a file the index may be stale against;
`fenced_sections` is applied *after* that guard on the disk path, and after
`live_symbol` on the live path.
## Status / TODO
- [x] `Symbol::detail_span`, written by `bind_port_decl`, first writer wins —
for a module's non-ANSI port and for an old-style task/function
argument, which merge through the same `bind::declare`.
- [x] `Def::detail_span` + the index's `Decl` carrying it.
- [x] `facts.rs` codec: unconditional pair, `(0,0)` = `None`, `FACTS_FORMAT`
bumped so a stale store is not read as a fresh one.
- [x] `hover::fenced_sections` — one section, or header + detail.
- [x] `nav::definition` returns the detail location first.
- [x] Comment attachment (`attached_lines`): same-line, above and below, each
guarded on its own, all three at once where all three are written.
- [x] Tests: `vlog_semantic` records the span for a split port and not for an
ANSI one; hover shows two sections from either end of the port;
comments attach above, below, and are not stolen from the next port;
a cross-file split port shows both sections from the index.
- [x] **2026-08-28**: the below-comment guard is a closer whitelist, so a
*wrapped* next declaration keeps its own leading comment (QA, PDS-1).
- [x] **2026-08-28**: above / beside / below are independent (QA, PDS-2).
- [x] **2026-08-28**: an old-style task or function argument gets a
`detail_span` too (QA, PDS-3).
- [x] **2026-08-28**: a CRLF file's snippet carries no `\r` into the fence
(QA, PDS-4).
- [ ] Not done: `detail_span` for anything other than a port or a
task/function argument. An `extern`
method prototype and its out-of-body definition are the same
two-places-one-symbol shape and would fit the field exactly, but no
hover complaint has been filed about them and speculative generality is
what `CLAUDE.md` says not to build.
- [ ] Not done: a *doc-comment* model. The attachment above is positional and
deliberately dumb — no `///` convention, no markdown rendering of the
comment body, no stripping of `//`. That is a feature of its own if it
is ever wanted.
## Work log
**2026-08-28 — dev.** Implemented as part of the LSP performance round
(plan: "Improve LSP performance + hover accuracy", part B), continued by a
second dev after the first stopped mid-round; the code below is the first
dev's except where noted.
- `bind_port_decl` looks the declarator's name up in the scope it is binding
into *before* `bind_declarators` runs, because `declare` will turn the name
into a reference and there would be no symbol id to write on afterwards.
The lookup is the scope's own `names` map — the same map `declare` consults
— so "the same port" is decided in exactly one place.
- The codec writes the pair unconditionally rather than with a presence flag.
A flag would have kept old records readable at the cost of a branch in the
hot reader and a second thing to get wrong; dropping a stale record costs
one reparse of that file, once.
- Comment attachment was not in the plan. It is here because the first card
the two-section change produced looked wrong without it: a port's comment
sits on the line above or beside it, and showing the declaration without it
loses the only prose the author wrote. The rules are the narrowest ones
that never steal another declaration's comment, and each has a test.
- **Second dev, 2026-08-28**: **bumped `FACTS_FORMAT` 2 → 3**, which the
first dev's change owed and did not take. Its comment argued that a
pre-field record is "one field short, fails `done()`, and is dropped" —
true for the last declaration in a record, but a record with a declaration
followed by anything else is not short, it is *shifted*, and relying on a
trailing-length check to catch a field-order change is exactly what the
format number exists to make unnecessary. The workspace `VERSION` is also
in the store's header, but it has not moved this round, so without the bump
a store written by the released 0.12.1 would have been read by the new
codec. Otherwise no behavioral change: this README is the documentation the
round owed, and `cargo fmt` was run over `hover.rs`.
**2026-08-28 — dev (QA fixes, third dev).** Every finding in the QA log below
is addressed; each is marked fixed or left, with the reason.
- **PDS-1 — fixed.** `another_port_on`/`is_port_grammar_word` are gone,
replaced by `only_a_closer_on`/`is_closer_word` (`hover.rs`). The old
predicate asked "does this line carry an identifier the port grammar cannot
account for?", which is a blacklist: a line that is *only* keywords — the
first line of a wrapped `input\n [7:0] result;` — answered "no other
port here" and handed `result`'s comment to `data_in`. The new one asks the
question the other way round: every word on the line must be a block
terminator, so a line with any word the whitelist does not name (a bare
`input` included) reads as another declaration and the comment stays put.
A line with no words at all — `);`, blank, punctuation — passes, which is
what a last port's trailing comment is really followed by, and so does the
end of the file, where there is no line left to claim anything. The doc
comment now states that bias and why only that direction is safe.
- `name` fell out of the predicate, and with it out of `attached_lines` and
`fenced_sections` — the guard no longer needs to know which port it is
guarding, only whether anything follows the comment. Three call sites
simplified; no behaviour rides on the removal.
- Pinned: `a_wrapped_next_declaration_keeps_its_own_leading_comment` (the
QA repro verbatim, plus the assertion that the comment does reach
`result`'s own card) and `a_wrapped_declaration_keeps_the_comment_below_it`
(the same wrapped shape as the *last* declaration still takes it). The
existing `a_comments_below_a_declaration_attach_only_when_no_port_follows_them`
— comment block above `endmodule` — still passes unchanged.
- **PDS-2 — fixed.** `attached_lines` no longer runs a priority chain: the
above walk, the declaration's own lines (which carry the same-line comment
inherently) and the below walk are three independent collections joined in
source order. `has_comment_after` was the chain's only reader and is
deleted. Each guard is exactly as strict as before — the above walk still
stops at the first line that is not comment-only, and the below guard got
*stricter* with PDS-1 — so nothing new can be stolen; what changes is only
that a below-comment nothing else claims is no longer silently dropped
because something was also written above.
- Pinned: `a_declaration_shows_the_comments_above_beside_and_below_it_at_once`
(all three on one body declaration) and
`a_header_port_shows_the_comments_above_and_below_it_at_once`, which is
QA's repro 1 and repro 2 in one header — with the negative half (the same
block *is* left alone when another port follows it) in the same test.
- **PDS-3 — fixed, not documented as a gap.** Checked the binder first, as
the brief asked: `bind_tf_args` declares `task t(a);`'s `a` as a `TfArg` in
the task's own scope, and `input [7:0] a;` at statement position reaches
`bind_port_decl` with that same scope, so `declare` turns it into a
reference to the header symbol — the identical header→body merge a module
port gets, one symbol and not two (verified by probe before changing
anything). So the recording is extended rather than parked: the
`kind == SymbolKind::Port` gate is gone and the inner test is
`symbol.kind == kind`, which is the same condition for a port and now also
holds for an argument. Pinned in `vlog_semantic`
(`an_old_style_task_argument_records_its_body_declaration_too`, including
that an ANSI-style argument still has none) and in hover
(`an_old_style_task_argument_hovers_as_two_sections_too`).
- **PDS-4 — fixed.** `attached_lines`'s line reader strips a trailing `\r`
from every line it composes, so a CRLF file's fenced block is `\n`-joined
like any other. It is done there, at the one place all three collections
(above, declaration, below) pass through, rather than in `cut_to_size`,
which would have had to re-split the joined string. Display text only —
nothing writes to the buffer. QA's pinned test
`a_crlf_multiline_snippet_keeps_interior_carriage_returns` was the
regression test for the old behaviour; it is now
`a_crlf_multiline_snippet_carries_no_carriage_returns`, asserting no `\r`
survives *and* that the lines read as written. (Editing a QA-authored test
rather than deleting it: the finding it pins is the one being closed, and
the same file's `local_text` path goes through the same helper, so it
covers both branches QA named.)
## QA log
**2026-08-28 — QA.** Verified against the owner's own spec ("two sections
… same line, or above it (if no other port on the line above), or below it
(if no other port on the line below)"), and attacked with the shapes named in
the QA brief. Gates green (see change-debounce's QA log for the shared run).
All reproductions used temporary `#[test]`s in `hover.rs`, run once, and
removed after confirming — none are left in the tree, except the one noted
below as a kept, permanent regression test.
- **Finding PDS-1 (high — a wrong comment shown, the one invariant this
feature explicitly promises never to violate).** `another_port_on`
(`hover.rs:355`) — the guard that decides whether a below-comment block
belongs to *this* declaration or the next one — inspects only the single
line immediately following the comment block. When the next port's own
declaration **wraps**, with its direction keyword alone on the first line
and its name on a later line, every word on that first line is in
`is_port_grammar_word`'s list (`hover.rs:368`, which includes bare
`input`/`output`/etc.), so `another_port_on` returns `false` — "no other
port here" — and the comment attaches to the **wrong** declaration.
- Repro:
```systemverilog
module alu (data_in, result);
input [7:0] data_in;
// about result
input
[7:0] result;
endmodule
```
Hovering `data_in` shows a detail section reading
`input [7:0] data_in;\n// about result` — `result`'s own leading comment,
attached to `data_in`'s card. Confirmed live (temporary test asserting
the comment is *not* present failed with exactly this text).
- This is precisely the failure mode `docs/features/port-detail-spans/
README.md`'s own Assumptions section rules out: "a false 'yes' only ever
declines to attach a comment — the direction that cannot lie." Here a
false *no* (failing to recognize `result`'s declaration as a port) makes
it lie. Left unfixed — not small/unambiguous; the honest fix wants
`another_port_on` (or its caller) to look past a line that is *entirely*
grammar words with no other identifier, to the line(s) after it, which
is a real design change to a predicate three call sites and several
tests depend on.
- **Finding PDS-2 (medium — divergence from the stated spec, not corruption;
the one the QA brief asked to check explicitly).** The owner's rule reads
as three independently-checked sources (same line, above, below). The
implementation instead runs a strict priority chain in `attached_lines`
(`hover.rs:297`): below-comment collection is skipped **entirely** whenever
there is *any* above-comment, or *any* same-line trailing comment
(`hover.rs:313`, `if above.is_empty() && !decl.last()...has_comment_after`)
— even when the below comment is otherwise unclaimed by anything else
(no other port follows it).
- Repro 1 (above blocks below):
```systemverilog
module alu (
// above
data_in
// below
);
input [7:0] data_in;
endmodule
```
Header section shows `// above` + `data_in` only; `// below` is silently
dropped, though nothing else claims it (the next line is `);`).
- Repro 2 (same-line trailing comment blocks below):
```systemverilog
module alu (
data_in // right here
// below
);
input [7:0] data_in;
endmodule
```
Header section shows `data_in // right here` only; `// below` dropped.
- Not unsafe (never shows the wrong comment — just fewer than the literal
spec asks for), so lower severity than PDS-1, but a real, reproducible
divergence. Left unfixed — a design call (should a declaration ever show
*two* attached comments at once?) belongs to the dev/lead, not QA.
- **Finding PDS-3 (low — silent feature-completeness gap, not a bug).**
`bind_port_decl`'s `detail_span`-recording branch is gated on `kind ==
SymbolKind::Port` (`bind.rs:512`), which excludes `SymbolKind::TfArg` —
**old-style (non-ANSI) task/function port declarations**
(`task t(a);\n input a;\n ...\nendtask`) never get a `detail_span`, even
though they are exactly the same two-places-one-symbol shape a module's
non-ANSI port is, and `bind_port_decl` is already reached at statement
position for them (`bind.rs:1030`, `StmtKind::PortDecl`). The feature's own
"Not done" list names only extern method prototypes as the deliberately
parked case; task/function old-style ports are a second, unmentioned one.
Falls back to the single-section card exactly as before this round — no
regression, just an undocumented gap, worth a line in Status/TODO if the
dev wants it.
- **Finding PDS-4 (low/cosmetic — pre-existing, amplified by this round, not
introduced by it).** On a CRLF file, a multi-line fenced snippet embeds a
raw `\r` byte in the *middle* of the code fence for every joined line
except the last (whose trailing `\r` happens to be stripped because
`cut_to_size`'s `trim_end()` only trims the very end of the whole joined
string, not each line). This is pre-existing behavior of
`Positions::whole_lines` / `cut_to_size` — `local_text` already had the
same characteristic for any multi-line `decl_span` before this round — but
comment attachment now makes multi-line snippets routine (any port with a
nearby comment, not just a rare multi-line declaration), so the gap is hit
far more often in practice. Repro: a CRLF split-port module with an
above-comment; the header section's rendered text contains a literal `\r`
between the comment line and the declaration line. Cosmetic only (a stray
control character, not wrong text); not fixed, flagged for whoever touches
`cut_to_size` next.
- **Attack angles checked and clean (no finding):**
- *A port declared twice* — first-writer-wins confirmed: the second body
declaration's comment (`// second (duplicate...)`) never appears; only
the first's (`// first`) does, matching `bind_port_decl`'s documented
policy.
- *ANSI mixed with non-ANSI in one header* — a full ANSI port (`input wire
clk,`) and a split non-ANSI port (`data_in`) in the same header list:
`clk` renders exactly one fenced section, `data_in` exactly two, no
cross-contamination.
- *A comment containing `//` inside a string on the declaration line* —
the whole line is shown verbatim regardless (the attachment logic never
parses the line's meaning, only whether `has_comment_after` sees `//`/
`/*` after the name), so there is no wrong-line risk, only the expected
line reproduced as written.
- *`` `ifdef``/`` `endif`` between the header and the body declaration* —
correctly ignored as neither comment-only nor a stolen declaration; the
detail section is exactly the body decl's own line(s). (Note: a
`` `endif``/`` `ifdef``/`` `define`` line sitting where "no other port"
is required is itself treated as "another port" by `another_port_on`'s
conservative word-matching — a false positive that only *declines* to
attach, so it is safe, just another instance of the documented
conservative-below-the-fold behavior, not a new bug.)
- *An attribute (`(* foo *)`) prefixing the next port's declaration* —
correctly detected as "another port" (the attribute's own words split
out as ordinary non-grammar identifiers), so the comment is not stolen.
- *A block comment `/* … */` spanning multiple lines* — the interior lines
are (by design, and correctly) not recognized as comment-only, so the
walk stops there and nothing is attached from inside the block — safe
(declines rather than guesses), matching the documented limitation.
- **Facts-format bump (2 → 3): verified the drop, not a shifted read.**
Wrote and kept a permanent regression test,
`a_store_from_the_previous_facts_format_is_dropped_not_misread`
(`crates/lucisv_server/src/index_cache.rs`, next to the existing
`a_store_from_another_version_is_dropped_whole_and_replaced` and
`a_store_from_the_previous_store_format_is_dropped_whole_and_replaced`,
which cover a `VERSION` mismatch and a `CACHE_FORMAT` mismatch but, before
this, never a `FACTS_FORMAT`-only mismatch). It writes a store whose header
says `FACTS_FORMAT` `2` with today's `CACHE_FORMAT` and `VERSION`
otherwise unchanged, opens it, and asserts `facts_for` returns `None` (the
whole store is unread, not field-shifted) and that the first write since
replaces it under today's header, readable afterward. Passes. This closes
a real test gap the round left — the design (the format number lives in
the header line `IndexCache::open` compares byte-for-byte,
`index_cache.rs:103`) was sound but untested for this exact axis.
- **A3 tie-break: confirmed correct**, both via the shipped
`looking_a_name_up_answers_exactly_what_scanning_every_symbol_would`
(passes) and by re-deriving it: `by_name` is built with a **stable** sort
(`Vec::sort_by`, `lib.rs`), so symbols sharing a name keep declaration
order, and `symbols_named`'s two `partition_point` binary searches over
that name-sorted table can only reorder within a name if the sort were
unstable — it is not.
- **`nav::definition` / hover agreement:** confirmed the detail location is
filtered by `!span.is_empty()` (`nav.rs`) exactly as documented, and that a
detail-less symbol (ANSI port, ordinary declaration) still returns exactly
one location, unchanged from before this round.
## Review
**2026-08-28 — lead.** Accepted after one fix round. Gates re-run
independently: fmt clean, clippy silent, `cargo test --workspace` green
(2 396 passing at the time of review), `cargo test -p vlog_formatter` green.
`detail_span` is the right adaptation of the "detail range" idea to this
model: the non-ANSI merge already produced one symbol, so the only thing
missing was *where the declaration is completed*, and recording that as an
optional second span leaves every complete-where-named declaration
untouched. Hover and go-to-definition read the same field, which keeps
`topo.md`'s one-matcher rule intact.
Two things in this feature deserved the scrutiny they got.
**The facts-format bump.** The first implementation added two numbers per
declaration record without moving `FACTS_FORMAT`, on the argument that a
short record fails `done()` and is dropped. That argument only holds for the
*last* declaration in a record; every earlier one would have been read
field-shifted by two, which is a persisted cache handing back wrong spans —
the exact shape invariant 4 exists to catch, in the same family as the
macro-items corruption. Bumping 2→3 is correct and QA's added regression test
(`index_cache.rs`, a store from the previous format is dropped, not misread)
closes a gap no existing test covered, since nothing varied `FACTS_FORMAT`
alone.
**The comment attachment.** This began as scope creep — round 1's plan
explicitly deferred doc comments on hover — and then turned out to be
precisely what the user asked for, so it stays. But it is a *textual*
heuristic running over disk text on the cross-file path, and QA's PDS-1 found
it lying: `another_port_on` was a keyword blacklist, so a wrapped declaration
whose first line is bare `input` looked like an empty line and the next
port's comment attached to the previous port's card. Replacing the blacklist
with a closer whitelist (`only_a_closer_on`) inverts the bias in the one
direction that is safe — an unrecognised line now declines to attach rather
than mis-attaching — and the doc comment states that bias as the contract.
That is the correct resolution; a predicate over source text that guesses
must fail closed.
PDS-2 was a genuine divergence from the user's stated rule and is fixed by
making the three comment sources independent rather than a priority chain.
PDS-3 was worth chasing rather than parking: the binder does perform the same
header/body merge for `TfArg`, so old-style task and function arguments now
get detail spans too, and the gap is closed rather than documented. PDS-4's
CRLF strip is display-only and does not touch the buffer.
The dev renamed and inverted a QA-authored test, and flagged it. Correct call
and correctly surfaced: the behaviour that test pinned *was* the finding.