Compare commits

...
4 Commits
Author SHA1 Message Date
Guoliang ChenandClaude Mythos 5.2 a8c22dcab0 Release 0.65.9: lucisv-mcp no longer serves stale contents; the suite runs on Linux
ci / linux (push) Failing after 34s
ci / checks (push) Successful in 55s
ci / corpus (push) Successful in 16s
release / build-and-publish (push) Successful in 5m22s
TODO §70, closed.

- lucisv_mcp/src/project/files.rs: Stamp's racy rule (re-check by content a
  stamp taken too close to a timestamp it trusts) covered the mtime alone.
  On Linux, where ctime moves in 1 ms ticks, a same-size rewrite that
  restored the old mtime inside the tick of the server's read matched in
  every field and index-based answers came from the old text indefinitely.
  The rule now covers every trusted timestamp (mtime, and ctime where there
  is one), the window is 3 s, and a wall clock stepped back since the read
  distrusts the stamp. The decision is a pure compare(Seen, Clocks) with
  deterministic unit tests.
- Test-only: two stdin helpers tolerate BrokenPipe on the write to a child
  that exits before reading (lucisv cli.rs, lucisv_mcp qa_m8.rs); the
  didOpen latency test's budget is six parses of the same buffer, not 200 ms
  (lucisv_server e2e.rs); qa_m3's server is spawned before its checker
  thread, which removes a hang on a pipe inherited across threads on macOS.
- .gitea/workflows/ci.yml: a linux job on the luhpe-linux-x64 runner —
  clippy and cargo test --workspace on Linux x86-64.
- docs/features/mcp-transport describes the new rule and what it cannot see
  (Windows has no ctime; writable mmaps).

Linux: whole suite green 10/10 as root and 10/10 as a user (dev), 6/6 and
6/6 (QA). QA reproduced the stale read on 0.65.8 (65/65, 87/87 when the stat
was identical) and got 0 here. Dev, QA and lead review:
docs/features/linux-test-portability/README.md, Round 2.

Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots); notes in CHANGELOG.md (## 0.65.9) and
editors/vscode/CHANGELOG.md.

Gates: tools/gates.sh PASS on this tree including cross; lucisv_mcp 388/0.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-19 13:03:59 -08:00
Guoliang ChenandClaude Mythos 5.2 934d472af2 Release 0.65.8: Find References next to a name, edits kept in order, a startup that could take minutes
ci / checks (push) Successful in 54s
ci / corpus (push) Successful in 15s
release / build-and-publish (push) Successful in 5m28s
TODO §71.7. Three server bugs, all older than this series.

- A caret just past an identifier's last letter resolved the NEXT character
  (spans are end-exclusive): references, definition, hover and highlight came
  back empty where VS Code considers the caret on the word — the owner's
  'not found, then works after clicking back'. lucisv_server/src/caret.rs;
  nine position-to-symbol requests use it through Server::symbol_offset; the
  References view opens a row with the caret at the name's start.
- process_batch held requests during a scan but applied notifications at
  once, so a didChange could overtake an older one still queued; with
  incremental sync that corrupted the server's copy of the buffer until the
  file was reopened. Rule now: no notification overtakes an older unapplied
  notification (Server::must_hold, the 'behind' count for the burst a scan
  is nested in). Cancels wait whenever anything is held; responses never.
- answer_what_is_waiting acted on a didOpen it had queued but not applied,
  re-holding the same batch at every file of the startup scan (~300-400 s on
  OpenTitan). Scan state now changes only where a message is applied; a held
  batch is handed back at most once per applied didOpen.

An attempt to also drop excluded buffers from the index on close cost 190 ms
per open of an outside file and was reverted after QA measured it.

Dev (two rounds), QA (two rounds, own ordering driver: 9 118 bursts, no
wrong text) and lead review: docs/features/scan-ordering/README.md. TODO.md
files what stays open.

Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots); notes in CHANGELOG.md (## 0.65.8) and
editors/vscode/CHANGELOG.md.

Gates: tools/gates.sh PASS on this tree including cross;
lucisv_server 2030/0.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-19 11:47:14 -08:00
Guoliang ChenandClaude Mythos 5.2 dbb2349267 Release 0.65.7: 0.65.6, built for every platform
ci / checks (push) Successful in 54s
ci / corpus (push) Successful in 15s
release / build-and-publish (push) Successful in 5m19s
0.65.6 was tagged and never published: the release build failed to compile
lucisv-server for Windows. lucisv_core::walk::dir_id is a Copy (dev, ino)
pair on unix and an owned PathBuf elsewhere, and 71.1's
Workspace::holds_another_spelling_of moved it inside a closure
(lucisv_server/src/state/incremental.rs). Compared by reference now.

tools/gates.sh gains a `cross` step: cargo check of the three shipped
binaries for x86_64-pc-windows-gnu and x86_64-unknown-linux-musl with the
rustup toolchain release.sh --cross uses (skipped with a note when it is
absent). It fails on the unfixed tree with the release run's own error and
passes on this one. tools/RELEASING.md lists it.

CHANGELOG.md's 0.65.7 section carries 0.65.6's notes in full under a short
account of what happened; the v0.65.6 tag is left where it is.

Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots).

Gates: tools/gates.sh PASS on this tree including cross; a full local
tools/release.sh --cross and tools/audit_artifacts.sh dist pass (seven .vsix
packages, eighteen binaries).

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-19 10:52:35 -08:00
Guoliang ChenandClaude Mythos 5.2 58d3db3e3c Release 0.65.6: saving a file no longer re-indexes the workspace
ci / checks (push) Successful in 59s
ci / corpus (push) Successful in 16s
release / build-and-publish (push) Failing after 4m55s
TODO §71.1. On OpenTitan hw (4 058 files) every save cost ~160 ms of
whole-index work, twice (the save and VS Code's watcher echo), and watcher
events for files the index could not hold started whole rescans.

- vlog_semantic: resolution records every table lookup per reading file,
  misses included (workspace/dependents.rs, references.rs, replace.rs); an
  update re-resolves the edited file and the readers of keys whose values
  changed in what resolution reads. An unchanged record merges nothing. When
  the readers hold more than an eighth of all references, old results are
  removed in one pass over the postings.
- lucisv_server: watcher events are classified per file (state/watched.rs);
  the include graph keeps every include line as written and re-resolves the
  lines a named path could satisfy, in one pass per event; an event naming
  more paths than half the index takes the single rescan; an open buffer the
  index does not hold joins on its first save; completion tables are rebuilt
  only for the names a file declares. Every save still republishes every open
  buffer. The line-length lint follows the formatting style's width.
- Fixed on the way: removing an included header left other files' include
  edges pointing at it.

Typical saves: comment or watcher echo <0.3 ms, local signal 4 ms, package
member 12 ms; warm startup +40..120 ms for the readers table.

QA failed the first cut on four stale answers found with an independent
fresh-server oracle; all four are fixed and are differential tests. Dev
(three rounds), QA (two rounds) and lead review:
docs/features/localized-reindex/README.md. TODO.md files lane 71.7 from
what the QA rounds and an investigation found in earlier releases too.

Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots); notes in CHANGELOG.md (## 0.65.6) and
editors/vscode/CHANGELOG.md.

Gates: tools/gates.sh PASS on this tree; vlog_semantic 435/0,
lucisv_server 2011/0, lucisv_mcp 384/0.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-19 08:52:01 -08:00
59 changed files with 7906 additions and 474 deletions

No files matched your search

+25 -2
View File
@@ -1,7 +1,9 @@
# CI: the three checks CLAUDE.md requires before any work is finished,
# plus the extension's JavaScript tests and the corpus gate, enforced on
# every push. Runs on the self-hosted mac-arm64 runner in host mode (no
# containers), so the toolchain is the same one releases are built with.
# every push. Runs on the self-hosted macOS runner in host mode (no
# containers), so the toolchain is the same one releases are built with —
# and, since 0.65.9, the same checks on Linux (the `linux` job below), where
# the released Linux binaries had never been compiled-and-tested before.
name: ci
on:
push:
@@ -41,3 +43,24 @@ jobs:
run: cargo build --release -p lucisv
- name: Score and gate
run: scripts/corpus_gate.sh "$CORPUS"
# The suite on Linux x86-64: the luhpe-linux-x64 runner starts each job in
# the runner image (as root, 4 CPUs / 8 GB for the whole runner), with no
# Rust in it, so the toolchain is installed per job and the build is cold
# (a few minutes). Clippy is here as well as on macOS because code behind
# cfg(unix)/cfg(target_os) is only compiled on the platform it names: the
# first Linux trial failed clippy on imports macOS never saw. To run the
# same thing from a working tree without a push: tools/linux_check.sh.
linux:
runs-on: linux-x64
steps:
- uses: actions/checkout@v4
- name: Install the Rust toolchain
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \
| sh -s -- -y --profile minimal -c clippy,rustfmt
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
- name: cargo clippy
run: cargo clippy --all-targets -- -D warnings
- name: cargo test
run: cargo test --workspace
+211
View File
@@ -4,6 +4,217 @@ All notable changes to lucisv are recorded here. Versions follow
[semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes
(see `README.md`) are the only frozen contract.
## 0.65.9 — 2026-11-19
### `lucisv-mcp` no longer serves stale contents; the suite runs on Linux
(`docs/features/linux-test-portability`, Round 2; TODO §70.)
- **`lucisv-mcp` no longer answers from a file's old contents after a
same-size rewrite that restores its old modification time.** The server
decides whether a file changed from its size, mtime, change time and
inode, and re-reads a file whose mtime is too fresh to trust — but it did
not apply that caution to the change time. On Linux, where the change time
moves in 1 ms ticks, a file rewritten at the same size with its mtime put
back (`cp -p`, `rsync -t`, `touch -r`, a rename-over) inside the same tick
as the server's read matched in every field, and index-based answers
(`find`, `hierarchy`, `check`) came from the old text until the file
changed again. `read` and `outline` were never affected. The rule now
covers every timestamp the stamp trusts, its window is 3 s (2 s was too
close to FAT's 2-second timestamps), and a wall clock stepped backwards
since a read distrusts the stamp. Reproduced on purpose on 0.65.8 (every
run with an identical stat was stale) and gone on this build across
overlayfs, tmpfs and APFS; ordinary reads cause no extra re-read.
- **What it still cannot see**, now written down in
`docs/features/mcp-transport`: on Windows there is no change time or
inode, so a same-size rewrite that restores the old mtime more than 3 s
after a read goes unseen; and a store through a writable memory map that
the kernel has not yet reflected in the file's timestamps. A tree whose
files carry modification times in the future is re-read on every call.
- **The test suite is stable on Linux, and CI runs it there.** It was green
on Linux most of the time and failed about one run in three: two test
helpers insisted that writing to a child's input succeed (a usage error
exits before reading), one latency test used a fixed 200 ms budget (it now
measures against a parse of the same buffer in the same process), and one
MCP test could hang on macOS under load on a pipe inherited across
threads. Ten consecutive green runs as root and ten as an unprivileged
user, then six and six by QA. `ci.yml` has a `linux` job (clippy and the
whole suite on Linux x86-64) beside the macOS one.
## 0.65.8 — 2026-11-19
### Find References next to a name, edits kept in order, and a startup that could take minutes
(`docs/features/scan-ordering`; TODO §71.7. Three bugs, all older than this
series of releases.)
- **Find All References, Go to Definition, hover, highlight and rename work
with the cursor just after a name.** A double-click, a click on the right
half of a name's last letter, or a click on a row of lucisv's References
view leaves the cursor there, and the server used to look at the character
*after* the name — so VS Code said "No references found" until you clicked
away and back. Nine requests now resolve the name the cursor touches
(hover, definition, type definition, references, document highlight,
prepare-rename, rename, and the call- and type-hierarchy prepares); the
ones with boundary rules of their own (completion, signature help, linked
editing, selection range) are unchanged. The References view now opens a
row with the cursor at the start of the name. Checked on every identifier
of 350 files: the answer at the end of a name equals the answer at its
start, and a rename there never touches the neighbouring token.
- **Edits made while the workspace is re-indexing are applied in order.**
The server held requests during a scan but applied notifications at once,
so a newer edit could overtake an older one still queued — and since the
editor sends edits as differences, the server's copy of the file then
differed from the editor's until the file was closed and reopened: wrong
symbols, wrong diagnostics, wrong references. Edits, opens, closes, saves
and the other notifications the editor sends are now applied in the order
sent. QA's independent driver: 9 118 bursts, 87 % of them sent mid-scan,
no wrong text, no lost or duplicated answer; the same check fails on
0.65.7 at once.
- **Opening a file while the first index is built no longer makes that index
take minutes.** A request followed by a file open in the same batch was
handed back and re-held at every file of the startup scan: about 300–400 s
on OpenTitan instead of 2 s. Now a held batch is handed back at most once
per file actually opened; the same sequence takes 2.6–3.3 s.
- **Known and left for later**, all present before: a request held during a
scan is answered against the newest text, so a position-based request can
land on a different symbol if an edit moved the text under it (and rename
edits carry no document version for the client to reject a stale one by);
deleting a directory is not seen by the server (VS Code reports the folder,
which the client's source-file filter drops); an excluded file stays in the
index after it is closed; symlinked files can be held under two spellings;
renaming a port of a module defined twice gives an edit or a refusal at
random.
## 0.65.7 — 2026-11-19
### 0.65.6, built for every platform
0.65.6 was tagged but never published: it passed every gate on the Mac and
then failed to compile for Windows, so the release stopped before anything
was built for distribution. This release is 0.65.6 with that fixed; its
notes are below, unchanged.
- **The Windows build compiles again.** One comparison in the language
server's new "is this file already held under another spelling" check moved
a directory identity that is a small copyable pair on macOS and Linux but an
owned path on Windows (`lucisv_server/src/state/incremental.rs`).
- **The gates now compile for the other platforms.** `tools/gates.sh` has a
new `cross` step: `cargo check` of the three shipped binaries for Windows
and Linux, with the same toolchain the release build uses. Until now
platform-conditional code was first compiled by the release build itself,
after the gates.
### Saving a file no longer re-indexes the workspace
(`docs/features/localized-reindex`; TODO §71.1. Measured on OpenTitan's `hw`
tree, 4 058 files, with the server driven the way VS Code drives it.)
- **What was happening.** Every save cost about 160 ms of whole-index work
whatever was edited — 117 ms of it re-resolving all 470 000 cross-file
references — and VS Code triggered it twice, once for the save and once for
its own file watcher. Watcher events for files the index could not hold (a
generated file in a gitignored directory, a file outside the filelist or
folder scope, a held file reported through a symlinked root or in another
letter case) started a whole rescan with the progress bar, 270–750 ms.
- **Now the index does only what the edit can reach.**
| edit, then save | before | now |
|---|---:|---:|
| a comment, or the watcher's echo of any save | ~160 ms | under 0.3 ms |
| a local signal in `uart_tx` or `prim_flop` | ~170 ms | 4 ms |
| a member added to `uart_reg_pkg` | ~167 ms | 12 ms |
| a line above a module 125 files instantiate | ~163 ms | 47 ms |
| a member added to a package 677 files import | ~162 ms | 92 ms |
| a watcher event for a file outside the scope | up to 746 ms, with the bar | 3.5 ms |
The index records which names each file looked up — including the ones it
did not find — and re-resolves only the readers of names whose meaning
changed. A save whose index record is unchanged merges nothing.
- **Still wide, on purpose.** Adding or deleting a file; a burst of more
files in one watcher event than half the index holds (a branch switch),
which takes the one rescan it always did; an edit above a declaration many
files use. Every save still re-checks every open file's diagnostics, so a
`lucisv.toml` or waiver edit takes effect at the next save as before — with
200 files open that is most of a save (53 ms, against ~205 ms before).
- **The price.** Every whole rescan costs a few per cent more for the table
that makes the rest cheap: warm OpenTitan startup is 40–120 ms slower,
depending on machine load.
- **How it is known to be right.** After any sequence of edits, everything
the server answers must equal what a freshly started server answers for the
same files. QA built that oracle independently and it failed the first cut
on four stale answers (include links to headers outside the scope, lint
configuration, a file-age check macOS defeats, excluded open buffers); all
four are fixed and are now tests. The final build: 312 hand-written
comparisons and twelve random 300–500-step runs over the corpus and
OpenTitan with no divergence it caused.
- **Also.** The language server's `line-length` lint now follows the chosen
formatting style's width (80 under `ansi` and `nxp`, 120 under
`microsoft`), closing the limit noted in 0.65.5. Removing an included
header no longer leaves other files' include links pointing at it.
- **Known, and next.** Found by this round's QA and present in earlier
releases too: an edit made while a whole rescan is running can be applied
out of order, leaving the server's copy of the buffer wrong until the file
is reopened; a watcher event that names only a directory leaves stale
state; an excluded file stays indexed after it is closed. These are the
next round's work.
## 0.65.6 — 2026-11-19
### Saving a file no longer re-indexes the workspace
(`docs/features/localized-reindex`; TODO §71.1. Measured on OpenTitan's `hw`
tree, 4 058 files, with the server driven the way VS Code drives it.)
- **What was happening.** Every save cost about 160 ms of whole-index work
whatever was edited — 117 ms of it re-resolving all 470 000 cross-file
references — and VS Code triggered it twice, once for the save and once for
its own file watcher. Watcher events for files the index could not hold (a
generated file in a gitignored directory, a file outside the filelist or
folder scope, a held file reported through a symlinked root or in another
letter case) started a whole rescan with the progress bar, 270–750 ms.
- **Now the index does only what the edit can reach.**
| edit, then save | before | now |
|---|---:|---:|
| a comment, or the watcher's echo of any save | ~160 ms | under 0.3 ms |
| a local signal in `uart_tx` or `prim_flop` | ~170 ms | 4 ms |
| a member added to `uart_reg_pkg` | ~167 ms | 12 ms |
| a line above a module 125 files instantiate | ~163 ms | 47 ms |
| a member added to a package 677 files import | ~162 ms | 92 ms |
| a watcher event for a file outside the scope | up to 746 ms, with the bar | 3.5 ms |
The index records which names each file looked up — including the ones it
did not find — and re-resolves only the readers of names whose meaning
changed. A save whose index record is unchanged merges nothing.
- **Still wide, on purpose.** Adding or deleting a file; a burst of more
files in one watcher event than half the index holds (a branch switch),
which takes the one rescan it always did; an edit above a declaration many
files use. Every save still re-checks every open file's diagnostics, so a
`lucisv.toml` or waiver edit takes effect at the next save as before — with
200 files open that is most of a save (53 ms, against ~205 ms before).
- **The price.** Every whole rescan costs a few per cent more for the table
that makes the rest cheap: warm OpenTitan startup is 40–120 ms slower,
depending on machine load.
- **How it is known to be right.** After any sequence of edits, everything
the server answers must equal what a freshly started server answers for the
same files. QA built that oracle independently and it failed the first cut
on four stale answers (include links to headers outside the scope, lint
configuration, a file-age check macOS defeats, excluded open buffers); all
four are fixed and are now tests. The final build: 312 hand-written
comparisons and twelve random 300–500-step runs over the corpus and
OpenTitan with no divergence it caused.
- **Also.** The language server's `line-length` lint now follows the chosen
formatting style's width (80 under `ansi` and `nxp`, 120 under
`microsoft`), closing the limit noted in 0.65.5. Removing an included
header no longer leaves other files' include links pointing at it.
- **Known, and next.** Found by this round's QA and present in earlier
releases too: an edit made while a whole rescan is running can be applied
out of order, leaving the server's copy of the buffer wrong until the file
is reopened; a watcher event that names only a directory leaves stale
state; an excluded file stays indexed after it is closed. These are the
next round's work.
## 0.65.5 — 2026-11-19
### Named formatting styles
Generated
+9 -9
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.65.5"
version = "0.65.9"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.65.5"
version = "0.65.9"
[[package]]
name = "lucisv_mcp"
version = "0.65.5"
version = "0.65.9"
dependencies = [
"lucisv_core",
"serde",
@@ -126,7 +126,7 @@ dependencies = [
[[package]]
name = "lucisv_server"
version = "0.65.5"
version = "0.65.9"
dependencies = [
"lsp-server",
"lsp-types",
@@ -262,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.65.5"
version = "0.65.9"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.65.5"
version = "0.65.9"
dependencies = [
"lucisv_core",
"vlog_formatter",
@@ -279,11 +279,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.65.5"
version = "0.65.9"
[[package]]
name = "vlog_refactor"
version = "0.65.5"
version = "0.65.9"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -292,7 +292,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.65.5"
version = "0.65.9"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -13,7 +13,7 @@ members = [
]
[workspace.package]
version = "0.65.5"
version = "0.65.9"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+70 -5
View File
@@ -7299,9 +7299,9 @@ as the trial shows. One lane, `docs/features/linux-test-portability`;
left implicit, assertions on wall-clock or environment that the runner
shows to be fragile. No test is deleted and the test count does not
drop; no production code and nothing in `verify.rs` changes.
- [ ] `cargo test --workspace` green on Linux as root and with `--user`,
- [x] `cargo test --workspace` green on Linux as root and with `--user`,
and `tools/gates.sh` green on macOS.
- [ ] (lead) `.gitea/workflows/ci.yml` gains a `linux` job on `linux-x64`;
- [x] (lead) `.gitea/workflows/ci.yml` gains a `linux` job on `linux-x64`;
`docs/topo.md` and `tools/RELEASING.md` updated.
## 71. The overnight queue (2026-11-19, owner's order) — eight features, one release each
@@ -7315,7 +7315,8 @@ the OpenTitan tree (not only on unit fixtures) before it is called done.
The items are the owner's words, lightly condensed; each gets its own
subsection, plan and `docs/features/<name>/README.md` when its turn comes.
- [ ] **71.1 An edit does not re-index the whole database.** Today every
- [x] **71.1 An edit does not re-index the whole database.** (0.65.6, `docs/features/localized-reindex`)
Today every
file edit re-indexes everything. A change to a `define` may have to;
a typical, localized edit must not.
- [ ] **71.2 Actions stay fast on a huge, heavily-dependent tree.** Do the
@@ -7339,7 +7340,8 @@ subsection, plan and `docs/features/<name>/README.md` when its turn comes.
file's instance and its parents in different shades — bright light
orange for the instance, dimmer the further up — or anything in that
spirit that makes the hierarchy easy to read.
- [ ] **71.7 Find References sometimes answers "not found"** on a
- [x] **71.7 Find References sometimes answers "not found"** (0.65.8, `docs/features/scan-ordering`: a server bug — the caret just past a name)
on a
port/signal, then works after clicking elsewhere and back. VS Code or
the server? Investigate, then fix what is ours.
- [x] **71.8 Comments: no code colours inside them** (0.65.3, `docs/features/comment-highlighting`; the bracket colour is VS Code's, explained not changed)
@@ -7399,8 +7401,71 @@ indexing, collide with each other and with §70's test files, and wait for
formatter should not need it.
- [ ] `` `ifdef `` between `end` and `else` is a parse error.
- [ ] An attribute on an ANSI port (`(* keep *) input a`) is a parse error.
- [ ] The server's `line-length` lint falls back to 100 columns under the
- [x] The server's `line-length` lint falls back to 100 columns under the
`ansi`/`microsoft`/`nxp` styles (`lucisv_server/src/lint.rs`); taken
when 71.1 merges.
- [ ] One-per-line styles give multi-instance declarations
(`p1 u8 (...), u9 (...)`) the hanging layout.
- Wave 5 (lead, 2026-11-19): 71.1 shipped as 0.65.6 after a QA FAIL (four
stale answers), a fix round, a QA pass and a last small round. What the
QA rounds and a read-only investigation turned up, all present before this
wave, becomes lane **71.7** (the owner's Find References item, widened):
- [x] A caret just past an identifier's last letter asks about the next
character: references, definition, hover and highlight come back
empty (`server/dispatch.rs` `Server::offset`). This is the owner's
"not found, then works after clicking back".
- [x] A `didChange` arriving during a whole rescan can overtake an older
one still queued (`server/mod.rs` `process_batch`): with incremental
sync the server's buffer is corrupted until the file is reopened.
- [x] A burst `[request, didOpen]` during the startup scan is re-held at
every file (`server/index.rs` `answer_what_is_waiting`): the scan
takes ~300 s on OpenTitan instead of ~1.7 s.
- [ ] A watcher event naming only a directory leaves stale state; an
excluded buffer stays indexed after close; symlinked files are held
under one or both spellings depending on what was open.
71.3 (viewport highlighting) passed QA with a gap in the default folder
scope (colours wait out a widen, ~630 ms); it is rebased after 71.7 and
closes that in its fix round. Then 71.2.
- 0.65.6 never published (lead, 2026-11-19): the release build failed to
compile `lucisv-server` for Windows — `dir_id` is a `Copy` pair on unix and
a `PathBuf` elsewhere, and 71.1's new code moved it in a closure
(`state/incremental.rs`). The gate caught nothing because nothing before
the release build compiles for another platform. Fixed by the lead (one
line) and shipped as 0.65.7 with 0.65.6's notes; `tools/gates.sh` gains a
`cross` step so the next one is caught before the tag. Seven of the eight
§71 items therefore have releases 0.65.2–0.65.5 and 0.65.7.
- Wave 6 (lead, 2026-11-19): 71.7 shipped as 0.65.8. Left open from it and
from its QA, all older than this series:
- [ ] A request held during a scan is answered against the newest text; a
position-based one can resolve a different symbol when an edit moved
the text under it, and rename edits carry no document version.
- [ ] An unheld buffer opened while a scan runs is never taken in
afterwards; closing an unsaved in-scope buffer a rescan had indexed
leaves its text in the index.
- [ ] Renaming a port of a module defined twice gives an edit or a refusal
at random (`qa717/drv/dup.py`).
- [ ] Directory-only watcher events (needs a broader watcher
registration — the owner's call), excluded buffers after close (a
cheap fix belongs in the index layer: adding a file is a wide
change), symlink spellings.
- §70 closed (lead, 2026-11-19), shipped with 0.65.9. Once ssh was back the
suite proved flaky on Linux (3 of 9 runs): two test helpers that insisted
a write to a child's stdin succeed, a 200 ms wall-clock bound, an MCP test
that could hang on an inherited pipe — and one real bug, `lucisv-mcp`
serving stale contents after a same-tick, same-size rewrite on Linux
(`project/files.rs`, the racy rule covered the mtime alone). All fixed in
lane 70b (`docs/features/linux-test-portability`, Round 2); Linux is green
10/10 as root and as a user (dev) and 6/6 each (QA); `ci.yml` has its
`linux` job. Left open:
- [ ] A file with an mtime in the future is re-read by `lucisv-mcp` on
every call, forever (67 ms against 7 ms per `find` on 4 000 files).
- [ ] `crates/lucisv/tests/cli.rs:2149` asserts only an empty stdout, no
exit code.
- [ ] `crates/lucisv_mcp/tests/qa_m3.rs` uses unix-only APIs with no cfg:
`cargo check --all-targets` for Windows fails there (tests only).
- [ ] The release is still gated on macOS alone; Windows is compile-checked
(`cross`), never executed.
+24 -10
View File
@@ -92,16 +92,29 @@ fn run_in(dir: &TempDir, args: &[&str]) -> Output {
Command::new(LUCISV).args(args).current_dir(&dir.path).output().expect("run lucisv")
}
/// Runs lucisv with the cache switched off, `input` on its stdin.
fn run_with_stdin(args: &[&str], input: &str) -> Output {
let mut child = Command::new(LUCISV)
.args(with_no_cache(args))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("spawn lucisv");
child.stdin.as_mut().expect("stdin").write_all(input.as_bytes()).expect("write stdin");
child.wait_with_output().expect("run lucisv")
run_with_stdin_raw(&with_no_cache(args), input)
}
/// Writes `input` to the child's stdin and closes it.
///
/// A child that exits without reading — a usage error refuses before it
/// looks at stdin — is legitimate, and the write then races its exit: it
/// fails with `BrokenPipe` when the child is already gone. That one error is
/// not the test's business; the exit code and output the caller asserts on
/// are. (A successful write never meant the child read anything either:
/// every input here is far smaller than a pipe's buffer, so the write lands
/// in the buffer whether or not the child ever reads it.) Any other error is
/// a failure.
fn feed(child: &mut std::process::Child, input: &str) {
let mut stdin = child.stdin.take().expect("stdin");
match stdin.write_all(input.as_bytes()) {
Err(error) if error.kind() != std::io::ErrorKind::BrokenPipe => {
panic!("write stdin: {error:?}")
}
_ => {}
}
}
fn code(out: &Output) -> i32 {
@@ -1755,6 +1768,7 @@ fn lines_neither_reads_nor_writes_the_cache() {
assert!(!fresh.cache_file().exists(), "a range run must not seed the cache");
}
/// Runs lucisv exactly as given, cache and all, `input` on its stdin.
fn run_with_stdin_raw(args: &[&str], input: &str) -> Output {
let mut child = Command::new(LUCISV)
.args(args)
@@ -1763,7 +1777,7 @@ fn run_with_stdin_raw(args: &[&str], input: &str) -> Output {
.stderr(Stdio::piped())
.spawn()
.expect("spawn lucisv");
child.stdin.as_mut().expect("stdin").write_all(input.as_bytes()).expect("write stdin");
feed(&mut child, input);
child.wait_with_output().expect("run lucisv")
}
+254 -28
View File
@@ -5,7 +5,7 @@
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};
use std::time::{Duration, Instant, SystemTime};
use lucisv_core::cache::content_hash;
use lucisv_core::config::Discovery;
@@ -16,11 +16,25 @@ use lucisv_core::walk::collect_files_with;
/// something an agent wants summarised.
pub const MAX_FILE_BYTES: u64 = 1024 * 1024;
/// A file whose mtime is this close to the moment it was read may have been
/// written again within the filesystem's timestamp resolution, so its stamp
/// proves nothing: it is re-read (and re-hashed) until it is older than
/// this. Git's "racy clean" rule, for the same reason.
const RACY: Duration = Duration::from_secs(2);
/// A file whose mtime or ctime is this close to the moment it was read may
/// have been written again within the filesystem's timestamp resolution, so
/// its stamp proves nothing: it is re-read (and re-hashed) until it is older
/// than this. Git's "racy clean" rule, for the same reason.
///
/// The window must outlast the coarsest timestamp a filesystem keeps plus
/// how far its clock can lag the one `read_at` comes from. Linux stamps
/// files from a clock that moves in 1–4 ms ticks; ext3 and many network
/// mounts keep whole seconds, FAT two. Three seconds covers FAT's two with
/// a second to spare. A just-changed file costs a few more re-reads; a
/// window too short costs stale contents.
const RACY: Duration = Duration::from_secs(3);
/// How far the wall clock may fall behind the monotonic one since a read
/// before the stamp stops being trusted: a clock stepped back can give a
/// later write the very timestamp the stamp holds. Large next to the
/// microseconds between the paired clock reads, small next to the margin
/// [`RACY`] keeps over the coarsest timestamps.
const STEP_BACK: Duration = Duration::from_millis(100);
/// The files one discovery found, and what it had to say about the rest.
#[derive(Debug, Default)]
@@ -137,13 +151,16 @@ pub struct Stamp {
pub mtime: Option<SystemTime>,
/// `content_hash` of its bytes.
pub hash: u64,
/// When it was read.
/// When it was read, by the wall clock file timestamps are compared with.
pub read_at: SystemTime,
/// The same moment by the monotonic clock: what tells a wall clock that
/// was stepped back since the read.
pub read_mono: Instant,
/// Its ctime and inode — what still moves when a same-size rewrite puts
/// the old mtime back (`cp -p`, `rsync -t`, `touch -r`), git's answer to
/// the same problem. Zero off Unix, where size, mtime and the racy rule
/// the same problem. `None` off Unix, where size, mtime and the racy rule
/// are all there is.
pub identity: (i64, i64, u64),
pub identity: Option<Identity>,
/// Whether its text spells `endprogram` — the cheap test that says a
/// `Module`-kind unit in it might be a `program` (the semantic layer
/// models both as a module).
@@ -161,6 +178,42 @@ pub enum Change {
Gone,
}
/// A file's inode change time and inode number (Unix only).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Identity {
/// The ctime, `None` when it does not fit a `SystemTime`.
pub ctime: Option<SystemTime>,
/// The inode number.
pub ino: u64,
}
/// What one `stat` says about a file, as far as a stamp is concerned.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Seen {
size: u64,
mtime: Option<SystemTime>,
identity: Option<Identity>,
}
impl Seen {
fn of(meta: &fs::Metadata) -> Seen {
Seen { size: meta.len(), mtime: meta.modified().ok(), identity: identity(meta) }
}
}
/// The two clocks, read back to back.
#[derive(Debug, Clone, Copy)]
struct Clocks {
wall: SystemTime,
mono: Instant,
}
impl Clocks {
fn now() -> Clocks {
Clocks { wall: SystemTime::now(), mono: Instant::now() }
}
}
impl Stamp {
/// Compare the file on disk with this stamp, by one `stat`.
pub fn check(&self, path: &Path) -> Change {
@@ -170,18 +223,56 @@ impl Stamp {
if !meta.is_file() || meta.len() > MAX_FILE_BYTES {
return Change::Gone;
}
let mtime = meta.modified().ok();
let racy = match mtime {
Some(mtime) => mtime + RACY > self.read_at,
None => true,
};
let moved = meta.len() != self.size || mtime != self.mtime;
if moved || identity(&meta) != self.identity || racy {
self.compare(Seen::of(&meta), Clocks::now())
}
/// The decision [`Stamp::check`] makes, from what the `stat` saw and
/// what the clocks say now.
fn compare(&self, seen: Seen, now: Clocks) -> Change {
let moved =
seen.size != self.size || seen.mtime != self.mtime || seen.identity != self.identity;
if moved || self.racy() || self.clock_stepped_back(now) {
Change::Suspect
} else {
Change::Same
}
}
/// **Invariant: a stamp is trusted on a later match only if every
/// timestamp it trusts (the mtime, and the ctime where there is one) is
/// at least [`RACY`] older than the moment the stamp was taken** —
/// otherwise a write inside the same timestamp tick, after the read,
/// leaves every one of them as it was. A timestamp that is missing, or
/// later than the read (a clock behind the filesystem's), is racy too.
fn racy(&self) -> bool {
let ctime = self.identity.map(|identity| identity.ctime);
[Some(self.mtime), ctime].into_iter().flatten().any(|stamped| match stamped {
Some(time) => time.checked_add(RACY).is_none_or(|settled| settled > self.read_at),
None => true,
})
}
/// Whether the wall clock is now more than [`STEP_BACK`] behind where
/// the monotonic clock says it would be had it only run forward since
/// the read. After such a step a new write can be stamped with an old
/// time, so no timestamp match means anything until the file is re-read.
fn clock_stepped_back(&self, now: Clocks) -> bool {
let expected = match now.mono.checked_duration_since(self.read_mono) {
Some(elapsed) => self.read_at.checked_add(elapsed),
None => self.read_at.checked_sub(self.read_mono - now.mono),
};
match (expected, now.wall.checked_add(STEP_BACK)) {
(Some(expected), Some(tolerated)) => tolerated < expected,
_ => true,
}
}
/// This stamp as if it had been taken `by` later, on both clocks: how a
/// test ages a stamp past the racy window without waiting for it.
#[cfg(test)]
pub(crate) fn taken_later(self, by: Duration) -> Stamp {
Stamp { read_at: self.read_at + by, read_mono: self.read_mono + by, ..self }
}
}
/// Read one source file and stamp it. `Err` for a file that is gone or is
@@ -191,33 +282,43 @@ pub fn read_source(path: &Path) -> io::Result<(String, Stamp)> {
// Stat before reading: a write that lands between the two leaves a stamp
// older than the bytes, which the next sweep sees as a change.
let meta = fs::metadata(path)?;
let read_at = SystemTime::now();
let read = Clocks::now();
let bytes = fs::read(path)?;
let hash = content_hash(&bytes);
let text = String::from_utf8(bytes)
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "not UTF-8 text"))?;
let seen = Seen::of(&meta);
let stamp = Stamp {
size: meta.len(),
mtime: meta.modified().ok(),
size: seen.size,
mtime: seen.mtime,
hash,
read_at,
identity: identity(&meta),
read_at: read.wall,
read_mono: read.mono,
identity: seen.identity,
program: text.contains("endprogram"),
};
Ok((text, stamp))
}
/// A file's ctime (seconds, nanoseconds) and inode number.
/// A file's ctime and inode number.
#[cfg(unix)]
fn identity(meta: &fs::Metadata) -> (i64, i64, u64) {
fn identity(meta: &fs::Metadata) -> Option<Identity> {
use std::os::unix::fs::MetadataExt;
(meta.ctime(), meta.ctime_nsec(), meta.ino())
let nanos = Duration::from_nanos(u64::try_from(meta.ctime_nsec()).unwrap_or(0));
let ctime = match u64::try_from(meta.ctime()) {
Ok(secs) => SystemTime::UNIX_EPOCH.checked_add(Duration::from_secs(secs) + nanos),
Err(_) => SystemTime::UNIX_EPOCH
.checked_sub(Duration::from_secs(meta.ctime().unsigned_abs()))
.and_then(|time| time.checked_add(nanos)),
};
Some(Identity { ctime, ino: meta.ino() })
}
/// No ctime or inode off Unix: the stamp falls back to size and mtime.
/// No ctime or inode off Unix (std has no change time on Windows): the
/// stamp falls back to size and mtime, and the racy rule on the mtime.
#[cfg(not(unix))]
fn identity(_: &fs::Metadata) -> (i64, i64, u64) {
(0, 0, 0)
fn identity(_: &fs::Metadata) -> Option<Identity> {
None
}
#[cfg(test)]
@@ -273,7 +374,7 @@ mod tests {
let (_, stamp) = read_source(&path).unwrap();
// Just written: racy, so suspect even though nothing moved.
assert_eq!(stamp.check(&path), Change::Suspect);
let settled = Stamp { read_at: stamp.read_at + RACY + RACY, ..stamp };
let settled = stamp.taken_later(RACY + RACY);
assert_eq!(settled.check(&path), Change::Same);
fs::write(&path, "module a2; endmodule\n").unwrap();
assert_eq!(settled.check(&path), Change::Suspect);
@@ -281,4 +382,129 @@ mod tests {
assert_eq!(settled.check(&path), Change::Gone);
fs::remove_dir_all(dir).unwrap();
}
// The racy rule, decided from values: no file, no waiting, no clock but
// the ones given.
/// A stamp taken at `read` (wall) / `mono`, of a file whose mtime and
/// ctime are `mtime_age` and `ctime_age` before the read.
fn stamp_aged(
read: SystemTime,
mono: Instant,
mtime_age: Duration,
ctime_age: Duration,
) -> Stamp {
Stamp {
size: 20,
mtime: Some(read - mtime_age),
hash: 7,
read_at: read,
read_mono: mono,
identity: Some(Identity { ctime: Some(read - ctime_age), ino: 42 }),
program: false,
}
}
/// What a `stat` of the unchanged file sees.
fn unchanged(stamp: &Stamp) -> Seen {
Seen { size: stamp.size, mtime: stamp.mtime, identity: stamp.identity }
}
/// The clocks a second after the read, both having run forward.
fn a_second_later(stamp: &Stamp) -> Clocks {
let second = Duration::from_secs(1);
Clocks { wall: stamp.read_at + second, mono: stamp.read_mono + second }
}
#[test]
fn a_match_is_trusted_only_when_every_timestamp_was_settled_at_the_read() {
let (read, mono) = (SystemTime::now(), Instant::now());
let old = Duration::from_secs(3600);
let fresh = Duration::from_millis(1);
let cases = [
("neither racy", old, old, Change::Same),
("mtime racy", fresh, old, Change::Suspect),
// The Linux hole: an old mtime put back, a ctime from this tick.
("ctime racy", old, fresh, Change::Suspect),
("both racy", fresh, fresh, Change::Suspect),
("just inside the window", old, RACY - Duration::from_nanos(1), Change::Suspect),
("exactly the window old", old, RACY, Change::Same),
];
for (what, mtime_age, ctime_age, expected) in cases {
let stamp = stamp_aged(read, mono, mtime_age, ctime_age);
assert_eq!(
stamp.compare(unchanged(&stamp), a_second_later(&stamp)),
expected,
"{what}"
);
}
}
#[test]
fn a_timestamp_later_than_the_read_or_missing_is_racy() {
let (read, mono) = (SystemTime::now(), Instant::now());
let old = Duration::from_secs(3600);
let mut ahead = stamp_aged(read, mono, old, old);
ahead.identity = Some(Identity { ctime: Some(read + Duration::from_secs(60)), ino: 42 });
assert_eq!(ahead.compare(unchanged(&ahead), a_second_later(&ahead)), Change::Suspect);
let mut no_ctime = stamp_aged(read, mono, old, old);
no_ctime.identity = Some(Identity { ctime: None, ino: 42 });
assert_eq!(
no_ctime.compare(unchanged(&no_ctime), a_second_later(&no_ctime)),
Change::Suspect
);
let mut no_mtime = stamp_aged(read, mono, old, old);
no_mtime.mtime = None;
assert_eq!(
no_mtime.compare(unchanged(&no_mtime), a_second_later(&no_mtime)),
Change::Suspect
);
// Off Unix there is no ctime to trust: the mtime alone decides.
let mut off_unix = stamp_aged(read, mono, old, old);
off_unix.identity = None;
assert_eq!(off_unix.compare(unchanged(&off_unix), a_second_later(&off_unix)), Change::Same);
}
#[test]
fn a_wall_clock_stepped_back_since_the_read_distrusts_the_stamp() {
let (read, mono) = (SystemTime::now(), Instant::now());
let old = Duration::from_secs(3600);
let stamp = stamp_aged(read, mono, old, old);
let ten = Duration::from_secs(10);
// Ten seconds of real time, but the wall clock shows one: stepped back.
let back = Clocks { wall: read + Duration::from_secs(1), mono: mono + ten };
assert_eq!(stamp.compare(unchanged(&stamp), back), Change::Suspect);
// Behind the read itself.
let behind = Clocks { wall: read - ten, mono: mono + Duration::from_secs(1) };
assert_eq!(stamp.compare(unchanged(&stamp), behind), Change::Suspect);
// A wall clock that ran ahead (a suspend the monotonic clock slept
// through) is no reason to doubt anything.
let ahead = Clocks { wall: read + ten, mono: mono + Duration::from_secs(1) };
assert_eq!(stamp.compare(unchanged(&stamp), ahead), Change::Same);
// Jitter under the tolerance is not a step.
let jitter = Clocks { wall: read + ten - STEP_BACK / 2, mono: mono + ten };
assert_eq!(stamp.compare(unchanged(&stamp), jitter), Change::Same);
// A stamp aged on both clocks at once is not a step either.
let aged = stamp.taken_later(ten);
assert_eq!(aged.compare(unchanged(&aged), a_second_later(&stamp)), Change::Same);
}
#[test]
fn any_moved_field_is_suspect_however_settled() {
let (read, mono) = (SystemTime::now(), Instant::now());
let old = Duration::from_secs(3600);
let stamp = stamp_aged(read, mono, old, old);
let now = a_second_later(&stamp);
let same = unchanged(&stamp);
let identity = stamp.identity.unwrap();
let moved = [
Seen { size: 21, ..same },
Seen { mtime: Some(read), ..same },
Seen { identity: Some(Identity { ino: 43, ..identity }), ..same },
Seen { identity: Some(Identity { ctime: Some(read - old / 2), ..identity }), ..same },
];
for seen in moved {
assert_eq!(stamp.compare(seen, now), Change::Suspect, "{seen:?}");
}
}
}
+2 -3
View File
@@ -4,7 +4,7 @@
use std::fs;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};
use std::time::Duration;
use vlog_semantic::WorkspaceIndex;
@@ -29,9 +29,8 @@ fn rebuilt(project: &Project) -> String {
/// Age every stamp past the racy window, so only a real change is suspect.
fn settle(project: &mut Project) {
let later = SystemTime::now() + Duration::from_secs(10);
for stamp in project.files.values_mut() {
stamp.read_at = later;
*stamp = stamp.taken_later(Duration::from_secs(10));
}
}
+9 -1
View File
@@ -706,6 +706,15 @@ fn qa_lucisv_check_over_the_same_tree_while_the_server_formats() {
copy_tree(&scratch.0, &reference.0);
let status = Command::new(&cli).arg("--no-cache").arg(&reference.0).output().unwrap();
assert!(status.status.success(), "{status:?}");
// The server is spawned before the checker starts, never while it runs.
// A spawn on one thread can inherit a pipe another thread is just
// creating for its child: macOS has no `pipe2`, so close-on-exec is set
// in a second step. Seen once under load (2026-11-19, `lsof`): the
// server held the write end of a `lucisv --check`'s stdout. That
// `output()` never saw EOF, `join` below waited on it, and the server,
// which lives until this test ends, never let go, so the test hung.
// Spawned first, the server cannot hold any of the checker's pipes.
let mut server = Session::over(&scratch);
let stop = Arc::new(AtomicBool::new(false));
let checker = {
let (stop, cli, root) = (Arc::clone(&stop), cli.clone(), scratch.0.clone());
@@ -719,7 +728,6 @@ fn qa_lucisv_check_over_the_same_tree_while_the_server_formats() {
codes
})
};
let mut server = Session::over(&scratch);
for _ in 0..5 {
for (name, text) in &messy {
scratch.write(name, text);
+8 -1
View File
@@ -113,7 +113,14 @@ fn run(args: &[&str], lines: &[Value]) -> Output {
Value::String(raw) => raw.clone(),
other => other.to_string(),
};
writeln!(stdin, "{text}").unwrap();
// A refused argument list exits 2 before reading a byte, so the write
// races that exit and can fail with `BrokenPipe`. That is the child
// being gone, not the test failing: what it said and its exit code
// are what the caller asserts on. Any other error is a failure.
match writeln!(stdin, "{text}") {
Err(error) if error.kind() == std::io::ErrorKind::BrokenPipe => break,
result => result.unwrap(),
}
}
drop(stdin);
child.wait_with_output().unwrap()
+105 -9
View File
@@ -197,17 +197,86 @@ impl Candidates {
/// patched: this file's old words are given back and its new ones taken,
/// so nothing else is re-lexed. The result is what a whole
/// [`Candidates::build`] over the same files would have produced.
#[cfg(test)]
pub fn update_file(&mut self, index: &WorkspaceIndex, path: &Path, text: &str) {
self.update_words(index, path, words_in(text));
}
/// [`Candidates::update_file`] for a file whose words the caller already
/// has — an open buffer's, read off the tokens it was analyzed from.
#[cfg(test)]
pub fn update_words(&mut self, index: &WorkspaceIndex, path: &Path, words: Vec<String>) {
self.take_index_tables(index);
self.set_words(path, words);
}
/// [`Candidates::update_words`] in two halves, for a caller that knows
/// which it needs: the word table patched by this file alone…
pub fn set_file_words(&mut self, path: &Path, words: Vec<String>) {
self.set_words(path, words);
}
/// …and the two index-derived tables re-derived for the names one file declared
/// before or declares now — `symbols` its units and connection members,
/// `macros` its `` `define``s ([`FileFacts::declared_names`]) — which are
/// the only entries its update can move.
///
/// Exact because every table here is one block per exact name ([`word_cmp`]
/// is total, so equal keys are equal names) and each block is read off
/// the index for that name alone: the unit block from the symbol listing
/// restricted to the name, in the listing's order and deduplicated the
/// same way; a module name present exactly when some unit of it is
/// instantiable; a macro's entry from its first definition in file order.
/// So a block re-derived here is the block a whole re-derivation gives,
/// and every other block is untouched by an update that does not name it.
///
/// [`FileFacts::declared_names`]: vlog_semantic::FileFacts::declared_names
pub fn refresh_names(
&mut self,
index: &WorkspaceIndex,
symbols: &HashSet<&str>,
macros: &HashSet<&str>,
) {
let (fresh, _) = unit_tables(index, index.symbols_named(symbols));
let mut held = std::mem::take(&mut self.units);
held.retain(|unit| !symbols.contains(unit.name.as_str()));
self.units = merge_by_name(held, fresh, |unit| unit.name.as_str());
self.unit_masks = self.units.iter().map(|unit| char_mask(&unit.name)).collect();
for name in symbols {
let instantiable = index.units(name).iter().any(|def| def.kind.is_instantiable());
match (self.modules.binary_search_by(|held| held.as_str().cmp(name)), instantiable) {
(Ok(at), false) => {
self.modules.remove(at);
}
(Err(at), true) => self.modules.insert(at, name.to_string()),
_ => {}
}
}
let mut fresh: Vec<Macro> = macros
.iter()
.filter_map(|name| index.find_define(name).first().map(|(_, define)| macro_of(define)))
.collect();
sort_by_name(&mut fresh, |m| m.name.as_str());
let mut held = std::mem::take(&mut self.macros);
held.retain(|m| !macros.contains(m.name.as_str()));
self.macros = merge_by_name(held, fresh, |m| m.name.as_str());
}
/// Every table, rendered for comparison — the equivalence witness the
/// incremental tests hold an updated workspace to a rebuilt one with.
#[cfg(test)]
pub fn fingerprint(&self) -> String {
let mut word_files: Vec<(&String, &usize)> = self.word_files.iter().collect();
word_files.sort();
let mut per_file: Vec<(&PathBuf, &Vec<String>)> = self.per_file.iter().collect();
per_file.sort();
format!(
"units {:?}\nunit_masks {:?}\nmodules {:?}\nmacros {:?}\nwords {:?}\n\
word_masks {:?}\nword_files {word_files:?}\nper_file {per_file:?}\n",
self.units, self.unit_masks, self.modules, self.macros, self.words, self.word_masks
)
}
/// [`Candidates::update_words`] for a batch of files — the form a scan
/// publishing what it has indexed so far uses.
///
@@ -715,7 +784,15 @@ fn char_mask(text: &str) -> u32 {
/// tables want the same records. It is paid once per index build rather than
/// once per keystroke, which is the whole point of both.
fn index_tables(index: &WorkspaceIndex) -> (Vec<Candidate>, Vec<String>) {
let symbols = index.workspace_symbols("");
unit_tables(index, index.workspace_symbols(""))
}
/// [`index_tables`] over a given part of the symbol listing — all of it, or
/// the names one update touched — in the listing's own order.
fn unit_tables(
index: &WorkspaceIndex,
symbols: Vec<vlog_semantic::WorkspaceSymbol<'_>>,
) -> (Vec<Candidate>, Vec<String>) {
// `workspace_symbols` sorts by name first — with `str`'s own `Ord`, not a
// case-folded one — so same-named declarations are already adjacent and a
// plain `dedup` leaves one entry per module name, in `str` order. That is
@@ -757,14 +834,7 @@ fn macros_of(index: &WorkspaceIndex) -> Vec<Macro> {
for id in 0..index.files().len() {
let Some(table) = index.defines(vlog_semantic::FileId(id as u32)) else { continue };
for define in table.entries().iter().filter(|d| d.kind == DefineKind::Define) {
let args = match &define.params {
Some(params) => format!("({})", params.join(", ")),
None => String::new(),
};
out.push(Macro {
name: define.name.clone(),
detail: format!("`define {}{args}", define.name),
});
out.push(macro_of(define));
}
}
sort_by_name(&mut out, |m| m.name.as_str());
@@ -772,6 +842,31 @@ fn macros_of(index: &WorkspaceIndex) -> Vec<Macro> {
out
}
/// One `` `define``'s completion entry.
fn macro_of(define: &vlog_parser::defines::Define) -> Macro {
let args = match &define.params {
Some(params) => format!("({})", params.join(", ")),
None => String::new(),
};
Macro { name: define.name.clone(), detail: format!("`define {}{args}", define.name) }
}
/// Two lists sorted by [`word_cmp`] with no name in common, as one.
fn merge_by_name<T>(held: Vec<T>, fresh: Vec<T>, name: impl Fn(&T) -> &str) -> Vec<T> {
let mut out = Vec::with_capacity(held.len() + fresh.len());
let mut fresh = fresh.into_iter().peekable();
for item in held {
while let Some(next) =
fresh.next_if(|next| word_cmp(name(next), name(&item)) == Ordering::Less)
{
out.push(next);
}
out.push(item);
}
out.extend(fresh);
out
}
/// Every distinct identifier one file's token stream contains.
///
/// **`vlog_semantic::words::harvest_text`, under this crate's old name.** The
@@ -786,6 +881,7 @@ fn macros_of(index: &WorkspaceIndex) -> Vec<Macro> {
/// one pass at the end: no part of a scan may be longer than one file, or the
/// message queue goes unanswered for the length of it
/// (`docs/features/scan-interleave/README.md`).
#[cfg(test)]
pub(crate) fn words_in(text: &str) -> Vec<String> {
words::harvest_text(text)
}
+127
View File
@@ -0,0 +1,127 @@
//! Which byte a "symbol under the cursor" request is about.
//!
//! An LSP position is a caret *between* two characters, and a span here is
//! end-exclusive, so a caret just past an identifier's last letter names the
//! character **after** the name. VS Code calls that caret "on the word" — a
//! double-click, a click on the right half of the last letter, or a jump that
//! selects the name all leave it there, and its own word highlight and the
//! title of a references search both use the word before it. Asking about the
//! next character instead answered `[]`, and VS Code said "No references
//! found" for a name it was showing as selected
//! (`docs/features/scan-ordering/README.md`, A1).
//!
//! The rule is VS Code's: a caret touching a name on its right edge is on
//! that name — unless a name also starts at the caret, which then wins
//! (`a|b` cannot happen; `a|.b` is on `a`, `a.|b` is on `b`).
/// The byte offset a request about the name under the cursor should resolve,
/// given the caret's byte offset in `text`.
///
/// Moves one byte left when the caret is just past a name and not at the
/// start of another; every other caret is returned unchanged. A name is an
/// identifier, keyword, system task, macro or number written with
/// [`is_name_byte`] — or an escaped identifier, `\` up to the whitespace that
/// ends it, whose own characters can be anything.
pub fn symbol_offset(text: &str, caret: u32) -> u32 {
let bytes = text.as_bytes();
let at = caret as usize;
if at == 0 || at > bytes.len() || bytes.get(at).copied().is_some_and(is_name_byte) {
return caret;
}
let before = bytes[at - 1];
if is_name_byte(before) || ends_an_escaped_identifier(bytes, at) {
return caret - 1;
}
caret
}
/// Whether `byte` can be part of a simple identifier (IEEE 1800-2017 §5.6):
/// a letter, a digit, `_` or `$`. A system task's leading `$` and a macro
/// name after its backtick are covered by the same set.
fn is_name_byte(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$'
}
/// Whether the caret at `at` sits on the whitespace (or the end of the text)
/// that terminates an escaped identifier — a `\` followed by at least one
/// non-whitespace byte, all of it before the caret.
fn ends_an_escaped_identifier(bytes: &[u8], at: usize) -> bool {
if bytes.get(at).is_some_and(|b| !b.is_ascii_whitespace()) {
return false;
}
let start = bytes[..at].iter().rposition(u8::is_ascii_whitespace).map_or(0, |ws| ws + 1);
at - start >= 2 && bytes[start] == b'\\'
}
#[cfg(test)]
mod tests {
use super::symbol_offset;
/// The offset `symbol_offset` picks for the caret written as `|` in
/// `marked`, as the character it lands on (`None` past the end).
fn lands_on(marked: &str) -> Option<char> {
let caret = marked.find('|').expect("a caret") as u32;
let text = marked.replacen('|', "", 1);
let at = symbol_offset(&text, caret) as usize;
text[at..].chars().next()
}
#[test]
fn a_caret_just_past_a_name_is_on_its_last_letter() {
assert_eq!(lands_on("logic tx|,"), Some('x'));
assert_eq!(lands_on("assign y = tx|;"), Some('x'));
assert_eq!(lands_on("tx|"), Some('x'), "at the end of the text");
assert_eq!(lands_on("logic tx|\nwire w;"), Some('x'), "at the end of a line");
assert_eq!(lands_on("logic tx|\r\nwire w;"), Some('x'), "before a CRLF");
}
#[test]
fn a_caret_on_or_inside_a_name_is_left_alone() {
assert_eq!(lands_on("logic |tx;"), Some('t'), "at the start");
assert_eq!(lands_on("logic t|x;"), Some('x'), "in the middle");
}
#[test]
fn a_caret_touching_two_names_takes_the_one_that_starts_there() {
// VS Code's word at `a|.b` is `a`; at `a.|b` it is `b`.
assert_eq!(lands_on("u_a|.sig"), Some('a'), "before the dot: the instance");
assert_eq!(lands_on("u_a.|sig"), Some('s'), "after the dot: the member");
assert_eq!(lands_on(".clk|(clk_i)"), Some('k'), "a port name before its paren");
assert_eq!(lands_on(".clk(|clk_i)"), Some('c'), "the signal after the paren");
assert_eq!(lands_on("mem|[3]"), Some('m'), "a name before an index");
}
#[test]
fn a_caret_after_anything_but_a_name_is_left_alone() {
assert_eq!(lands_on("a = b;|"), None, "past a semicolon at the end");
assert_eq!(lands_on("a = b; |"), None, "past whitespace");
assert_eq!(lands_on("f(x)|;"), Some(';'), "past a paren");
assert_eq!(lands_on("|"), None, "an empty text");
assert_eq!(lands_on("|tx"), Some('t'), "the very start");
}
#[test]
fn system_tasks_macros_and_keywords_are_names_too() {
assert_eq!(lands_on("$display|("), Some('y'));
assert_eq!(lands_on("`WIDTH|-1"), Some('H'));
assert_eq!(lands_on("begin|\n"), Some('n'), "so a keyword pair highlights");
}
#[test]
fn an_escaped_identifier_ends_at_its_whitespace() {
// `\a+b ` is one name whose last byte is not an identifier byte.
assert_eq!(lands_on(r"assign \a+b+ |= 1;"), Some('='), "past the space: not on it");
assert_eq!(lands_on(r"assign \a+b+| = 1;"), Some('+'), "on the space that ends it");
assert_eq!(lands_on(r"\bus[0]|"), Some(']'), "at the end of the text");
assert_eq!(lands_on(r"x = a \| b;"), Some(' '), "a lone backslash is not a name");
}
#[test]
fn non_ascii_text_before_the_name_does_not_move_the_byte() {
// The caret arrives as a byte offset already converted from UTF-16;
// the rule reads bytes, and a multi-byte character is never a name.
assert_eq!(lands_on("// é\nlogic tx|;"), Some('x'));
assert_eq!(lands_on("é|tx"), Some('t'), "a name starting after a non-ASCII letter");
assert_eq!(lands_on("é|;"), Some(';'), "a non-ASCII letter is not a name");
}
}
+102 -20
View File
@@ -86,7 +86,7 @@ fn include_on_line(line: &str, base: u32) -> Option<Include> {
///
/// Rebuilt whole on every index rebuild, from the same source list — and
/// patched one file at a time when only one file's text moved
/// ([`IncludeGraph::update_file`]).
/// ([`IncludeGraph::update_held`]).
#[derive(Debug, Default, Clone)]
pub struct IncludeGraph {
/// The `+incdir+` directories of the configured filelist, in filelist
@@ -107,6 +107,11 @@ pub struct IncludeGraph {
/// a single file — which is what makes an incrementally widened graph
/// byte-identical to a rebuilt one (`docs/features/index-scope/README.md`).
raw: HashMap<PathBuf, Vec<PathBuf>>,
/// Every held file's `` `include`` lines as written, resolved or not — so
/// a file appearing or vanishing anywhere on disk can be answered by
/// re-resolving just the lines that could name it
/// ([`IncludeGraph::refresh_naming`]), without reading a file.
lines: HashMap<PathBuf, Vec<Include>>,
/// Every in-scope file, exactly as the index spells it.
known: HashSet<PathBuf>,
/// Lower-cased spelling → the one in-scope file that has it, or `None`
@@ -154,29 +159,81 @@ impl IncludeGraph {
graph
}
/// Re-scan one file's `` `include``s, the rest of the graph left standing.
/// Re-scan one file's `` `include``s, the rest of the graph left standing —
/// for a file whose text changed while the file set did not, a save of a
/// file the index already holds. The known-file and folded-spelling tables
/// are a function of the file set, and every other file's edges a function
/// of its own text and those tables, so only this file's edges are
/// re-scanned and re-spelled (`docs/features/localized-reindex/README.md`).
///
/// `known` is the index's file list as it stands *after* the update, which
/// is what the known-file and folded-spelling tables are: cheap to rebuild
/// from a list already in memory, and wrong to leave stale when a file has
/// come or gone.
///
/// One honest limit, and the reason the incremental path in `state.rs`
/// takes it only for a file that already existed: an edge of a *different*
/// file is not re-**resolved** against the disk. So a file appearing or
/// vanishing on disk does not change whether some other file's
/// `` `include "x.svh"`` finds anything until the next whole rebuild. Every
/// held edge *is* re-spelled against the new file list, because that half
/// costs no filesystem call — see [`IncludeGraph::respell`]. For the case
/// this is used in — one file's text changed, the file set did not — there
/// is nothing stale at all.
pub fn update_file(&mut self, path: &Path, text: &str, known: &[PathBuf]) {
self.relearn(known);
/// Until 2026-11-19 this was `update_file`, which also re-learned both
/// tables and re-spelled every edge — O(files) for an answer that cannot
/// move. Its one honest limit is unchanged: an edge of a *different* file
/// is not re-**resolved** against the disk, which is why the incremental
/// path takes only a file the index already holds.
pub fn update_held(&mut self, path: &Path, text: &str) {
self.rescan_edges(path, text);
self.respell();
self.respell_one(path);
}
/// [`IncludeGraph::update_file`] for a batch of files whose `` `include``
/// Re-resolve the `` `include`` lines of every held file that writes one
/// whose last component could be `path`'s name — the only lines a file
/// appearing, vanishing or moving at `path` can change the answer of,
/// whether or not `path` is in scope: an include is resolved against the
/// disk, not against the scope (`docs/features/localized-reindex`, QA F1).
///
/// The name is compared case-insensitively, so a case-insensitive disk is
/// covered, and a target with no last component (`..`) counts as naming
/// everything. Reads no file: the lines are held.
pub fn refresh_naming(&mut self, path: &Path) {
self.refresh_naming_all(std::slice::from_ref(&path.to_path_buf()));
}
/// [`IncludeGraph::refresh_naming`] for every path of one watcher event
/// at once: one pass over the held lines for the whole set of names, so a
/// burst of ten thousand generated files costs one pass, not ten thousand
/// (QA R2-1). A line is re-resolved exactly when it would have been for
/// one of the paths alone, and re-resolving a file twice gives what once
/// does, so the batch is the same answer.
pub fn refresh_naming_all(&mut self, paths: &[PathBuf]) {
let folded = |name: &std::ffi::OsStr| name.to_string_lossy().to_lowercase();
let names: HashSet<String> =
paths.iter().filter_map(|path| path.file_name()).map(folded).collect();
if names.is_empty() {
return;
}
let could_name = |include: &Include| {
Path::new(&include.target).file_name().is_none_or(|last| names.contains(&folded(last)))
};
let mut naming: Vec<PathBuf> = self
.lines
.iter()
.filter(|(_, lines)| lines.iter().any(could_name))
.map(|(from, _)| from.clone())
.collect();
naming.sort();
for from in naming {
let lines = self.lines.get(&from).cloned().unwrap_or_default();
self.rescan_found(&from, &lines);
self.respell_one(&from);
}
}
/// Re-spell one file's edges from its raw ones.
fn respell_one(&mut self, path: &Path) {
match self.raw.get(path) {
Some(targets) => {
let spelled =
targets.iter().map(|to| self.as_the_index_spells_it(to.clone())).collect();
self.edges.insert(path.to_path_buf(), spelled);
}
None => {
self.edges.remove(path);
}
}
}
/// [`IncludeGraph::update_held`] for a batch of files whose `` `include``
/// lines have already been read, with the `+incdir+`s the scope resolves
/// to right now — the form a scan publishing what it has indexed so far
/// uses. The lines come from the step that indexed each file, for the
@@ -203,11 +260,29 @@ impl IncludeGraph {
self.respell();
}
/// Take `path` into the file set: known, folded, and every held edge
/// re-spelled against the new set — what [`IncludeGraph::from_includes`]
/// over the old set and `path` would have learned. Its own edges are
/// [`IncludeGraph::update_held`]'s business.
pub fn add_known(&mut self, path: &Path) {
if !self.known.insert(path.to_path_buf()) {
return;
}
if let Some(key) = path.to_str().map(str::to_lowercase) {
self.folded
.entry(key)
.and_modify(|found| *found = None)
.or_insert_with(|| Some(path.to_path_buf()));
}
self.respell();
}
/// Drop one file from the graph: its own edges, and its place among the
/// known files.
pub fn remove_file(&mut self, path: &Path, known: &[PathBuf]) {
self.relearn(known);
self.raw.remove(path);
self.lines.remove(path);
self.respell();
}
@@ -223,6 +298,10 @@ impl IncludeGraph {
fn rescan_found(&mut self, path: &Path, found: &[Include]) {
let targets: Vec<PathBuf> =
found.iter().filter_map(|include| self.found(Some(path), include)).collect();
match found.is_empty() {
true => self.lines.remove(path),
false => self.lines.insert(path.to_path_buf(), found.to_vec()),
};
match targets.is_empty() {
true => self.raw.remove(path),
false => self.raw.insert(path.to_path_buf(), targets),
@@ -425,6 +504,9 @@ impl IncludeGraph {
let mut raw: Vec<(&PathBuf, &Vec<PathBuf>)> = self.raw.iter().collect();
raw.sort();
out.push_str(&format!("raw {raw:?}\n"));
let mut lines: Vec<(&PathBuf, &Vec<Include>)> = self.lines.iter().collect();
lines.sort_by_key(|(path, _)| *path);
out.push_str(&format!("lines {lines:?}\n"));
out
}
}
+86 -1
View File
@@ -304,7 +304,17 @@ fn configured(
}
}
options.overlay(&client.lint_options);
let width = file.line_length.or(client.line_length).unwrap_or(DEFAULT_LINE_LENGTH);
// The formatter's width ladder, so a line lucisv wrote is never a line
// lucisv calls too long: an explicit width (`lucisv.toml`, then the
// editor), else the chosen style's width (`lucisv.toml`'s `style`, then
// `lucisv.format.style`), else the default. `auto` names no preset and so
// no width — it falls through to the default, as it does in the
// formatter (`docs/features/format-styles/README.md`, Handshakes).
let styled = file.format_style.or(client.style).and_then(vlog_formatter::style::preset);
let width = file
.line_length
.or(client.line_length)
.unwrap_or_else(|| styled.map_or(DEFAULT_LINE_LENGTH, |style| style.line_length));
(options, width, file, problems)
}
@@ -731,6 +741,81 @@ mod tests {
assert_eq!(oracle.package_exports("nowhere_pkg"), Exports::Unknown);
}
/// Whether the server flags `line-length` on a line of `columns`
/// characters, in a scratch tree governed by `toml` (none for `None`),
/// with the editor's `lucisv.format.style` set to `editor_style`.
fn flags_a_line_of(
columns: usize,
toml: Option<&str>,
editor_style: Option<&'static str>,
) -> bool {
let dir = std::env::temp_dir().join(format!(
"lucisv_lint_width_{}_{columns}_{}",
std::process::id(),
toml.map_or(0, str::len) + editor_style.map_or(0, str::len) * 1000
));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("scratch dir");
if let Some(toml) = toml {
std::fs::write(dir.join("lucisv.toml"), toml).expect("config");
}
let text = format!("module m;\n // {}\nendmodule\n", "x".repeat(columns - 5));
let path = dir.join("m.sv");
std::fs::write(&path, &text).expect("source");
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings { style: editor_style, ..ClientSettings::default() });
let uri = crate::uri::path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), text);
let doc = ws.document(&uri).expect("open");
let run = LintRun::for_document(&ws, doc);
let flagged = diagnostics_in(doc, &run)
.iter()
.any(|d| d.code == Some(NumberOrString::String("line-length".into())));
let _ = std::fs::remove_dir_all(&dir);
flagged
}
/// The width `lucisv check` holds the same file to: the CLI's own ladder,
/// an explicit width over the named style's over the default
/// (`lucisv`'s `Options::config_with`), with the editor's style standing
/// in for `--style`.
fn check_width(explicit: Option<usize>, style: Option<&str>) -> usize {
let config = style.and_then(vlog_formatter::Config::named).unwrap_or_default();
explicit.unwrap_or(config.max_width)
}
#[test]
fn line_length_holds_a_buffer_to_the_width_the_formatter_and_check_use() {
// One rung each, from the top: an explicit width beats a style; a
// project's style; the editor's style; the default; and `auto`, which
// names no width and so takes the default.
let rungs: [(&str, Option<&str>, Option<&'static str>, usize); 5] = [
(
"explicit",
Some("line-length = 120\n[format]\nstyle = \"ansi\"\n"),
None,
check_width(Some(120), Some("ansi")),
),
(
"project style",
Some("[format]\nstyle = \"ansi\"\n"),
None,
check_width(None, Some("ansi")),
),
("editor style", None, Some("microsoft"), check_width(None, Some("microsoft"))),
("default", None, None, check_width(None, None)),
("auto", Some("[format]\nstyle = \"auto\"\n"), None, check_width(None, Some("auto"))),
];
assert_eq!(rungs.map(|r| r.3), [120, 80, 120, 100, 100], "premise: the widths check uses");
for (rung, toml, editor, width) in rungs {
assert!(
!flags_a_line_of(width, toml, editor),
"{rung}: a line of exactly {width} is fine"
);
assert!(flags_a_line_of(width + 1, toml, editor), "{rung}: one column more is flagged");
}
}
#[test]
fn a_tab_becomes_one_warning_carrying_its_rule_name() {
let (ws, uri) = doc_of("module m;\n\twire a;\nendmodule\n");
+1
View File
@@ -8,6 +8,7 @@
mod auto_style;
mod candidates;
mod caret;
mod code_action;
mod completion;
mod convert;
+10 -23
View File
@@ -4,20 +4,20 @@
//! forwarder here moves them onto a queue of our own so that "everything the
//! client has already sent" is a question with an answer. The rest of the
//! file reads a burst without handling anything in it: which requests it
//! cancels, which files it opens, and — for a `didOpen` — whether the index
//! scope grew, stayed, or has to be rebuilt. The loop in `mod.rs` and the
//! cancels and — for a `didOpen` — whether the index scope grew, stayed, or
//! has to be rebuilt. (Which files a burst *opens* is not read here any more:
//! a `didOpen` changes a scan's order when it is applied, never because a
//! batch carries it — `docs/features/scan-ordering/README.md`.) The loop in `mod.rs` and the
//! mid-scan drain in `index.rs` both read bursts through here, which is why
//! this is its own file rather than part of either.
use std::collections::HashSet;
use lsp_server::{Connection, Message, RequestId, Response};
use lsp_types::notification::{Cancel, DidOpenTextDocument, Notification as _};
use lsp_types::notification::{Cancel, Notification as _};
use lsp_types::request::{Request as _, Shutdown};
use lsp_types::{CancelParams, NumberOrString};
use super::dispatch::document_uri;
/// Whether this message is the `shutdown` request. `lsp-server` keeps its own
/// answer to that question private, so it is asked here by method name — the
/// same name `handle_shutdown` matches on.
@@ -167,22 +167,9 @@ pub(super) fn widen_of(before: &[std::path::PathBuf], after: &[std::path::PathBu
Widen::Added(after.iter().filter(|dir| !before.contains(dir)).cloned().collect())
}
/// The files a burst opened, in the order the client opened them.
///
/// Read off the raw messages rather than off the workspace afterwards,
/// because the workspace holds its buffers in a `HashMap` and "which file did
/// the user just open" is a question about order.
pub(super) fn opened_in(batch: &[Message]) -> Vec<std::path::PathBuf> {
batch
.iter()
.filter_map(|message| match message {
Message::Notification(notification)
if notification.method == DidOpenTextDocument::METHOD =>
{
document_uri(&notification.params)
}
_ => None,
})
.filter_map(|uri| crate::uri::uri_to_path(&uri))
.collect()
/// Whether a message changes what the server holds — any notification but a
/// `$/cancelRequest`. These are the messages whose order is the order the
/// client sent them in (`Server::must_hold`).
pub(super) fn changes_state(message: &Message) -> bool {
matches!(message, Message::Notification(n) if n.method != Cancel::METHOD)
}
@@ -92,7 +92,7 @@ impl Server {
/// Everything the server has to say about a buffer — the one computation
/// both diagnostic models answer from. A buffer that is not open has
/// nothing said about it.
fn diagnostics_of(&self, uri: &Uri) -> Vec<lsp_types::Diagnostic> {
pub(super) fn diagnostics_of(&self, uri: &Uri) -> Vec<lsp_types::Diagnostic> {
let Some(doc) = self.workspace.document(uri) else { return Vec::new() };
// The lint pass is given the project: the rule selection
// `lucisv.lint.*` and the buffer's `[lint]` table resolved to, and the
+24 -12
View File
@@ -44,9 +44,10 @@ use serde_json::Value;
use super::client::ms;
use super::Server;
use crate::{
code_action, completion, design_hierarchy, extract, file_ops, folding, format, hierarchy,
hover, imports, includes, inlay, inline, inline_module, lens, linked, lint, lint_trace, nav,
pairs, ports, rename, selection, signature, symbols, tokens, type_def, type_hierarchy,
caret, code_action, completion, design_hierarchy, extract, file_ops, folding, format,
hierarchy, hover, imports, includes, inlay, inline, inline_module, lens, linked, lint,
lint_trace, nav, pairs, ports, rename, selection, signature, symbols, tokens, type_def,
type_hierarchy,
};
/// The requests whose empty answer may mean "this scan has not reached the
@@ -197,7 +198,7 @@ impl Server {
HoverRequest::METHOD => decode(request).and_then(|p: HoverParams| {
let at = p.text_document_position_params;
let (uri, position) = (at.text_document.uri, at.position);
self.offset(&uri, position)
self.symbol_offset(&uri, position)
.map(|offset| hover::hover(&self.workspace, &uri, offset))
.map_or(Ok(Value::Null), to_value)
}),
@@ -205,7 +206,7 @@ impl Server {
let at = p.text_document_position_params;
let (uri, position) = (at.text_document.uri, at.position);
let locations = self
.offset(&uri, position)
.symbol_offset(&uri, position)
.map(|offset| nav::definition(&self.workspace, &uri, offset))
.unwrap_or_default();
to_value(GotoDefinitionResponse::Array(locations))
@@ -221,7 +222,7 @@ impl Server {
let at = p.text_document_position_params;
let (uri, position) = (at.text_document.uri, at.position);
let locations = self
.offset(&uri, position)
.symbol_offset(&uri, position)
.map(|offset| type_def::type_definition(&self.workspace, &uri, offset))
.unwrap_or_default();
to_value(GotoTypeDefinitionResponse::Array(locations))
@@ -255,7 +256,7 @@ impl Server {
let at = p.text_document_position;
let (uri, position) = (at.text_document.uri, at.position);
let locations = self
.offset(&uri, position)
.symbol_offset(&uri, position)
.map(|offset| nav::references(&self.workspace, &uri, offset, include))
.unwrap_or_default();
to_value(locations)
@@ -271,7 +272,7 @@ impl Server {
decode(request).and_then(|p: DocumentHighlightParams| {
let at = p.text_document_position_params;
let (uri, position) = (at.text_document.uri, at.position);
let found = self.offset(&uri, position).and_then(|offset| {
let found = self.symbol_offset(&uri, position).and_then(|offset| {
let doc = self.workspace.document(&uri)?;
pairs::highlights(doc, offset)
.or_else(|| nav::document_highlights(doc, offset))
@@ -444,7 +445,7 @@ impl Server {
PrepareRenameRequest::METHOD => {
decode(request).and_then(|at: TextDocumentPositionParams| {
let (uri, position) = (at.text_document.uri, at.position);
let Some(offset) = self.offset(&uri, position) else {
let Some(offset) = self.symbol_offset(&uri, position) else {
return Ok(Value::Null);
};
match rename::prepare(&self.workspace, &uri, offset) {
@@ -457,7 +458,7 @@ impl Server {
let new_name = p.new_name;
let at = p.text_document_position;
let (uri, position) = (at.text_document.uri, at.position);
let Some(offset) = self.offset(&uri, position) else {
let Some(offset) = self.symbol_offset(&uri, position) else {
return Ok(Value::Null);
};
// One `timing: rename trace …` line behind `--verbose`, and
@@ -588,7 +589,7 @@ impl Server {
decode(request).and_then(|p: CallHierarchyPrepareParams| {
let at = p.text_document_position_params;
let (uri, position) = (at.text_document.uri, at.position);
self.offset(&uri, position)
self.symbol_offset(&uri, position)
.and_then(|offset| hierarchy::prepare(&self.workspace, &uri, offset))
.map_or(Ok(Value::Null), to_value)
})
@@ -611,7 +612,7 @@ impl Server {
decode(request).and_then(|p: TypeHierarchyPrepareParams| {
let at = p.text_document_position_params;
let (uri, position) = (at.text_document.uri, at.position);
self.offset(&uri, position)
self.symbol_offset(&uri, position)
.and_then(|offset| type_hierarchy::prepare(&self.workspace, &uri, offset))
.map_or(Ok(Value::Null), to_value)
})
@@ -660,6 +661,17 @@ impl Server {
fn offset(&self, uri: &Uri, position: Position) -> Option<u32> {
self.workspace.document(uri).map(|doc| doc.positions().offset(position))
}
/// [`Server::offset`] for a request about the name under the cursor: a
/// caret just past a name is on that name, as VS Code's own word rule
/// says ([`caret::symbol_offset`]). Requests with a boundary rule of
/// their own — completion, signature help, linked editing, on-type
/// formatting — keep the caret as sent; the table is in
/// `docs/features/scan-ordering/README.md`.
fn symbol_offset(&self, uri: &Uri, position: Position) -> Option<u32> {
let doc = self.workspace.document(uri)?;
Some(caret::symbol_offset(&doc.text, doc.positions().offset(position)))
}
}
/// Why a request could not be answered, in the protocol's own terms.
+117 -24
View File
@@ -14,13 +14,24 @@ use std::path::Path;
use lsp_types::ProgressToken;
use super::batch::opened_in;
use super::client::{notify_on, plural};
use super::progress::IndexWatch;
use super::{Server, INTERLEAVE_ABOVE};
use crate::state::{IndexEvent, Scan, Workspace};
use crate::state::{IndexEvent, OneFile, Scan, Watched, Workspace};
use crate::{design_hierarchy, file_ops};
/// A watcher event naming more than one path per `BURST_DIVISOR` files the
/// index holds takes the whole rescan instead of being sorted path by path.
///
/// Measured on the full OpenTitan `hw` tree (4 058 files, release, one
/// notification of generated files under a gitignored directory, medians of
/// 3): sorting costs ~0.10 ms a path (1 000 paths 0.10 s, 5 000 paths 0.50 s),
/// a cached whole rescan ~0.16 ms an indexed file (0.63–0.65 s) — so the two
/// cross near 1.6 paths per file, and both scale with the tree. Dividing by 2
/// keeps the sorted path at or under ~0.3× the rescan it saves on any tree
/// (QA R2-1: never slower than 7408fac's one rescan per notification).
const BURST_DIVISOR: usize = 2;
impl Server {
/// Rescan the workspace and republish every open buffer against the new
/// index. Every caller changed what the index should contain — a save, a
@@ -59,15 +70,22 @@ impl Server {
/// that file is one the index already holds. Reports whether it ran; a
/// `false` means the caller owes a whole rebuild.
///
/// Everything a rebuild does *after* the scan happens here too, for the
/// same reasons: the code-lens refresh (the file that moved may have
/// changed an instantiation count in any buffer), the diagnostics
/// generation bump (every open buffer's diagnostics are computed against
/// the index), and a republish of every open buffer. The republish stays
/// wholesale rather than narrowing to the buffers that could have moved:
/// a lint reads the index, so any buffer's diagnostics may have changed,
/// and narrowing it correctly needs a dependency graph this server does not
/// have. Worth doing later; wrong to guess at now.
/// When the index moved, everything a rebuild does *after* the scan
/// happens here too, for the same reasons: the code-lens refresh (the file
/// that moved may have changed an instantiation count in any buffer), the
/// hierarchy view's invalidation, the diagnostics generation bump (every
/// open buffer's diagnostics are computed against the index), and a
/// republish of every open buffer. The republish stays wholesale: a lint
/// reads the index, so any buffer's diagnostics may have changed, and it
/// costs ~0.3 ms a buffer on OpenTitan — narrowing it would buy nothing
/// measurable for the one place a stale squiggle could hide
/// (`docs/features/localized-reindex/README.md`).
///
/// When the file's record did **not** move — the watcher's echo of the
/// save that just ran, a save of an unchanged buffer — every answer read
/// off the index alone is the answer it already was, so no lens refresh
/// and no hierarchy invalidation is sent. The republish still is: see
/// below.
///
/// Three things a whole rebuild does that this deliberately does not:
///
@@ -93,19 +111,84 @@ impl Server {
return true;
}
let started = self.timer();
if !self.workspace.update_one(path) {
let outcome = self.workspace.update_one_file(path);
if outcome == OneFile::NotHeld {
// No line: nothing was reindexed, and the caller is about to
// rebuild the whole index — which times itself.
return false;
}
self.refresh_code_lenses();
self.hierarchy_index_changed();
// Lenses and the hierarchy view are read off the index alone, so an
// unchanged record owes them nothing. Diagnostics are not: a lint
// also reads the buffer's `lucisv.toml` and waiver files from disk,
// which no notification reports, and a save has always been when an
// edit to them takes effect (QA F2). So every save republishes.
if outcome == OneFile::Changed {
self.refresh_code_lenses();
self.hierarchy_index_changed();
}
self.republish_all();
// The unchanged case says so inside the parentheses, so every reader
// of the old `reindex_one(<path>) took <ms>` shape still matches.
let unchanged = if outcome == OneFile::Unchanged { ", unchanged" } else { "" };
self.timed(started, |took| {
format!("reindex_one({}{unchanged}) took {took}", path.display())
});
true
}
/// The rescan a watcher event owes, decided file by file
/// ([`Workspace::watched`]): a file the scope provably cannot take — a
/// generated file under a gitignored directory, one outside the folder
/// scope or the filelist — owes nothing; a held file, by whatever
/// spelling the client used, is the one-file update; anything the scope
/// may take and the index does not hold is a whole rebuild, and so are
/// two or more held files, exactly as a checkout always was.
///
/// `named` is every path the event named, any extension: the include
/// lines that could name one are re-resolved first, unless the event takes
/// the whole rescan, which re-resolves all of them (QA F1). An event that owes the index
/// nothing still republishes every open buffer, for the reason
/// [`Server::reindex_one`] gives.
pub(super) fn reindex_watched(
&mut self,
paths: &[std::path::PathBuf],
named: &[std::path::PathBuf],
) {
// A burst — a branch switch, a generator run — is sorted file by file
// only while that is cheaper than the rescan it replaces.
if paths.len().saturating_mul(BURST_DIVISOR) > self.workspace.index().files().len() {
return self.reindex();
}
self.workspace.refresh_includes_naming(named);
let mut held: Vec<std::path::PathBuf> = Vec::new();
for path in paths {
match self.workspace.watched(path) {
Watched::Held(spelled) => held.push(spelled),
Watched::Outside => {}
Watched::Unknown => return self.reindex(),
}
}
held.sort();
held.dedup();
match held.as_slice() {
[] => self.republish_all(),
[one] => {
if !self.reindex_one(one) {
self.reindex();
}
}
_ => self.reindex(),
}
}
/// Every open buffer's diagnostics said again, under a new generation so
/// a pulling client asks again too — what a save owes even when the index
/// did not move. ~0.3 ms a buffer on OpenTitan.
pub(super) fn republish_all(&mut self) {
self.generation += 1;
for uri in self.workspace.open_uris() {
self.publish(&uri);
}
self.timed(started, |took| format!("reindex_one({}) took {took}", path.display()));
true
}
/// [`Server::reindex`] for a `didOpen` that only ever **added** folders to
@@ -221,6 +304,7 @@ impl Server {
self.scanning = false;
// A neighbourhood can only be owed by a scan, and there is none now.
self.head_owed = false;
self.opened_mid_scan = false;
self.answer_what_was_deferred();
warnings
}
@@ -393,6 +477,8 @@ impl Server {
while let Ok(message) = self.queue.try_recv() {
arrived.push(message);
}
#[cfg(test)]
super::probe::at_interleave_point(owed, &mut arrived);
// A quiet scan pays nothing at all, and that is a promise: the cadence
// is asked only when there is something for a publish to be *for*.
if !owed && arrived.is_empty() && self.deferred.is_empty() {
@@ -409,15 +495,22 @@ impl Server {
if batch.is_empty() {
return false;
}
// A `didOpen` in this burst names a folder the work list has not been
// ordered around yet, so the requests behind it in the burst are owed
// that ordering before they are answered — which is exactly what the
// widen this `didOpen` used to trigger made them wait for. The flag is
// set *before* the batch is applied, so `must_wait` holds them; it is
// recomputed below once the new head segment is known.
let opened = !opened_in(&batch).is_empty();
self.head_owed |= opened;
// A `didOpen` this burst *applies* names a folder the work list has
// not been ordered around yet, so the requests behind it are owed that
// ordering before they are answered — which is exactly what the widen
// this `didOpen` used to trigger made them wait for. The `didOpen` arm
// sets `head_owed` as it applies one, so `must_wait` holds what is
// behind it; it is recomputed below once the new head is known.
//
// **Applied, not merely present.** Before 2026-11-19 the flag was read
// off the batch before it was handled, so a `didOpen` the batch held
// unapplied behind a request re-held that request, and the same batch
// came back at every file — a five-minute startup scan on OpenTitan
// (`docs/features/scan-ordering/README.md`, C). Only a message that
// has been applied changes the scan's state, and each is applied once.
self.opened_mid_scan = false;
self.stopped = !matches!(self.process_batch(batch), Ok(false));
let opened = std::mem::take(&mut self.opened_mid_scan);
// The files the user has just opened, and the folders around them, are
// what they are looking at, so they are indexed next rather than when
// the alphabet reaches them — the open-first rule, for buffers opened
+117 -31
View File
@@ -46,7 +46,7 @@ use lsp_types::{SemanticToken, Uri};
use crate::state::Workspace;
use batch::{burst, cancelled_id, cancelled_in, cancelled_response};
use batch::{burst, cancelled_id, cancelled_in, cancelled_response, changes_state};
use dispatch::names_nowhere;
mod batch;
@@ -57,6 +57,8 @@ mod formatting;
mod index;
mod large_file;
mod notification;
#[cfg(test)]
mod probe;
mod progress;
mod semantic_tokens;
mod startup;
@@ -222,6 +224,12 @@ pub struct Server {
/// (`docs/features/perf5-p4/README.md`). False whenever no scan is
/// running, and false during a scan with no neighbourhood to wait for.
head_owed: bool,
/// Whether a `didOpen` was **applied** while the scan now running had
/// messages to answer — set where the `didOpen` is applied, and read by
/// that scan's drain once the batch carrying it has been handled. Never
/// read off a batch, which may hold the `didOpen` unapplied behind a
/// request (`docs/features/scan-ordering/README.md`, C).
opened_mid_scan: bool,
/// A rescan asked for while a scan was running. Coalesced: any number of
/// requests is one more scan when this one ends, whatever asked for them.
rescan_wanted: bool,
@@ -239,6 +247,12 @@ pub struct Server {
/// [`Server::must_wait`] — this is the order contract, not a queue of its
/// own.
held: Vec<Message>,
/// How many notifications older than the message being handled are still
/// unapplied in the bursts it is nested inside — the tail of a burst
/// whose message started a scan, while that scan answers newer ones. One
/// of the two places an older notification can wait; `held` is the other
/// ([`Server::must_hold`]). Cancels are not counted: they change nothing.
behind: usize,
/// Navigation requests a scan answered **empty** while it was still
/// growing the index, to be asked again at its next publish.
///
@@ -398,52 +412,42 @@ impl Server {
// The `$/cancelRequest`s this burst has already carried, kept only
// long enough to put them back if a request behind them has to wait.
let mut consumed_cancels: Vec<Message> = Vec::new();
// The bursts this one is nested inside, and the notifications of them
// still unapplied; restored on the way out (an `Err` is a client that
// has gone, and nothing reads this after it).
let outer = self.behind;
let mut unapplied = batch.iter().filter(|m| changes_state(m)).count();
let mut messages = batch.into_iter();
while let Some(message) = messages.next() {
// A request that must wait takes everything behind it with it, or
// What is unapplied *older* than this message is only ever in the
// bursts around this one — the rest of this burst is newer.
self.behind = outer;
// A message that must wait takes everything behind it with it, or
// the burst's arrival order would not survive the wait —
// `shutdown` included, because a request sent before a shutdown
// is a request the client is still owed an answer to.
if self.must_wait() && matches!(message, Message::Request(_)) {
if self.must_hold(&message) {
self.cancel_deferred(&message)?;
self.say_held(&message);
// The cancels this burst carried were consumed on the way
// here, and `cancelled_in` runs again over the held batch — so
// they go back in front of what they cancel rather than being
// lost. A cancel naming nothing in the held batch is dropped
// there exactly as it was dropped here.
let mut rest: Vec<Message> = std::mem::take(&mut consumed_cancels);
rest.push(message);
rest.extend(messages);
rest.extend(self.held.split_off(already_waiting));
self.held.extend(rest);
self.hold(rest, already_waiting);
return Ok(false);
}
unapplied -= usize::from(changes_state(&message));
// Whatever this message starts — a scan, whose drain answers the
// client's newer messages — runs with the rest of this burst's
// notifications still unapplied, and newer ones must not overtake
// them.
self.behind = outer + unapplied;
match message {
Message::Request(request) => {
if self.connection.handle_shutdown(&request)? {
self.behind = outer;
return Ok(true);
}
// Removed as it is used: a second cancel for the same id
// then finds nothing, and the set cannot outlive the burst.
let response = if cancelled.remove(&request.id) {
cancelled_response(request.id)
} else {
// A navigation request whose answer would be `[]` only
// because the scan has not reached its target yet is
// asked again at the next publish rather than answered
// with nowhere ([`Server::deferred`]).
let again = self.ask_again_if_empty(&request);
let response = self.request(request);
match again.filter(|_| names_nowhere(&response)) {
Some(request) => {
self.say_deferred(&request);
self.deferred.push(Message::Request(request));
continue;
}
None => response,
}
};
self.connection.sender.send(Message::Response(response))?;
self.answer_from_batch(request, &mut cancelled)?;
}
// The cancels themselves are consumed here — `notification`
// has nothing to do with one, and everything it could do has
@@ -463,9 +467,53 @@ impl Server {
Message::Response(response) => self.response(response),
}
}
self.behind = outer;
Ok(false)
}
/// Answer one request a burst carried: `RequestCancelled` when the burst
/// also carried its cancel, set aside for the next publish when it is a
/// navigation request the scan has not reached the answer to yet, and
/// computed otherwise.
fn answer_from_batch(
&mut self,
request: lsp_server::Request,
cancelled: &mut HashSet<RequestId>,
) -> Result<(), Box<dyn Error + Sync + Send>> {
// Removed as it is used: a second cancel for the same id then finds
// nothing, and the set cannot outlive the burst.
let response = if cancelled.remove(&request.id) {
cancelled_response(request.id)
} else {
// A navigation request whose answer would be `[]` only because
// the scan has not reached its target yet is asked again at the
// next publish rather than answered with nowhere
// ([`Server::deferred`]).
let again = self.ask_again_if_empty(&request);
let response = self.request(request);
if let Some(request) = again.filter(|_| names_nowhere(&response)) {
self.say_deferred(&request);
self.deferred.push(Message::Request(request));
return Ok(());
}
response
};
self.connection.sender.send(Message::Response(response))?;
Ok(())
}
/// Put `rest` — the cancels the burst already carried, the message that
/// must wait, and the rest of its burst, in that order — into `held`: in
/// front of whatever a scan this burst started has held since
/// `already_waiting`, behind everything older. The cancels go back in
/// front of what they cancel because `cancelled_in` runs again over the
/// held batch; one naming nothing in it is dropped there, as it would
/// have been here.
fn hold(&mut self, mut rest: Vec<Message>, already_waiting: usize) {
rest.extend(self.held.split_off(already_waiting));
self.held.extend(rest);
}
/// Honour a `$/cancelRequest` naming a request in [`Server::deferred`]:
/// take it out and answer it cancelled. A cancel naming anything else is
/// left to the batch's own rule.
@@ -528,6 +576,44 @@ impl Server {
|| self.head_owed
}
/// Whether `message`, reaching `process_batch` right now, must be held
/// instead of handled.
///
/// **No notification overtakes an older notification.** Only a
/// notification changes what the server holds — a buffer's text, which
/// buffers are open, the settings, the folders, what is on disk — so the
/// order those are applied in is the order they were sent in, and nothing
/// a request is later answered against can be a state the client never
/// had. A notification waits while an older one is unapplied: in `held`,
/// or in the tail of a burst whose message started the scan now draining
/// ([`Server::behind`]). Before 2026-11-19 a `didChange` drained mid-scan
/// was applied ahead of an older `didChange` still waiting, and an
/// incremental edit landed on the wrong text
/// (`docs/features/scan-ordering/README.md`, B).
///
/// **Not "no notification overtakes a request".** A request held by the
/// contract above is answered against whatever was applied by the time
/// it is replayed — as every request answered late always was — and a
/// notification behind it with nothing older unapplied is applied at
/// once. Holding it too would cost the startup its first `didOpen`
/// (QA-3) and buy no state the client could see.
///
/// A **cancel** changes nothing the server holds, so it never makes a
/// notification wait; it waits itself whenever anything is held, so that
/// one naming a held request is replayed beside it and honoured. A
/// **response** is never held: it answers a request the server made, and
/// no ordering promise ties it to the editor's stream
/// (`take_the_answer_out_of_held` in `startup.rs` makes the same
/// argument).
fn must_hold(&self, message: &Message) -> bool {
match message {
Message::Request(_) => self.must_wait(),
Message::Notification(_) if !changes_state(message) => !self.held.is_empty(),
Message::Notification(_) => self.behind > 0 || self.held.iter().any(changes_state),
Message::Response(_) => false,
}
}
/// Whether a scan is running or already owed — the two states in which a
/// rescan trigger records that one more scan is wanted instead of running
/// one itself.
@@ -25,6 +25,7 @@ use serde::de::DeserializeOwned;
use super::batch::{widen_of, Widen};
use super::client::ms;
use super::Server;
use crate::uri::uri_to_path;
use crate::{file_ops, lint, settings, sync, watch};
impl Server {
@@ -95,6 +96,14 @@ impl Server {
// rungs, which an open buffer cannot widen.
let before = self.workspace.scope_dirs();
self.set_document(uri.clone(), p.text_document.text);
// Mid-scan, the work list is re-ordered round this buffer
// once the batch carrying it is handled, and what is behind
// it in that batch waits for the new order
// (`Server::answer_what_is_waiting`).
if self.scanning {
self.head_owed = true;
self.opened_mid_scan = true;
}
match widen_of(&before, &self.workspace.scope_dirs()) {
Widen::Nothing => self.publish(&uri),
Widen::Added(dirs) => self.reindex_widened(dirs),
@@ -136,8 +145,18 @@ impl Server {
}
DidSaveTextDocument::METHOD => {
if let Ok(p) = extract::<DidSaveTextDocumentParams>(notification) {
// A save carrying the text the buffer already holds — the
// normal case, since every change was flushed above — has
// nothing to re-analyze. One carrying different text is a
// change the server missed: analyzed and published here,
// so the buffer's own answer is current whatever the
// reindex below finds moved.
if let Some(text) = p.text {
self.set_document(p.text_document.uri.clone(), text);
let uri = p.text_document.uri.clone();
if self.workspace.document(&uri).is_none_or(|doc| doc.text != text) {
self.set_document(uri.clone(), text);
self.publish(&uri);
}
}
// A save is one of the things that rebuild the index; the
// others are a change to `lucisv.exclude`/`lucisv.filelist`
@@ -160,15 +179,28 @@ impl Server {
// the params carry a list, and a checkout fills it.
DidChangeWatchedFiles::METHOD => {
if let Ok(p) = extract::<DidChangeWatchedFilesParams>(notification) {
// Whatever else the event owes, every path it names may
// be what an `include` line was looking for — in scope or
// not, of a source extension or not (QA F1). A rescan
// re-resolves every line anyway, so only the paths that
// do not take one are refreshed here.
let named: Vec<std::path::PathBuf> =
p.changes.iter().filter_map(|change| uri_to_path(&change.uri)).collect();
let filelist = self.workspace.filelist_path();
if watch::touches_scope(&p.changes, filelist.as_deref()) {
// One file named is the incremental case; a checkout
// filling the list, or the filelist itself moving, is
// the whole rebuild.
let one = watch::one_scope_file(&p.changes, filelist.as_deref());
if !one.is_some_and(|path| self.reindex_one(path.as_path())) {
self.reindex();
if watch::names_a_config(&p.changes) {
// A `lucisv.toml` moves excludes, the filelist and
// the lint configuration at once — for the client
// that forwards it (ours registers sources only).
self.reindex();
} else if watch::touches_scope(&p.changes, filelist.as_deref()) {
// The filelist itself moving is the whole rebuild;
// anything else is sorted file by file.
match watch::scope_files(&p.changes, filelist.as_deref()) {
Some(paths) => self.reindex_watched(&paths, &named),
None => self.reindex(),
}
} else {
self.workspace.refresh_includes_naming(&named);
}
}
}
+79
View File
@@ -0,0 +1,79 @@
//! A test's hand on the mid-scan drain: what the client "sends" at each
//! interleave point, and how often a scan handed back what it was holding.
//!
//! Test-only. The real transport cannot be timed against a scan's files —
//! the forwarder thread delivers whenever it likes — so a test that needs a
//! burst to land *at the third file* scripts it here, and the drain appends it
//! to what `try_recv` found, exactly where a real arrival would be. Thread
//! local because every test drives its server on its own thread.
use std::cell::RefCell;
use std::collections::VecDeque;
use lsp_server::Message;
#[derive(Default)]
struct Probe {
/// Bursts to deliver, one per interleave point, oldest first.
arrivals: VecDeque<Vec<Message>>,
/// Interleave points reached since the last [`take_counts`].
points: usize,
/// How many of those handed messages the scan had been holding back to
/// `process_batch` — what loops when a held batch is re-held at every file.
handed_back: usize,
/// How many scripted bursts a scan received.
delivered: usize,
}
/// What [`take_counts`] reports.
#[derive(Debug, Clone, Copy)]
pub(super) struct Counts {
/// Interleave points reached.
pub(super) points: usize,
/// Held batches handed back to `process_batch`.
pub(super) handed_back: usize,
/// Scripted bursts delivered mid-scan.
pub(super) delivered: usize,
}
thread_local! {
static PROBE: RefCell<Probe> = RefCell::default();
}
/// Script `bursts` to arrive at the next interleave points, one each, behind
/// anything already scripted.
pub(super) fn script(bursts: impl IntoIterator<Item = Vec<Message>>) {
PROBE.with(|probe| probe.borrow_mut().arrivals.extend(bursts));
}
/// What is still scripted and has not arrived — the bursts a scan ended
/// before reaching, which the test then delivers as `run` would.
pub(super) fn unarrived() -> Vec<Vec<Message>> {
PROBE.with(|probe| probe.borrow_mut().arrivals.drain(..).collect())
}
/// What the scans did since the last call.
pub(super) fn take_counts() -> Counts {
PROBE.with(|probe| {
let mut probe = probe.borrow_mut();
Counts {
points: std::mem::take(&mut probe.points),
handed_back: std::mem::take(&mut probe.handed_back),
delivered: std::mem::take(&mut probe.delivered),
}
})
}
/// Called by the drain at every interleave point: count it, and deliver the
/// next scripted burst behind whatever the transport delivered.
pub(super) fn at_interleave_point(handed_back: bool, arrived: &mut Vec<Message>) {
PROBE.with(|probe| {
let mut probe = probe.borrow_mut();
probe.points += 1;
probe.handed_back += usize::from(handed_back);
if let Some(burst) = probe.arrivals.pop_front() {
probe.delivered += 1;
arrived.extend(burst);
}
});
}
@@ -163,11 +163,13 @@ impl Server {
queue,
scanning: false,
head_owed: false,
opened_mid_scan: false,
staging: false,
rescan_wanted: false,
answering_a_rescan: false,
stopped: false,
held: Vec::new(),
behind: 0,
deferred: Vec::new(),
verbose,
born: Instant::now(),
@@ -0,0 +1,153 @@
//! A caret just past a name is on that name, for every request about the
//! symbol under the cursor (`docs/features/scan-ordering/README.md`, A1).
//!
//! The owner's report: Find All References said "No references found" for a
//! port, and worked again after clicking away and back. A double-click, a
//! click on the right half of the last letter, or a row of lucisv's own
//! References view leaves the caret *after* the name; spans are
//! end-exclusive, so the request used to ask about the next character.
use super::*;
const SOURCE: &str = "\
module sub (input logic clk);
endmodule
module top;
logic clk;
sub u_sub (.clk(clk));
typedef logic [3:0] nib_t;
nib_t n;
assign n = 4'd1;
endmodule
class base;
endclass
class child extends base;
endclass
";
/// A session with [`SOURCE`] open, and its uri.
fn opened(tag: &str) -> (Tree, Session, Uri) {
let tree = Tree::new(tag);
tree.write("top.sv", SOURCE);
let mut session = Session::wide(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("top.sv"), SOURCE);
let _ = session.drain();
(tree, session, uri)
}
/// The params every position request below sends, plus what `method` adds.
fn at(method: &str, uri: &Uri, line: u32, character: u32) -> Value {
let mut params = serde_json::json!({
"textDocument": { "uri": uri },
"position": { "line": line, "character": character },
});
if method == References::METHOD {
params["context"] = serde_json::json!({ "includeDeclaration": true });
}
if method == Rename::METHOD {
params["newName"] = serde_json::json!("renamed");
}
params
}
/// The answer, or the error's message — a declined rename is an answer too.
fn answer(session: &mut Session, method: &str, params: Value) -> Value {
match session.request(method, params).response_result {
Ok(value) => value,
Err(error) => Value::String(error.message),
}
}
/// Whether an answer says nothing: `null`, `[]`, or a refusal.
fn says_nothing(value: &Value) -> bool {
value.is_null() || value.as_array().is_some_and(Vec::is_empty) || value.is_string()
}
/// For `name` on `line`, the answer at the name's first column, just past
/// its last character, and one column further right.
fn around(session: &mut Session, uri: &Uri, method: &str, line: u32, name: &str) -> [Value; 3] {
let text = SOURCE.lines().nth(line as usize).expect("the line");
let start = find_word(text, name) as u32;
let end = start + name.len() as u32;
[start, end, end + 1].map(|column| answer(session, method, at(method, uri, line, column)))
}
/// The byte column of `name` as a whole word on `text`.
fn find_word(text: &str, name: &str) -> usize {
let is_name = |c: char| c.is_ascii_alphanumeric() || c == '_';
text.match_indices(name)
.find(|(at, _)| {
let before = text[..*at].chars().next_back().is_none_or(|c| !is_name(c));
let after = text[at + name.len()..].chars().next().is_none_or(|c| !is_name(c));
before && after
})
.map(|(at, _)| at)
.expect("the name on its line")
}
#[test]
fn every_symbol_request_answers_the_same_just_past_a_name_as_at_its_start() {
let (_tree, mut session, uri) = opened("caretend");
// (method, line, name) — each followed by a character that is not part
// of a name, so one column further right answers nothing. The two
// hierarchy prepares are the exception: they answer for the whole
// instantiation or declaration, so one further right is still the name.
let cases = [
(References::METHOD, 3, "clk"),
(GotoDefinition::METHOD, 7, "n"),
(HoverRequest::METHOD, 3, "clk"),
(DocumentHighlightRequest::METHOD, 3, "clk"),
(PrepareRenameRequest::METHOD, 3, "clk"),
(Rename::METHOD, 3, "clk"),
(GotoTypeDefinition::METHOD, 7, "n"),
(CallHierarchyPrepare::METHOD, 4, "sub"),
(TypeHierarchyPrepare::METHOD, 9, "base"),
];
for (method, line, name) in cases {
let [start, end, beyond] = around(&mut session, &uri, method, line, name);
assert!(!says_nothing(&start), "{method} at the start of {name} answers: {start}");
assert_eq!(end, start, "{method} just past {name} answers as at its start");
if ![CallHierarchyPrepare::METHOD, TypeHierarchyPrepare::METHOD].contains(&method) {
assert!(says_nothing(&beyond), "{method} one further right: nothing, got {beyond}");
}
}
}
#[test]
fn a_caret_after_a_dot_is_on_the_member_and_before_it_on_the_instance() {
// `u_sub.clk` is not in the fixture, but `.clk(` is: the caret between
// `.` and `clk` is on `clk`, and just past `clk` (before `(`) too.
let (_tree, mut session, uri) = opened("caretdot");
let text = SOURCE.lines().nth(4).expect("line 4");
let port = find_word(text, "clk") as u32;
let refs = |s: &mut Session, column| {
answer(s, References::METHOD, at(References::METHOD, &uri, 4, column))
};
let on_port = refs(&mut session, port);
assert!(!says_nothing(&on_port));
assert_eq!(refs(&mut session, port + 3), on_port, "before the paren: the port");
let signal = refs(&mut session, port + 4);
assert!(!says_nothing(&signal), "after the paren: the signal");
assert_ne!(signal, on_port, "the signal's references are not the port's");
assert_eq!(refs(&mut session, port + 7), signal, "before the closing paren: the signal");
}
#[test]
fn the_column_past_a_name_is_counted_in_utf16_after_non_ascii_text() {
// `é` is two bytes and one UTF-16 unit: the caret arrives in units, is
// converted to a byte offset, and only then moved back one byte.
let text = "module m;\n /* é ü */ logic tx;\n assign tx = 1'b0;\nendmodule\n";
let tree = Tree::new("caretutf16");
tree.write("m.sv", text);
let mut session = Session::wide(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), text);
let line = text.lines().nth(1).expect("line 1");
let start = line[..line.find("tx").expect("tx")].encode_utf16().count() as u32;
let refs = |s: &mut Session, column| {
answer(s, References::METHOD, at(References::METHOD, &uri, 1, column))
};
let at_start = refs(&mut session, start);
assert_eq!(at_start.as_array().map(Vec::len), Some(2), "the declaration and the use");
assert_eq!(refs(&mut session, start + 2), at_start, "just past `tx`, in UTF-16 units");
assert!(says_nothing(&refs(&mut session, start + 3)), "past the `;`");
}
@@ -0,0 +1,754 @@
//! The localized reindex held to a whole rebuild through the real server
//! (`docs/features/localized-reindex/README.md`).
//!
//! Every step goes through the notifications an editor sends — a change, a
//! save and the watcher's echo of it for an open buffer; a watcher event alone
//! for a file rewritten, created or deleted on disk — and after every step the
//! server's state is compared with what a whole rebuild over the same disk and
//! the same buffers gives: the index (postings and readers table included),
//! the completion tables, the include graph, every open buffer's cross-file
//! answers, and **the diagnostics last published for every open buffer**. The
//! last is the one the narrowing could get wrong without any table showing it:
//! a buffer the server decided not to republish must still be showing what a
//! fresh analysis would say.
use std::collections::BTreeMap;
use super::*;
/// A session over a scratch tree, with what it last published per buffer.
struct Mirror {
tree: Tree,
session: Session,
open: BTreeMap<PathBuf, (Uri, i32)>,
shown: BTreeMap<String, Value>,
/// Whole rescans seen, so a sweep can say how much of it the narrowed
/// path carried.
rescans: usize,
}
impl Mirror {
fn new(name: &str, files: &[(&str, &str)], open: &[&str]) -> Mirror {
let tree = Tree::new(name);
for (rel, text) in files {
tree.write(rel, text);
}
Mirror::over(tree, open)
}
fn over(tree: Tree, open: &[&str]) -> Mirror {
let wide = ClientSettings {
index_scope: crate::settings::IndexScope::Workspace,
..Default::default()
};
Mirror::with(tree, open, wide)
}
fn with(tree: Tree, open: &[&str], settings: ClientSettings) -> Mirror {
// A client that shows a bar, so a whole rescan is visible as one.
let abilities =
ClientAbilities { file_watching: true, work_done_progress: true, ..Default::default() };
let session = Session::started(vec![tree.path.clone()], abilities, settings);
let mut mirror =
Mirror { tree, session, open: BTreeMap::new(), shown: BTreeMap::new(), rescans: 0 };
for rel in open {
let path = mirror.tree.path.join(rel);
let text = std::fs::read_to_string(&path).expect("an open buffer's file is on disk");
let uri = mirror.session.open(&path, &text);
mirror.open.insert(path, (uri, 1));
}
mirror.absorb();
mirror
}
/// Remember the newest diagnostics the server pushed for each buffer, and
/// count the whole rescans (a progress bar begun) among the steps.
fn absorb(&mut self) {
for message in self.session.drain() {
let Message::Notification(n) = message else { continue };
if n.method == PublishDiagnostics::METHOD {
let published: PublishDiagnosticsParams =
serde_json::from_value(n.params).expect("publish params");
let shown = serde_json::to_value(&published.diagnostics).expect("diagnostics");
self.shown.insert(published.uri.as_str().to_string(), shown);
} else if n.method == Progress::METHOD && n.params.to_string().contains("\"begin\"") {
self.rescans += 1;
}
}
}
/// Write `rel` as an editor does: through its buffer when it is open (the
/// change, the save, the disk, the watcher's echo), else on disk alone
/// with the watcher's event.
fn write(&mut self, rel: &str, text: &str) {
let path = self.tree.path.join(rel);
let created = !path.exists();
if let Some((uri, version)) = self.open.get_mut(&path) {
*version += 1;
let change = serde_json::json!({
"textDocument": { "uri": uri, "version": *version },
"contentChanges": [{ "text": text }],
});
let save = serde_json::json!({ "textDocument": { "uri": uri } });
self.session.notify(DidChangeTextDocument::METHOD, change);
self.tree.write(rel, text);
self.session.notify(DidSaveTextDocument::METHOD, save);
} else {
self.tree.write(rel, text);
}
let kind = if created { FileChangeType::CREATED } else { FileChangeType::CHANGED };
self.event(&path, kind);
}
/// Delete a closed file on disk, as a checkout does.
fn delete(&mut self, rel: &str) {
let path = self.tree.path.join(rel);
assert!(!self.open.contains_key(&path), "the sweep deletes closed files only");
std::fs::remove_file(&path).expect("delete");
self.event(&path, FileChangeType::DELETED);
}
/// Save an open buffer that has not changed, and the watcher's echo — a
/// save the index records nothing about.
fn save_only(&mut self, rel: &str) {
let path = self.tree.path.join(rel);
let (uri, _) = self.open.get(&path).cloned().expect("an open buffer");
let save = serde_json::json!({ "textDocument": { "uri": uri } });
self.session.notify(DidSaveTextDocument::METHOD, save);
self.event(&path, FileChangeType::CHANGED);
}
/// Rewrite an open buffer's file on disk behind the editor's back: the
/// editor reloads the clean buffer (a change carrying the disk's text),
/// and the watcher reports the file. No save.
fn disk_only(&mut self, rel: &str, text: &str) {
let path = self.tree.path.join(rel);
self.tree.write(rel, text);
if let Some((uri, version)) = self.open.get_mut(&path) {
*version += 1;
let change = serde_json::json!({
"textDocument": { "uri": uri, "version": *version },
"contentChanges": [{ "text": text }],
});
self.session.notify(DidChangeTextDocument::METHOD, change);
}
self.event(&path, FileChangeType::CHANGED);
}
/// Open a file that is on disk, after the startup scan.
fn open_file(&mut self, rel: &str) {
let path = self.tree.path.join(rel);
let text = std::fs::read_to_string(&path).expect("on disk");
let uri = self.session.open(&path, &text);
self.open.insert(path, (uri, 1));
}
fn event(&mut self, path: &Path, typ: FileChangeType) {
let changes = vec![FileEvent { uri: path_to_uri(path).expect("uri"), typ }];
self.session.notify(DidChangeWatchedFiles::METHOD, DidChangeWatchedFilesParams { changes });
}
/// The whole claim: what the server holds and last showed is what a whole
/// rebuild over the same disk and buffers gives. The rebuild is done in
/// place, so a run that passes goes on from the state it already had.
fn holds(&mut self, step: &str) {
self.absorb();
let workspace = &mut self.session.server.workspace;
let incremental = workspace.derived_fingerprint();
workspace.rebuild_index();
let rebuilt = workspace.derived_fingerprint();
if incremental != rebuilt {
let first = incremental.lines().zip(rebuilt.lines()).find(|(a, b)| a != b);
panic!("{step}: the incremental state is not a rebuild's; first difference {first:?}");
}
for (uri, _) in self.open.values() {
let fresh = self.session.server.diagnostics_of(uri);
let fresh = serde_json::to_value(&fresh).expect("diagnostics");
let shown = self.shown.get(uri.as_str()).cloned().unwrap_or(Value::Null);
assert_eq!(shown, fresh, "{step}: {} shows stale diagnostics", uri.as_str());
}
}
/// Every step, each followed by the check.
fn steps(&mut self, steps: &[(&str, &str)]) {
self.holds("before any step");
for (at, (rel, text)) in steps.iter().enumerate() {
self.write(rel, text);
self.holds(&format!("step {at}, `{rel}`"));
}
}
}
const LEAF: &str =
"module leaf (input logic clk, output logic q);\n logic s;\n assign q = s;\nendmodule\n";
const TOP: &str = "module top;\n logic c, d;\n leaf u_leaf (.clk(c), .q(d));\nendmodule\n";
const TB: &str = "module tb;\n top dut ();\n initial $display(dut.u_leaf.s);\nendmodule\n";
const PKG: &str =
"package cfg_pkg;\n localparam int W = 8;\n typedef logic [W-1:0] word_t;\nendpackage\n";
const USER: &str = "module user import cfg_pkg::*; (input word_t a, output word_t b);\n assign b = a + W;\nendmodule\n";
const DEFS: &str = "`define WIDTH 8\n`define CLOG(x) $clog2(x)\n";
const INCLUDER: &str =
"`include \"defs.svh\"\nmodule includer;\n logic [`WIDTH-1:0] v;\nendmodule\n";
fn design() -> Vec<(&'static str, &'static str)> {
vec![
("rtl/leaf.sv", LEAF),
("rtl/top.sv", TOP),
("dv/tb.sv", TB),
("rtl/cfg_pkg.sv", PKG),
("rtl/user.sv", USER),
("rtl/defs.svh", DEFS),
("rtl/includer.sv", INCLUDER),
]
}
#[test]
fn every_kind_of_edit_to_an_open_module_leaves_the_rebuilt_state_and_every_squiggle() {
let mut mirror =
Mirror::new("lr_module", &design(), &["rtl/leaf.sv", "rtl/top.sv", "dv/tb.sv"]);
let open_leaf = |text: &str| ("rtl/leaf.sv", text.to_string());
let steps = [
// Nothing the index records: a comment after the last token.
open_leaf(&format!("{LEAF}// trailing\n")),
// A body edit, a local signal, a comment above everything.
open_leaf(&LEAF.replace("assign q = s;", "assign q = ~s;")),
open_leaf(&LEAF.replace(" logic s;\n", " logic s;\n logic t;\n")),
open_leaf(&format!("// above\n{LEAF}")),
// The port list: renamed, removed, added — `top` connects by name, so
// its unknown-port squiggles must follow without `top` being saved.
open_leaf(&LEAF.replace("input logic clk", "input logic clock")),
open_leaf(&LEAF.replace("input logic clk, ", "")),
open_leaf(&LEAF.replace("output logic q", "output logic q, input logic en")),
// The signal the testbench names hierarchically, gone and back.
open_leaf(&LEAF.replace("logic s;\n assign q = s;", "logic r;\n assign q = r;")),
// The module renamed away, so `top`'s instantiation resolves nowhere.
open_leaf(&LEAF.replace("module leaf", "module leaf2")),
open_leaf(LEAF),
];
let steps: Vec<(&str, &str)> = steps.iter().map(|(rel, text)| (*rel, text.as_str())).collect();
mirror.steps(&steps);
}
#[test]
fn edits_to_a_closed_package_a_define_header_and_an_include_line_all_hold() {
let mut mirror = Mirror::new("lr_package", &design(), &["rtl/user.sv", "rtl/includer.sv"]);
let user_text = USER.replace("+ W", "+ W + DEPTH");
let pkg_depth =
PKG.replace("localparam int W = 8;", "localparam int W = 8;\n localparam int DEPTH = 4;");
let defs_more = format!("{DEFS}`define DEPTH 4\n");
let includer_none = INCLUDER.replace("`include \"defs.svh\"\n", "");
let pkg_renamed = PKG.replace("package cfg_pkg", "package cfg2_pkg");
let defs_wider = DEFS.replace("8", "16");
let defs_params = DEFS.replace("CLOG(x)", "CLOG(x, y)");
let includer_nowhere = INCLUDER.replace("defs.svh", "nowhere.svh");
let steps: Vec<(&str, &str)> = vec![
// A package member the open user does not name yet, then does.
("rtl/cfg_pkg.sv", &pkg_depth),
("rtl/user.sv", &user_text),
// The package member it names, gone.
("rtl/cfg_pkg.sv", PKG),
// The package renamed.
("rtl/cfg_pkg.sv", &pkg_renamed),
("rtl/cfg_pkg.sv", PKG),
// A define header: a value, a new macro, a parameter list.
("rtl/defs.svh", &defs_wider),
("rtl/defs.svh", &defs_more),
("rtl/defs.svh", &defs_params),
// An include line removed and put back, and one that resolves nowhere.
("rtl/includer.sv", &includer_none),
("rtl/includer.sv", INCLUDER),
("rtl/includer.sv", &includer_nowhere),
("rtl/includer.sv", INCLUDER),
];
mirror.steps(&steps);
}
#[test]
fn a_signal_another_file_mentions_keeps_its_lint_answer_as_the_mention_comes_and_goes() {
// `unused-signal` consults the workspace census: `dbg` is unused in
// `probe.sv` but named by `peek.sv`, which is closed. The open buffer is
// never saved here, so only a republish the narrowing owed can move it.
let probe = "module probe;\n logic dbg;\nendmodule\n";
let peek = "module peek;\n initial $display(probe.dbg);\nendmodule\n";
let mut mirror =
Mirror::new("lr_census", &[("probe.sv", probe), ("peek.sv", peek)], &["probe.sv"]);
mirror.steps(&[
("peek.sv", "module peek;\n initial $display(1);\nendmodule\n"),
("peek.sv", peek),
("peek.sv", &format!("{peek}// a comment that moves nothing\n")),
]);
}
#[test]
fn files_created_and_deleted_beside_open_buffers_hold() {
let mut mirror = Mirror::new("lr_files", &design(), &["rtl/top.sv", "rtl/includer.sv"]);
mirror.holds("before any step");
// A second `leaf` makes the instantiation ambiguous; deleting it heals it.
mirror.write("rtl/zz_leaf.sv", LEAF);
mirror.holds("a duplicate module created");
mirror.delete("rtl/zz_leaf.sv");
mirror.holds("and deleted");
mirror.delete("rtl/defs.svh");
mirror.holds("an included header deleted");
mirror.write("rtl/defs.svh", DEFS);
mirror.holds("and recreated");
}
#[test]
fn a_watcher_event_for_a_file_the_scope_cannot_take_costs_no_rescan() {
// A generated file under a gitignored directory, and a file outside the
// workspace root: neither can change the index, so neither may cost the
// progress bar — and the state is still a rebuild's.
let mut mirror = Mirror::new("lr_outside", &design(), &["rtl/top.sv"]);
mirror.tree.write(".gitignore", "build/\n");
mirror.holds("before any step");
let _ = mirror.session.drain();
mirror.write("build/gen.sv", "module gen;\nendmodule\n");
assert!(mirror.session.progress().is_empty(), "no bar for a gitignored file");
mirror.holds("a generated file under build/");
let outside = Tree::new("lr_outside_elsewhere");
outside.write("far.sv", "module far;\nendmodule\n");
let _ = mirror.session.drain();
mirror.event(&outside.path.join("far.sv"), FileChangeType::CHANGED);
assert!(mirror.session.progress().is_empty(), "no bar for a file outside every root");
mirror.holds("a file outside the root");
// A file the scope does take, appearing, is still the whole rebuild —
// which is also what proves the two assertions above can fail.
mirror.rescans = 0;
mirror.write("rtl/new.sv", "module fresh;\nendmodule\n");
mirror.holds("a new file in scope");
assert_eq!(mirror.rescans, 1, "a file the scope takes appearing is a rescan");
assert!(
mirror.session.server.workspace.index().units("fresh").len() == 1,
"the new file is in the index"
);
}
#[test]
fn a_buffer_opened_from_outside_the_filelist_joins_the_index_on_its_first_save() {
// VS Code restores editors while the startup scan runs; one outside the
// filelist is open but not indexed until something rebuilds. Its first
// save used to be that rebuild, bar and all.
let mut files = design();
files.push(("rtl/waits.sv", "`include \"late.svh\"\nmodule waits;\nendmodule\n"));
files.push(("files.f", "rtl/leaf.sv\nrtl/top.sv\nrtl/cfg_pkg.sv\nrtl/waits.sv\n"));
let tree = Tree::new("lr_filelist");
for (rel, text) in &files {
tree.write(rel, text);
}
let listed = ClientSettings { filelist: Some("files.f".to_string()), ..Default::default() };
let mut mirror = Mirror::with(tree, &["rtl/top.sv", "dv/tb.sv"], listed);
mirror.rescans = 0;
mirror.write("dv/tb.sv", &TB.replace("$display", "$write"));
mirror.holds("the first save of the unlisted buffer");
assert_eq!(mirror.rescans, 0, "the buffer was on disk before the scan: no rescan");
assert!(mirror.session.server.workspace.index().units("tb").len() == 1, "and it is indexed");
// A file born after the scan may be what some `include` was waiting
// for — `waits.sv`'s is: its lines are re-resolved, still no rebuild.
mirror.write("rtl/late.svh", "`define LATE 1\n");
let path = mirror.tree.path.join("rtl/late.svh");
let uri = mirror.session.open(&path, "`define LATE 1\n");
mirror.open.insert(path, (uri, 1));
mirror.rescans = 0;
mirror.write("rtl/late.svh", "`define LATE 2\n");
mirror.holds("the first save of a buffer younger than the scan");
assert_eq!(mirror.rescans, 0, "the include waiting for it is re-resolved in place");
let graph = mirror.session.server.workspace.includes();
assert_eq!(graph.reachable(vec![mirror.tree.path.join("rtl/waits.sv")]).len(), 2, "and found");
}
/// QA F1: a header the scope cannot take, appearing and vanishing, moves an
/// in-scope includer's edge — an include is resolved against the disk.
#[test]
fn a_header_outside_the_scope_created_and_deleted_moves_the_includers_edges() {
let files = [
(".gitignore", "gen/\n"),
("rtl/a.sv", "`include \"../gen/h.svh\"\nmodule a;\nendmodule\n"),
("rtl/a_inc.svh", "`include \"../gen/h.svh\"\n`define AW 2\n"),
("rtl/b.sv", "`include \"a_inc.svh\"\nmodule b;\nendmodule\n"),
];
let mut mirror = Mirror::new("lr_f1_ignored", &files, &["rtl/b.sv"]);
mirror.steps(&[("gen/h.svh", "`define GEN_W 4\n")]);
mirror.rescans = 0;
mirror.delete("gen/h.svh");
mirror.holds("the ignored header deleted");
mirror.write("gen/h.svh", "`define GEN_W 5\n");
mirror.holds("and created again");
assert_eq!(mirror.rescans, 0, "the include graph alone, never a rescan");
}
/// QA R2-1: one event naming a burst of files is sorted path by path only
/// while that is cheaper than a rescan (`BURST_DIVISOR`); past it the event
/// takes the whole rescan. The state is a rebuild's on both sides.
#[test]
fn a_burst_of_created_files_is_sorted_below_the_threshold_and_rescanned_above() {
let mut files = design();
files.push((".gitignore", "gen/\n"));
files.push(("rtl/waits.sv", "`include \"../gen/h0.svh\"\nmodule waits;\nendmodule\n"));
let mut mirror = Mirror::new("lr_burst", &files, &["rtl/top.sv"]);
mirror.holds("before any step");
let held = mirror.session.server.workspace.index().files().len();
let burst = |mirror: &mut Mirror, count: usize, tag: &str| {
let changes: Vec<FileEvent> = (0..count)
.map(|k| {
let rel = format!("gen/{tag}{k}.svh");
mirror.tree.write(&rel, &format!("`define {}{k} 1\n", tag.to_uppercase()));
let path = mirror.tree.path.join(rel);
FileEvent { uri: path_to_uri(&path).expect("uri"), typ: FileChangeType::CREATED }
})
.collect();
let params = DidChangeWatchedFilesParams { changes };
mirror.session.notify(DidChangeWatchedFiles::METHOD, params);
};
mirror.rescans = 0;
burst(&mut mirror, held / 2, "h");
mirror.holds("a burst at the threshold, `h0.svh` among it");
assert_eq!(mirror.rescans, 0, "sorted path by path: {held} held, {} named", held / 2);
burst(&mut mirror, held / 2 + 1, "k");
mirror.write("gen/h0.svh", "`define H0 2\n");
mirror.holds("a burst past the threshold");
assert_eq!(mirror.rescans, 1, "one path more is the whole rescan");
}
/// QA F1, filelist mode: an unlisted header under an `+incdir+`.
#[test]
fn an_unlisted_header_under_an_incdir_created_moves_the_includers_edge() {
let files = [
("files.f", "+incdir+inc\nrtl/a.sv\nrtl/top.sv\n"),
("rtl/a.sv", "`include \"h2.svh\"\nmodule a;\nendmodule\n"),
("rtl/top.sv", "module top;\n a u_a ();\nendmodule\n"),
];
let tree = Tree::new("lr_f1_incdir");
for (rel, text) in files {
tree.write(rel, text);
}
let listed = ClientSettings { filelist: Some("files.f".to_string()), ..Default::default() };
let mut mirror = Mirror::with(tree, &["rtl/top.sv"], listed);
mirror.holds("before any step");
mirror.write("inc/h2.svh", "`define H2 1\n");
mirror.holds("the unlisted header created");
mirror.delete("inc/h2.svh");
mirror.holds("and deleted");
}
/// QA F2: a `[lint]` edit in `lucisv.toml`, which no notification reports,
/// takes effect at the next save — even one the index records nothing about.
#[test]
fn a_lint_configuration_edit_takes_effect_at_a_save_that_moves_nothing() {
let lint_me = "module lint_me;\n\twire unused_w; \n reg r;\nendmodule\n";
let mut mirror = Mirror::new("lr_f2_toml", &[("rtl/lint_me.sv", lint_me)], &["rtl/lint_me.sv"]);
mirror.holds("before any step");
let uri = mirror.open.values().next().map(|(uri, _)| uri.as_str().to_string()).expect("open");
assert_ne!(mirror.shown.get(&uri), Some(&Value::Array(Vec::new())), "premise: findings");
mirror.tree.write(
"lucisv.toml",
"[lint]\nignore = [\"no-tabs\", \"no-trailing-whitespace\", \"unused-signal\"]\n",
);
mirror.save_only("rtl/lint_me.sv");
mirror.holds("the save after the lint configuration changed");
mirror.tree.write("lucisv.toml", "[lint]\n");
mirror.save_only("rtl/lint_me.sv");
mirror.holds("and after it changed back");
}
/// QA F3: a file moved in from elsewhere after the scan keeps its old times;
/// opened and saved, it joins the index and its waiting includer finds it.
/// No watcher event is sent for the move — a client that does not watch, or
/// an event coalesced away — so the save alone must re-resolve the includer
/// (the event's own re-resolution is F1's test).
#[test]
fn a_file_moved_in_after_the_scan_joins_and_is_found_by_its_includer() {
let files = [
("files.f", "rtl/a.sv\nrtl/top.sv\n"),
("rtl/a.sv", "`include \"late.svh\"\nmodule a;\nendmodule\n"),
("rtl/top.sv", "module top;\n a u_a ();\nendmodule\n"),
];
let elsewhere = Tree::new("lr_f3_elsewhere");
elsewhere.write("late.svh", "`define LATE 7\n");
let tree = Tree::new("lr_f3_moved");
for (rel, text) in files {
tree.write(rel, text);
}
let listed = ClientSettings { filelist: Some("files.f".to_string()), ..Default::default() };
let mut mirror = Mirror::with(tree, &["rtl/top.sv"], listed);
mirror.holds("before any step");
let moved = mirror.tree.path.join("rtl/late.svh");
std::fs::rename(elsewhere.path.join("late.svh"), &moved).expect("move in");
mirror.open_file("rtl/late.svh");
let (uri, _) = mirror.open[&moved].clone();
let save = serde_json::json!({ "textDocument": { "uri": uri } });
mirror.session.notify(DidSaveTextDocument::METHOD, save);
mirror.holds("opened and saved, with no watcher echo");
}
/// QA F4: an excluded buffer, open and changed on disk, is taken in, as a
/// fresh server takes every open buffer in.
#[test]
fn an_excluded_open_buffer_changed_on_disk_is_taken_in() {
let files = [
("lucisv.toml", "exclude = [\"rtl/b.sv\"]\n"),
("rtl/b.sv", "module b;\nendmodule\n"),
("rtl/top.sv", "module top;\n b u_b ();\nendmodule\n"),
];
let mut mirror = Mirror::new("lr_f4_excluded", &files, &["rtl/top.sv"]);
mirror.holds("before any step");
mirror.open_file("rtl/b.sv");
mirror.disk_only("rtl/b.sv", "module b;\n wire w2;\nendmodule\n");
mirror.holds("the excluded buffer changed on disk");
assert_eq!(mirror.session.server.workspace.index().units("b").len(), 1, "taken in");
}
#[cfg(unix)]
#[test]
fn a_held_file_reported_by_its_real_path_takes_the_one_file_update() {
// The workspace is opened through a symlink; the watcher reports the real
// path. Before this round that was a "file the index does not hold" and a
// whole rescan per save.
let real = Tree::new("lr_real");
for (rel, text) in design() {
real.write(rel, text);
}
let link = Tree::new("lr_link");
std::fs::remove_dir_all(&link.path).expect("make room for the link");
std::os::unix::fs::symlink(&real.path, &link.path).expect("symlink");
let abilities =
ClientAbilities { file_watching: true, work_done_progress: true, ..Default::default() };
let mut session = Session::wide_with(vec![link.path.clone()], abilities);
let _ = session.drain();
real.write("rtl/leaf.sv", &LEAF.replace("input logic clk", "input logic clock"));
session.watched(&[real.path.join("rtl/leaf.sv")]);
assert!(session.progress().is_empty(), "the one-file path, not a rescan");
let index = session.server.workspace.index();
assert_eq!(index.member("leaf", "clock").len(), 1, "and the update landed");
assert!(
index.files().iter().all(|path| path.starts_with(&link.path)),
"under the link's spelling"
);
let _ = std::fs::remove_file(&link.path);
}
// ----------------------------------------------------------------------
// The seeded sweep
// ----------------------------------------------------------------------
/// xorshift64*: reproducible from a seed, no dependency.
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 >> 12;
self.0 ^= self.0 << 25;
self.0 ^= self.0 >> 27;
self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
}
fn below(&mut self, n: usize) -> usize {
(self.next() % n.max(1) as u64) as usize
}
}
/// One random edit: a line inserted, deleted, duplicated or swapped with its
/// neighbour, or one identifier renamed to another the file already uses —
/// edits that move spans, names and whole declarations.
fn mutate(text: &str, rng: &mut Rng) -> String {
let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
let at = rng.below(lines.len() + 1);
match rng.below(6) {
0 => lines.insert(at, " // lucisv sweep".to_string()),
1 if at < lines.len() => {
lines.remove(at);
}
2 if at < lines.len() => {
let line = lines[at].clone();
lines.insert(at, line);
}
3 if at + 1 < lines.len() => lines.swap(at, at + 1),
4 => lines.insert(at, " logic lucisv_sweep_q;".to_string()),
_ => {
let words = vlog_semantic::words::harvest_text(text);
if words.len() >= 2 {
let from = words[rng.below(words.len())].clone();
let to = words[rng.below(words.len())].clone();
if let Some(line) = lines.iter_mut().find(|line| line.contains(from.as_str())) {
*line = line.replacen(from.as_str(), &to, 1);
}
}
}
}
let mut out = lines.join("\n");
out.push('\n');
out
}
/// `steps` seeded mutations over every source file under `tree`, with `open`
/// buffers open, each step checked; now and then a closed file is deleted or
/// a new one created.
fn sweep(tree: Tree, open: usize, seed: u64, steps: usize) {
// `opened` below is also what the lint-configuration step saves.
let mut files: Vec<String> = Vec::new();
collect(&tree.path, &tree.path, &mut files);
files.sort();
assert!(!files.is_empty(), "premise: a tree with sources in it");
let mut rng = Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1);
let opened: Vec<String> = (0..open).map(|_| files[rng.below(files.len())].clone()).collect();
let opened_refs: Vec<&str> = opened.iter().map(String::as_str).collect();
// The setting the event kinds QA found need: a gitignored `gen/` whose
// headers an in-scope file waits for, and excluded names to open.
tree.write(".gitignore", "gen/\n");
tree.write("lucisv.toml", "exclude = [\"sweep_excluded_*\"]\n");
let waits: String = (0..4).map(|k| format!("`include \"gen/h{k}.svh\"\n")).collect();
tree.write("sweep_waits.sv", &format!("{waits}module sweep_waits;\nendmodule\n"));
let elsewhere = Tree::new(&format!("lr_sweep_elsewhere_{seed}"));
let mut mirror = Mirror::over(tree, &opened_refs);
mirror.holds(&format!("seed {seed}: before any step"));
mirror.rescans = 0;
for step in 0..steps {
let rel = files[rng.below(files.len())].clone();
let path = mirror.tree.path.join(&rel);
let label = format!("seed {seed}, step {step}, `{rel}`");
match rng.below(24) {
0 if !mirror.open.contains_key(&path) && path.exists() => mirror.delete(&rel),
1 => mirror.write(&format!("sweep_new_{step}.sv"), "module sweep_new;\nendmodule\n"),
// A header outside the scope, waited for, toggled.
2 => {
let header = format!("gen/h{}.svh", rng.below(4));
match mirror.tree.path.join(&header).exists() {
true => mirror.delete(&header),
false => mirror.write(&header, &format!("`define SWEEP_{step} 1\n")),
}
}
// The lint configuration edited, then a save that moves nothing.
3 => {
let rules = ["no-tabs", "unused-signal", "line-length", "no-trailing-whitespace"];
let ignored: Vec<String> = rules
.iter()
.filter(|_| rng.below(2) == 0)
.map(|r| format!("\"{r}\""))
.collect();
let config = format!(
"exclude = [\"sweep_excluded_*\"]\n[lint]\nignore = [{}]\n",
ignored.join(", ")
);
mirror.tree.write("lucisv.toml", &config);
if let Some(open) = opened.get(rng.below(opened.len().max(1))) {
mirror.save_only(open);
}
}
// A file moved in from elsewhere, old times and all, then opened
// and saved.
4 => {
let name = format!("sweep_moved_{step}.svh");
elsewhere.write(&name, &format!("`define SWEEP_MOVED_{step} 1\n"));
let to = mirror.tree.path.join("gen").join(&name);
std::fs::create_dir_all(mirror.tree.path.join("gen")).expect("gen/");
std::fs::rename(elsewhere.path.join(&name), &to).expect("move in");
mirror.event(&to, FileChangeType::CREATED);
let rel = format!("gen/{name}");
mirror.open_file(&rel);
mirror.save_only(&rel);
}
// An excluded file, opened, then changed on disk.
5 => {
let rel = format!("sweep_excluded_{step}.sv");
mirror.write(&rel, &format!("module sweep_excluded_{step};\nendmodule\n"));
mirror.open_file(&rel);
let text = format!("module sweep_excluded_{step};\n wire w;\nendmodule\n");
mirror.disk_only(&rel, &text);
}
_ => {
let Ok(text) = std::fs::read_to_string(&path) else { continue };
let text = match mirror.open.contains_key(&path) {
true => mirror.session.server.workspace.text_of(&path).unwrap_or(text),
false => text,
};
mirror.write(&rel, &mutate(&text, &mut rng));
}
}
mirror.holds(&label);
}
eprintln!(
"seed {seed}: {steps} steps over {} files, {} of them whole rescans",
files.len(),
mirror.rescans
);
}
fn collect(root: &Path, dir: &Path, out: &mut Vec<String>) {
let Ok(entries) = std::fs::read_dir(dir) else { return };
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
collect(root, &path, out);
} else if crate::watch::watched(&path, None) {
if let Ok(rel) = path.strip_prefix(root) {
out.push(rel.to_string_lossy().into_owned());
}
}
}
}
/// Copy every source file under `from` into `tree` under `prefix`, saying
/// how many — none when `from` is not on this machine.
fn copy_into(tree: &Tree, from: &Path, prefix: &str) -> usize {
let mut files: Vec<String> = Vec::new();
collect(from, from, &mut files);
for rel in &files {
let Ok(text) = std::fs::read_to_string(from.join(rel)) else { continue };
tree.write(&format!("{prefix}{rel}"), &text);
}
files.len()
}
fn home(rel: &str) -> PathBuf {
std::env::var_os("HOME").map(PathBuf::from).unwrap_or_default().join(rel)
}
#[test]
fn a_seeded_sweep_over_the_hand_written_design_holds() {
for seed in 1..=3 {
let tree = Tree::new(&format!("lr_sweep_{seed}"));
for (rel, text) in design() {
tree.write(rel, text);
}
sweep(tree, 3, seed, 25);
}
}
/// `tools/guard.sh -- cargo test --release -p lucisv_server sweep_over_the_corpus -- --ignored --nocapture`
#[test]
#[ignore = "a sweep over ~/.cache/lucisv-corpus, minutes in a debug build"]
fn a_seeded_sweep_over_the_corpus_holds() {
let from = std::env::var_os("LUCISV_CORPUS")
.map(PathBuf::from)
.unwrap_or_else(|| home(".cache/lucisv-corpus"));
for seed in [11, 12, 13] {
let tree = Tree::new(&format!("lr_corpus_{seed}"));
if copy_into(&tree, &from, "") == 0 {
eprintln!("{} not present — skipping", from.display());
return;
}
sweep(tree, 5, seed, 60);
}
}
/// `tools/guard.sh -- cargo test --release -p lucisv_server sweep_over_an_opentitan -- --ignored --nocapture`
#[test]
#[ignore = "a sweep over a sample of OpenTitan, minutes in a debug build"]
fn a_seeded_sweep_over_an_opentitan_sample_holds() {
let hw = std::env::var_os("LUCISV_OPENTITAN")
.map(PathBuf::from)
.unwrap_or_else(|| home(".cache/lucisv-opentitan-full/hw"));
for seed in [21, 22] {
let tree = Tree::new(&format!("lr_opentitan_{seed}"));
let mut copied = 0;
for sub in ["ip/uart/", "ip/gpio/", "ip/prim/rtl/", "ip/prim_generic/rtl/", "ip/tlul/rtl/"]
{
copied += copy_into(&tree, &hw.join(sub), sub);
}
if copied == 0 {
eprintln!("{} not present — skipping", hw.display());
return;
}
sweep(tree, 6, seed, 60);
}
}
@@ -47,6 +47,7 @@ use crate::{design_hierarchy, diagnostics, format, lens, pairs, ports};
mod apply_edit;
mod cancel;
mod caret_boundary;
mod code_action;
mod file_ops;
mod folders;
@@ -56,6 +57,8 @@ mod hierarchy_reach;
mod index;
mod large_file;
mod lint_snapshot;
mod localized_reindex;
mod ordering_random;
mod progress;
mod pull_diagnostics;
mod qa_generate_label;
@@ -67,6 +70,7 @@ mod rename_implicit;
mod rename_top_rooted_scope;
mod requests;
mod scan;
mod scan_ordering;
mod scan_trace;
mod settings;
mod startup;
@@ -0,0 +1,341 @@
//! Random interleavings of the client's bursts against the real loop, mid-scan
//! and between scans (`docs/features/scan-ordering/README.md`, B and C).
//!
//! A seeded client sends bursts of requests, full and incremental
//! `didChange`s for three documents, opens, closes, cancels and watcher
//! events that cost a whole rescan; some bursts land at a scan's interleave
//! points ([`probe::script`]), the rest between scans. After every round the
//! server must hold exactly the buffers the client holds, with exactly the
//! client's text; every request must be answered exactly once; no scan may
//! hand its held batch back more often than the `didOpen`s and scans it saw
//! can explain; and at the end, the server must answer what a fresh server
//! on the same files and buffers answers.
use std::collections::HashMap;
use super::super::probe;
use super::scan_ordering::{ask, closed, created, note, opened, ordering_tree, settle, A_TEXT};
use super::*;
/// A small deterministic generator — xorshift64, no dependency.
struct Rng(u64);
impl Rng {
fn new(seed: u64) -> Rng {
Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
}
fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
fn below(&mut self, n: usize) -> usize {
(self.next() % n.max(1) as u64) as usize
}
fn percent(&mut self, p: u64) -> bool {
self.next() % 100 < p
}
}
/// The client: what it has open, with what text, and what it has asked.
struct Client {
rng: Rng,
docs: Vec<(Uri, String)>,
open: HashMap<Uri, (u32, String)>,
asked: Vec<i32>,
next_id: i32,
created: Vec<PathBuf>,
root: PathBuf,
/// `didOpen`s sent this round — what may re-order a scan.
opens: usize,
}
impl Client {
fn new(seed: u64, tree: &Tree) -> Client {
let docs = ["a/a.sv", "b/b.sv", "c/c.sv"]
.iter()
.map(|rel| {
let path = tree.path.join(rel);
let text = std::fs::read_to_string(&path).expect("a document");
(path_to_uri(&path).expect("uri"), text)
})
.collect();
Client {
rng: Rng::new(seed),
docs,
open: HashMap::new(),
asked: Vec::new(),
next_id: 1,
created: Vec::new(),
root: tree.path.clone(),
opens: 0,
}
}
fn doc(&mut self) -> Uri {
let n = self.rng.below(self.docs.len());
self.docs[n].0.clone()
}
fn burst(&mut self) -> Vec<Message> {
(0..1 + self.rng.below(4)).map(|_| self.message()).collect()
}
/// One message, applied to the client's own view as it is sent.
fn message(&mut self) -> Message {
let uri = self.doc();
let roll = self.rng.below(100);
match (roll, self.open.contains_key(&uri)) {
(0..=29, true) => self.change(&uri),
(30..=39, true) => {
self.open.remove(&uri);
closed(&uri)
}
(0..=39, false) => self.reopen(&uri),
(40..=49, _) => self.watcher_event(),
(50..=57, _) if !self.asked.is_empty() => {
let id = self.asked[self.rng.below(self.asked.len())];
note(Cancel::METHOD, serde_json::json!({ "id": id }))
}
_ => self.request(&uri),
}
}
fn reopen(&mut self, uri: &Uri) -> Message {
let disk = self.docs.iter().find(|(u, _)| u == uri).map(|(_, t)| t.clone());
let text = disk.unwrap_or_default() + &format!("// opened {}\n", self.rng.below(1000));
self.open.insert(uri.clone(), (1, text.clone()));
self.opens += 1;
opened(uri, &text)
}
/// A full or an incremental `didChange`, ranges in the text the client
/// holds right now — which is what makes a reordering visible.
fn change(&mut self, uri: &Uri) -> Message {
let n = self.rng.below(1000);
let full = self.rng.percent(30);
let lines = self.open[uri].1.split_inclusive('\n').count() as u32;
let line = self.rng.below(lines as usize + 1) as u32;
let (version, text) = self.open.get_mut(uri).expect("open");
*version += 1;
let mut kept: Vec<String> = text.split_inclusive('\n').map(str::to_string).collect();
let change = if full {
kept.push(format!("module m{n};\nendmodule\n"));
serde_json::json!({ "text": kept.concat() })
} else if lines > 3 && n.is_multiple_of(3) {
kept.remove(line.min(lines - 1) as usize);
let at = line.min(lines - 1);
serde_json::json!({
"range": { "start": { "line": at, "character": 0 },
"end": { "line": at + 1, "character": 0 } },
"text": "",
})
} else {
kept.insert(line as usize, format!("// e{n}\n"));
let at = serde_json::json!({ "line": line, "character": 0 });
serde_json::json!({ "range": { "start": at, "end": at }, "text": format!("// e{n}\n") })
};
*text = kept.concat();
note(
DidChangeTextDocument::METHOD,
serde_json::json!({
"textDocument": { "uri": uri, "version": *version },
"contentChanges": [change],
}),
)
}
/// A file created on disk, or one created earlier deleted, and the
/// watcher's word for it. A creation costs a whole rescan.
fn watcher_event(&mut self) -> Message {
if !self.created.is_empty() && self.rng.percent(30) {
let path = self.created.swap_remove(self.rng.below(self.created.len()));
let _ = std::fs::remove_file(&path);
let uri = path_to_uri(&path).expect("uri");
return note(
DidChangeWatchedFiles::METHOD,
serde_json::json!({ "changes": [{ "uri": uri, "type": 3 }] }),
);
}
self.created_file()
}
/// A new package file on disk, and the watcher's word for it.
fn created_file(&mut self) -> Message {
let name = format!("r{}", self.next_id * 1000 + self.rng.below(1000) as i32);
let path = self.root.join("z").join(format!("{name}.sv"));
std::fs::write(&path, format!("package {name};\n localparam K = 1;\nendpackage\n"))
.expect("write");
self.created.push(path.clone());
created(&path)
}
fn request(&mut self, uri: &Uri) -> Message {
let id = self.next_id;
self.next_id += 1;
self.asked.push(id);
let at = serde_json::json!({
"textDocument": { "uri": uri },
"position": { "line": self.rng.below(4), "character": self.rng.below(12) },
});
match self.rng.below(4) {
0 => ask(id, HoverRequest::METHOD, at),
1 => ask(id, GotoDefinition::METHOD, at),
2 => ask(id, WorkspaceSymbolRequest::METHOD, serde_json::json!({ "query": "p00" })),
_ => ask(
id,
DocumentSymbolRequest::METHOD,
serde_json::json!({ "textDocument": { "uri": uri } }),
),
}
}
}
/// What one round's messages from the server came to.
#[derive(Default)]
struct Heard {
answers: HashMap<RequestId, usize>,
scans: usize,
}
fn hear(session: &Session, heard: &mut Heard) {
for message in session.drain() {
match message {
Message::Response(response) => *heard.answers.entry(response.id).or_default() += 1,
Message::Notification(n)
if n.method == Progress::METHOD && n.params["value"]["kind"] == "begin" =>
{
heard.scans += 1;
}
_ => {}
}
}
}
/// The server holds exactly the client's buffers, with the client's text.
fn same_buffers(session: &Session, client: &Client, at: &str) {
let mut held: Vec<Uri> = session.server.workspace.open_uris();
held.sort_by_key(|uri| uri.to_string());
let mut wanted: Vec<Uri> = client.open.keys().cloned().collect();
wanted.sort_by_key(|uri| uri.to_string());
assert_eq!(held, wanted, "{at}: the open buffers");
for (uri, (_, text)) in &client.open {
assert_eq!(&buffer(session, uri), text, "{at}: the text of {uri:?}");
}
}
/// The answers a fresh server is compared on: every open buffer's symbols,
/// and the packages the watcher events created and deleted.
///
/// Not the modules a buffer's edits added: a whole rescan indexes an open
/// buffer's text and a fresh server opened after its scan has not, which is
/// the documented staleness of an unsaved buffer, not an ordering.
fn battery(session: &mut Session, client: &Client) -> Vec<Value> {
let mut uris: Vec<&Uri> = client.open.keys().collect();
uris.sort_by_key(|uri| uri.to_string());
let mut out: Vec<Value> = uris
.into_iter()
.map(|uri| {
session.result(
DocumentSymbolRequest::METHOD,
serde_json::json!({ "textDocument": { "uri": uri } }),
)
})
.collect();
let mut names: Vec<String> = session
.result(WorkspaceSymbolRequest::METHOD, serde_json::json!({ "query": "r" }))
.as_array()
.cloned()
.unwrap_or_default()
.iter()
.filter_map(|s| s["name"].as_str().map(str::to_string))
.collect();
names.sort();
out.push(serde_json::json!(names));
out
}
/// One seeded run: a startup scan with bursts landing in it, then `rounds`
/// rounds of bursts landing between and inside rescans. Reports how many
/// bursts landed mid-scan, so a run cannot pass by never interleaving.
fn run_seed(seed: u64, rounds: usize) -> usize {
let tree = ordering_tree(&format!("orderrand{seed}"));
tree.write("c/c.sv", "module cmod;\n logic c;\nendmodule\n");
let mut client = Client::new(seed, &tree);
let a = client.docs[0].0.clone();
client.open.insert(a.clone(), (1, A_TEXT.to_string()));
let _ = probe::take_counts();
let startup: Vec<Vec<Message>> = (0..1 + client.rng.below(5)).map(|_| client.burst()).collect();
probe::script(startup);
let mut session = Session::started_behind(
vec![tree.path.clone()],
watching_progress(),
wide_ish(),
Vec::new(),
vec![opened(&a, A_TEXT)],
);
let mut heard = Heard::default();
let mut mid_scan = 0;
let mut opens = std::mem::take(&mut client.opens) + 1;
for round in 0..=rounds {
settle(&mut session);
hear(&session, &mut heard);
let counts = probe::take_counts();
let handed_back = counts.handed_back;
mid_scan += counts.delivered;
let at = format!("seed {seed} round {round}");
assert!(
handed_back <= opens + heard.scans + 1,
"{at}: a scan handed its held batch back {handed_back} times \
for {opens} didOpens and {} scans",
heard.scans
);
same_buffers(&session, &client, &at);
if round == rounds {
break;
}
heard.scans = 0;
// Most rounds start a rescan, from anywhere in the burst — so the
// burst's own tail is often still unapplied while the scan runs.
let mut top = client.burst();
if client.rng.percent(70) {
let at = client.rng.below(top.len() + 1);
let trigger = client.created_file();
top.insert(at, trigger);
}
let inside: Vec<Vec<Message>> = (0..client.rng.below(7)).map(|_| client.burst()).collect();
opens = std::mem::take(&mut client.opens);
probe::script(inside);
assert!(!session.batch(top), "no shutdown");
}
for id in &client.asked {
let times = heard.answers.get(&RequestId::from(*id)).copied().unwrap_or(0);
assert_eq!(times, 1, "seed {seed}: request {id} answered {times} times");
}
let mine = battery(&mut session, &client);
let mut fresh = Session::wide(vec![tree.path.clone()], false);
for (uri, (_, text)) in &client.open {
let path = crate::uri::uri_to_path(uri).expect("a path");
fresh.open(&path, text);
}
assert_eq!(mine, battery(&mut fresh, &client), "seed {seed}: a fresh server's answers");
mid_scan
}
#[test]
fn random_bursts_keep_every_buffer_and_answer_every_request_once() {
let mid_scan: usize = (1..=12).map(|seed| run_seed(seed, 10)).sum();
assert!(mid_scan >= 200, "only {mid_scan} bursts landed mid-scan");
}
/// The long run: `cargo test -p lucisv_server -- --ignored ordering_random`.
#[test]
#[ignore = "a few minutes; the normal suite runs the twelve seeds above"]
fn random_bursts_long_run() {
let mid_scan: usize = (100..400).map(|seed| run_seed(seed, 40)).sum();
assert!(mid_scan >= 10_000, "only {mid_scan} bursts landed mid-scan");
}
@@ -81,17 +81,36 @@ fn an_index_rebuild_moves_the_result_id_too() {
// `inter_file_dependencies: true` is a promise: a save rebuilds the
// index, and what the index says can change what a *different* buffer
// reports. A stale "unchanged" there would be a wrong squiggle.
//
// Since localized-reindex (2026-11-19) the save whose record did not move
// still moves the stamp — a lint reads `lucisv.toml` from disk, and a
// save is when an edit to it takes effect (QA F2) — and so does the save
// of an edit the index has not seen.
let tree = Tree::new("pullreindex");
let mut session = Session::with(vec![tree.path.clone()], pulling());
let uri = session.open(&tree.path.join("m.sv"), BROKEN);
let stamp = document_pull(&mut session, &uri, None)["resultId"]
.as_str()
.expect("a result id")
.to_string();
let stamp = |session: &mut Session, previous: Option<&str>| {
document_pull(session, &uri, previous)["resultId"]
.as_str()
.expect("a result id")
.to_string()
};
let first = stamp(&mut session, None);
let save = serde_json::json!({ "textDocument": { "uri": uri } });
session.notify(DidSaveTextDocument::METHOD, save.clone());
let after = document_pull(&mut session, &uri, Some(&first));
assert_eq!(after["kind"], "full", "a save that moved no record: {after:#?}");
session
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
let after = document_pull(&mut session, &uri, Some(&stamp));
session.notify(
DidChangeTextDocument::METHOD,
serde_json::json!({
"textDocument": { "uri": uri, "version": 2 },
"contentChanges": [{ "text": "module m;\n\twire ;\n wire extra;\nendmodule\n" }],
}),
);
let edited = stamp(&mut session, Some(&first));
session.notify(DidSaveTextDocument::METHOD, save);
let after = document_pull(&mut session, &uri, Some(&edited));
assert_eq!(after["kind"], "full", "the index moved: {after:#?}");
}
@@ -201,9 +201,22 @@ fn a_rescan_asks_a_capable_client_to_refresh_its_code_lenses() {
let uri = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
let _ = session.drain();
// Every rescan trigger, one refresh each.
// Every rescan trigger, one refresh each — a save of an edit the index
// has not seen, since a save that moved nothing refreshes nothing
// (localized-reindex, 2026-11-19).
session
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
assert!(session.requests().is_empty(), "a save that moved nothing asks for nothing");
session.notify(
DidChangeTextDocument::METHOD,
serde_json::json!({
"textDocument": { "uri": uri, "version": 2 },
"contentChanges": [{ "text": "module sub;\n wire w;\nendmodule\n" }],
}),
);
session
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
tree.write("top.sv", "module top;\n sub u_a ();\nendmodule\n");
session.watched(&[tree.path.join("top.sv")]);
session.notify(
DidChangeConfiguration::METHOD,
@@ -223,9 +236,22 @@ fn a_client_that_cannot_refresh_code_lenses_is_never_asked_to() {
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
let _ = session.drain();
// A save of an edit the index has not seen, so the save path really
// moves the index (a save that moves nothing refreshes nothing anyway).
session.notify(
DidChangeTextDocument::METHOD,
serde_json::json!({
"textDocument": { "uri": uri, "version": 2 },
"contentChanges": [{ "text": "module sub;\n wire w;\nendmodule\n" }],
}),
);
session
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
tree.write("top.sv", "module top;\n sub u_a ();\nendmodule\n");
session.watched(&[tree.path.join("top.sv")]);
let index = session.server.workspace.index();
let w = index.member_in("sub", "w", vlog_semantic::Surface::Hierarchical);
assert_eq!(w.len(), 1, "premise: the save moved the index");
assert!(session.requests().is_empty(), "silence, on every rescan path");
}
@@ -368,6 +394,14 @@ fn qa_a_rescan_with_several_open_buffers_still_sends_exactly_one_refresh() {
.open(&tree.path.join("top.sv"), "module top;\n sub u_a ();\n sub u_b ();\nendmodule\n");
let _ = session.drain();
// An edit the index has not seen, so the save moves it.
session.notify(
DidChangeTextDocument::METHOD,
serde_json::json!({
"textDocument": { "uri": uri, "version": 2 },
"contentChanges": [{ "text": "module sub;\n wire w;\nendmodule\n" }],
}),
);
session
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
let methods: Vec<String> = session.requests().into_iter().map(|(method, _)| method).collect();
@@ -0,0 +1,312 @@
//! No client message overtakes an older one while a scan answers messages
//! (`docs/features/scan-ordering/README.md`, B and C).
//!
//! Every test here scripts what the client sends *at* a given interleave
//! point ([`probe::script`]) — the transport cannot be timed against a scan's
//! files — and then lets the loop finish the way `run` does: the held batch
//! first, then whatever the scan ended before receiving.
use super::super::probe;
use super::*;
/// A tree with enough files that every whole scan interleaves, plus one
/// file `a/a.sv` (and `b/b.sv`) that a test opens.
pub(super) fn ordering_tree(tag: &str) -> Tree {
let tree = Tree::new(tag);
for n in 0..INTERLEAVE_ABOVE + 6 {
tree.package(&format!("z/p{n:03}.sv"), &format!("p{n:03}"));
}
tree.write("a/a.sv", A_TEXT);
tree.write("b/b.sv", "module bmod;\nendmodule\n");
tree
}
pub(super) const A_TEXT: &str = "module amod;\n logic s;\nendmodule\n";
/// A notification on the wire.
pub(super) fn note(method: &str, params: Value) -> Message {
Message::Notification(Notification::new(method.to_string(), params))
}
/// A request on the wire.
pub(super) fn ask(id: i32, method: &str, params: Value) -> Message {
Message::Request(Request::new(RequestId::from(id), method.to_string(), params))
}
/// A watcher event saying `path` was created — a file the index does not
/// hold, which costs a whole rescan.
pub(super) fn created(path: &Path) -> Message {
note(
DidChangeWatchedFiles::METHOD,
serde_json::json!({ "changes": [{ "uri": path_to_uri(path).expect("uri"), "type": 1 }] }),
)
}
pub(super) fn opened(uri: &Uri, text: &str) -> Message {
note(
DidOpenTextDocument::METHOD,
serde_json::json!({ "textDocument": {
"uri": uri, "languageId": "systemverilog", "version": 1, "text": text,
} }),
)
}
pub(super) fn closed(uri: &Uri) -> Message {
note(DidCloseTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }))
}
/// An incremental `didChange` inserting `text` at the start of `line`.
fn inserted(uri: &Uri, version: u32, line: u32, text: &str) -> Message {
let at = serde_json::json!({ "line": line, "character": 0 });
note(
DidChangeTextDocument::METHOD,
serde_json::json!({
"textDocument": { "uri": uri, "version": version },
"contentChanges": [{ "range": { "start": at, "end": at }, "text": text }],
}),
)
}
fn hover(id: i32, uri: &Uri) -> Message {
ask(
id,
HoverRequest::METHOD,
serde_json::json!({ "textDocument": { "uri": uri }, "position": { "line": 0, "character": 0 } }),
)
}
/// Hand `burst` to the loop as `run` would, with every scripted burst
/// arriving mid-scan, then everything the loop owes afterwards.
fn deliver(session: &mut Session, burst: Vec<Message>) {
assert!(!session.batch(burst), "no shutdown");
let late = probe::unarrived();
assert!(late.is_empty(), "the rescan ended before the script did: {late:#?}");
settle(session);
}
/// What `run` does between bursts: answer the held batch until none is
/// left, then take the scripted bursts that arrived after every scan ended.
pub(super) fn settle(session: &mut Session) {
loop {
while !session.server.held.is_empty() {
let held = std::mem::take(&mut session.server.held);
assert!(!session.batch(held), "no shutdown");
}
let late = probe::unarrived();
if late.is_empty() {
return;
}
for burst in late {
assert!(!session.batch(burst), "no shutdown");
}
}
}
/// A workspace-scoped session showing a progress bar, with `a/a.sv` open,
/// and that buffer's uri.
pub(super) fn with_a_open(tree: &Tree) -> (Session, Uri) {
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
let a = session.open(&tree.path.join("a/a.sv"), A_TEXT);
// What the watcher events in these tests say was created: on disk, and
// not in the index the startup scan built, so each costs a whole rescan.
for new in ["new", "x1", "x2"] {
tree.package(&format!("z/{new}.sv"), new);
}
let _ = probe::take_counts();
let _ = session.drain();
(session, a)
}
#[test]
fn a_change_drained_mid_rescan_waits_behind_an_older_change_held_with_a_request() {
// QA F6, held form: the rescan holds `[hover, v2]`; `v3` arrives at the
// next file and used to be applied at once — ahead of `v2`, which then
// replaced it.
let tree = ordering_tree("orderheldfull");
let (mut session, a) = with_a_open(&tree);
let v2 = format!("{A_TEXT}module v2;\nendmodule\n");
let v3 = format!("{A_TEXT}module v3;\nendmodule\n");
probe::script([vec![hover(1, &a), changed(&a, 2, &v2)], vec![changed(&a, 3, &v3)]]);
deliver(&mut session, vec![created(&tree.path.join("z/new.sv"))]);
assert_eq!(buffer(&session, &a), v3, "the client's last text is the server's");
}
#[test]
fn incremental_changes_held_mid_rescan_are_applied_in_the_order_they_were_sent() {
// The same race under incremental sync is corruption, not staleness: each
// edit is a range into the text the one before it produced.
let tree = ordering_tree("orderheldincr");
let (mut session, a) = with_a_open(&tree);
let first = "// first\n";
let second = " // second, inside the module\n";
probe::script([
vec![hover(1, &a), inserted(&a, 2, 1, first)],
vec![inserted(&a, 3, 2, second)],
]);
deliver(&mut session, vec![created(&tree.path.join("z/new.sv"))]);
let mut client: Vec<&str> = A_TEXT.split_inclusive('\n').collect();
client.insert(1, first);
client.insert(2, second);
assert_eq!(buffer(&session, &a), client.concat());
}
#[test]
fn a_change_drained_mid_rescan_waits_behind_the_rest_of_the_burst_that_started_it() {
// QA F6, tail form: the burst that asks for the rescan still carries
// `v2` behind the watcher event while the scan answers `v3`.
let tree = ordering_tree("ordertail");
let (mut session, a) = with_a_open(&tree);
let v2 = format!("{A_TEXT}module v2;\nendmodule\n");
let v3 = format!("{A_TEXT}module v3;\nendmodule\n");
probe::script([vec![changed(&a, 3, &v3)]]);
let burst = vec![
ask(1, WorkspaceSymbolRequest::METHOD, serde_json::json!({ "query": "p" })),
created(&tree.path.join("z/new.sv")),
changed(&a, 2, &v2),
];
deliver(&mut session, burst);
assert_eq!(buffer(&session, &a), v3);
}
#[test]
fn a_reopen_behind_a_held_close_leaves_the_buffer_open_with_its_new_text() {
// Nothing is lost either way round: a close held behind a request and a
// reopen drained after it are applied close-then-open, so the buffer the
// editor is showing is the one the server holds.
let tree = ordering_tree("orderreopen");
let (mut session, a) = with_a_open(&tree);
let reopened = format!("{A_TEXT}// reopened\n");
probe::script([vec![hover(1, &a), closed(&a)], vec![opened(&a, &reopened)]]);
deliver(&mut session, vec![created(&tree.path.join("z/new.sv"))]);
assert_eq!(buffer(&session, &a), reopened, "open, with the text it was reopened with");
let answered: Vec<RequestId> = session.answers().into_iter().map(|r| r.id).collect();
assert_eq!(answered, [RequestId::from(1)], "the held hover is answered once");
}
#[test]
fn a_change_behind_only_a_held_request_applies_at_once_and_a_late_cancel_waits_with_it() {
// The rule is about notifications overtaking notifications. A change
// with nothing older unapplied but a held *request* is applied where it
// lands — the request is answered later against it, as every late
// request always was — while a cancel for that request waits beside it
// and is honoured when the held batch is replayed.
let tree = ordering_tree("ordernarrow");
let (mut session, a) = with_a_open(&tree);
let v2 = format!("{A_TEXT}// v2\n");
let cancel = note(Cancel::METHOD, serde_json::json!({ "id": 1 }));
probe::script([vec![hover(1, &a)], vec![changed(&a, 2, &v2)], vec![cancel]]);
assert!(!session.batch(vec![created(&tree.path.join("z/new.sv"))]), "no shutdown");
assert!(probe::unarrived().is_empty(), "all three landed mid-scan");
assert_eq!(buffer(&session, &a), v2, "applied mid-scan, ahead of the held hover");
let held: Vec<bool> = session.server.held.iter().map(changes_state_of).collect();
assert_eq!(held, [false, false], "the hover and its cancel, nothing else");
settle(&mut session);
let answers = session.answers();
assert_eq!(answers.len(), 1, "{answers:#?}");
assert!(
answers[0]
.response_result
.as_ref()
.is_err_and(|e| e.code == lsp_server::ErrorCode::RequestCanceled as i32),
"the late cancel was honoured: {answers:#?}"
);
}
fn changes_state_of(message: &Message) -> bool {
super::super::batch::changes_state(message)
}
#[test]
fn a_rescans_trigger_alone_in_its_burst_still_lets_newer_changes_apply_at_once() {
// The rule holds a notification only when something *older* is waiting.
// With nothing behind the watcher event and nothing held, a change
// drained mid-rescan is applied where it lands — so a burst of watcher
// events during a rescan is still coalesced into exactly one more scan.
let tree = ordering_tree("ordercoalesce");
let (mut session, a) = with_a_open(&tree);
let v2 = format!("{A_TEXT}// v2\n");
probe::script([
vec![changed(&a, 2, &v2)],
vec![created(&tree.path.join("z/x1.sv"))],
vec![created(&tree.path.join("z/x2.sv"))],
]);
deliver(&mut session, vec![created(&tree.path.join("z/new.sv"))]);
assert_eq!(buffer(&session, &a), v2);
let ends = session.drain().into_iter().filter_map(progress_step).filter(|(s, _)| *s == "end");
assert_eq!(ends.count(), 2, "the rescan, and one more for both watcher events");
}
/// The session the startup-scan tests below start: `a/a.sv` opened in the
/// client's opening burst, so the scan leads with folder `a`, and `later`
/// scripted to arrive once that folder is in.
fn startup_with(tree: &Tree, later: Vec<Message>) -> Session {
let a = path_to_uri(&tree.path.join("a/a.sv")).expect("uri");
let _ = probe::take_counts();
// The head is `a/a.sv` alone; three interleave points is well past it.
probe::script([Vec::new(), Vec::new(), later]);
Session::started_behind(
vec![tree.path.clone()],
watching_progress(),
wide_ish(),
Vec::new(),
vec![opened(&a, A_TEXT)],
)
}
/// Where the response to `id` sits among `said`, and where the bar's end.
fn answered_before_the_end(said: &[Message], id: i32) -> bool {
let (ended, answered) = super::scan::positions(said, id);
matches!((answered, ended), (Some(answered), Some(ended)) if answered < ended)
}
#[test]
fn a_request_ahead_of_a_didopen_mid_startup_is_answered_and_the_drain_runs_once() {
// QA Q1: `[request, didOpen(B)]` during the startup scan. The `didOpen`
// used to be read off the batch *before* it was applied, which held the
// request with the `didOpen` unapplied behind it — and the next file
// handed the same batch back, forced a publish, and held it again, at
// every file to the end of the scan (~300 s on OpenTitan).
let tree = ordering_tree("orderq1");
let a = path_to_uri(&tree.path.join("a/a.sv")).expect("uri");
let b = path_to_uri(&tree.path.join("b/b.sv")).expect("uri");
let tokens_b = ask(
8,
SemanticTokensFullRequest::METHOD,
serde_json::json!({ "textDocument": { "uri": b } }),
);
let later = vec![hover(7, &a), opened(&b, "module bmod;\nendmodule\n"), tokens_b];
let session = startup_with(&tree, later);
let probe::Counts { points, handed_back, .. } = probe::take_counts();
let _control = startup_with(&tree, Vec::new());
let unloaded = probe::take_counts().points;
let said = session.drain();
assert!(answered_before_the_end(&said, 7), "the request ahead of the didOpen: {said:#?}");
assert!(answered_before_the_end(&said, 8), "and the one behind it, mid-scan");
assert!(session.server.held.is_empty(), "nothing is left held");
assert!(handed_back <= 1, "one hand-back for one didOpen, not one per file: {handed_back}");
assert_eq!(points, unloaded, "as many interleave points as the scan with nothing sent");
}
#[test]
fn a_request_behind_a_didopen_mid_startup_still_waits_for_the_buffer_it_names() {
// The ordering the old flag existed for is kept: a request *behind* the
// `didOpen` sees the buffer, and the work list ordered round it.
let tree = ordering_tree("orderq1behind");
let b = path_to_uri(&tree.path.join("b/b.sv")).expect("uri");
let symbols_b =
ask(9, DocumentSymbolRequest::METHOD, serde_json::json!({ "textDocument": { "uri": b } }));
let session = startup_with(&tree, vec![opened(&b, "module bmod;\nendmodule\n"), symbols_b]);
let said = session.drain();
assert!(answered_before_the_end(&said, 9), "answered mid-scan: {said:#?}");
let answer = said.iter().find_map(|m| match m {
Message::Response(r) if r.id == RequestId::from(9) => r.response_result.clone().ok(),
_ => None,
});
let names: Vec<String> = answer
.and_then(|v| v.as_array().cloned())
.unwrap_or_default()
.iter()
.filter_map(|s| s["name"].as_str().map(str::to_string))
.collect();
assert_eq!(names, ["bmod"], "answered off the buffer the didOpen installed");
}
+3 -11
View File
@@ -389,18 +389,10 @@ impl Workspace {
// The walk names its inputs as strings; every directory here came
// from a `file:` URI, which cannot carry a non-UTF-8 path.
let Some(input) = root.to_str() else { continue };
// A broken `lucisv.toml` must not stop the server from indexing: an
// index that excludes nothing is a far better failure than a
// server that comes up empty. The error is reported when the user
// formats a file in this tree (`format::settings_for`).
// A broken `lucisv.toml` excludes nothing, and the client's
// `lucisv.exclude` is appended to it — see `walk_excludes`.
let configuring = trace.now();
let mut exclude =
discovery.for_dir(root).unwrap_or_default().exclude.unwrap_or_default();
// The client's `lucisv.exclude` is *appended*, never substituted —
// the CLI appends a config's excludes to `--exclude` the same way,
// and a setting that silently dropped a checked-in exclude would
// put vendored code back in the index for one user only.
exclude.extend(self.client.exclude.iter().cloned());
let exclude = self.walk_excludes(&mut discovery, root);
ScanTrace::add(&mut trace.config_ms, configuring);
// `.gitignore` is always honoured: it is the CLI's default, and an
// editor has no `--no-gitignore` to type. An unreadable directory
+230 -75
View File
@@ -1,96 +1,232 @@
//! Re-indexing one saved file the index already holds, patching every
//! table rather than rebuilding it — the cheap path a `didSave` takes
//! before falling back to a whole rescan.
//! before falling back to a whole rescan — and doing only the work the
//! file's change can reach (`docs/features/localized-reindex/README.md`).
use std::path::Path;
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use lucisv_core::walk::dir_id;
use vlog_semantic::FileFacts;
use super::Workspace;
use crate::scan_trace::ScanTrace;
/// What [`Workspace::update_one_file`] did.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OneFile {
/// The index does not hold the file; the caller owes a whole rebuild.
NotHeld,
/// The file's record is the one the index already held — the watcher's
/// echo of a save, or a save that changed nothing the index records — so
/// nothing derived from the index moved and no other buffer's answer can
/// have either.
Unchanged,
/// The index moved, and every open buffer's overlay was refreshed.
Changed,
}
impl Workspace {
/// [`Workspace::update_one_file`], for a test that only asks whether the
/// cheap path was taken.
#[cfg(test)]
pub fn update_one(&mut self, path: &Path) -> bool {
self.update_one_file(path) != OneFile::NotHeld
}
/// Rebuild the index for **one** file, leaving every other file's
/// contribution exactly as it is. Reports whether it could.
/// contribution exactly as it is, and say what moved.
///
/// `false` means the caller must fall back to [`Workspace::rebuild_index`]:
/// the file is not one this index already holds, which is the one case the
/// cheap path cannot settle. A file appearing changes which *other* files
/// exist as far as the include graph is concerned (a `` `include`` that had
/// nothing to resolve to now has something), and answering that takes a
/// walk — so the rule is simply "a file the index already holds".
/// [`OneFile::NotHeld`] means the caller must fall back to
/// [`Workspace::rebuild_index`]: the file is not one this index already
/// holds, which the cheap path settles only for an open buffer older than
/// the last whole scan ([`Workspace::add_open_buffer`]). A file appearing
/// changes which *other* files exist as far as the include graph is
/// concerned (a `` `include`` that had nothing to resolve to now has
/// something), and answering that takes a walk.
///
/// The four pieces of state a rebuild produces, and what happens to each:
///
/// * **the workspace index** — [`WorkspaceIndex::update_file`] /
/// * **the workspace index** — [`WorkspaceIndex::update_facts`] /
/// [`WorkspaceIndex::remove_file`], which promise the index a whole
/// rebuild over the same file set would have produced;
/// * **the completion tables** — the two index-derived ones re-derived, the
/// word table patched by this file's words alone;
/// * **the include graph** — this file's edges re-scanned, the known-file
/// and folded-spelling tables re-learned from the index's list;
/// * **every open buffer's overlay** — refreshed, exactly as a rebuild
/// refreshes it, because any of them may resolve into the file that moved.
/// rebuild over the same file set would have produced, and say when the
/// record did not move at all;
/// * **the completion tables** — the word table patched by this file's
/// words, and the two index-derived ones re-derived for the names this
/// file declared or declares, only when it now declares something
/// different ([`FileFacts::declares_the_same`]);
/// * **the include graph** — this file's edges re-scanned and re-spelled;
/// nothing else in it depends on one file's text;
/// * **every open buffer's overlay** — refreshed when the index moved,
/// because any of them may resolve into the file that moved.
///
/// The text is chosen by `collect_sources`'s rules, for one path: an open
/// buffer beats disk and is never capped; a walked file over
/// `lucisv.index.maxFileSize`, one that has been deleted, and one that
/// cannot be read are all "this file is not in the index any more".
pub fn update_one(&mut self, path: &Path) -> bool {
if !self.index.files().iter().any(|held| held == path) {
return false;
///
/// [`WorkspaceIndex::update_facts`]: vlog_semantic::WorkspaceIndex::update_facts
/// [`WorkspaceIndex::remove_file`]: vlog_semantic::WorkspaceIndex::remove_file
pub fn update_one_file(&mut self, path: &Path) -> OneFile {
if self.index.file_id(path).is_none() {
return self.add_open_buffer(path);
}
// Re-indexing one file *is* the claim that its bytes moved.
self.forget_view(path);
match self.current_text(path) {
Some(text) => {
// The same rule a whole rebuild follows: when the text came
// from an open buffer, that buffer's finished analysis is the
// facts and the words, and neither is derived from the text a
// second time. `current_text` answers with a buffer's text only
// when that buffer is not on the large-file fast path, so the
// analysis found here is a real one.
match self.analysis_of(path) {
Some((facts, words)) => {
self.index.update_facts(facts);
self.candidates.update_words(&self.index, path, words);
}
None => {
self.index.update_file(path.to_path_buf(), &text);
// The words come back out of the record the update
// just wrote, so the file is lexed once rather than
// twice (`FACTS_FORMAT` 13). A path the index somehow
// does not hold falls back to lexing, which is what
// this line always did.
match self.index.facts_for(path).map(|facts| facts.words().to_vec()) {
Some(words) => self.candidates.update_words(&self.index, path, words),
None => self.candidates.update_file(&self.index, path, &text),
}
}
}
self.includes.update_file(path, &text, self.index.files());
// Written through here too, so an hour of saves is an hour of
// work the next session does not repeat. The record is the
// one the update just made — no second parse — and it is
// keyed by the text it was made from, which is the buffer's
// when a buffer beat disk. That record is simply never hit
// again if the file on disk says something else.
// A save is the other thing that asks the store something, so
// it opens a re-open a scan deferred rather than writing into
// the store the previous rescan left in hand ([`StoreOpen`]).
self.open_store(&mut ScanTrace::default());
if let Some(facts) = self.index.facts_for(path) {
self.cache.record(facts, &text);
}
}
None => {
self.index.remove_file(path);
self.candidates.remove_file(&self.index, path);
self.includes.remove_file(path, self.index.files());
}
let Some(text) = self.current_text(path) else {
self.remove_one(path);
return OneFile::Changed;
};
// The same rule a whole rebuild follows: when the text came from an
// open buffer, that buffer's finished analysis is the facts and the
// words, and neither is derived from the text a second time.
// `current_text` answers with a buffer's text only when that buffer is
// not on the large-file fast path, so the analysis found here is a
// real one. Otherwise the file is parsed once, and its words come back
// out of the record (`FACTS_FORMAT` 13).
let (facts, words) = self.analysis_of(path).unwrap_or_else(|| {
let facts = FileFacts::of(path.to_path_buf(), &text);
let words = facts.words().to_vec();
(facts, words)
});
let declared = self.declared_by_either(path, &facts);
let moved = self.index.update_facts(facts);
// The include lines are not in the record — `` `include "a.svh"`` and
// `` `include <a.svh>`` can read the same to it — so they are
// re-scanned whatever the record said.
self.includes.update_held(path, &text);
self.write_through(path, &text);
if !moved {
return OneFile::Unchanged;
}
self.candidates.set_file_words(path, words);
if let Some((symbols, macros)) = declared {
let symbols: HashSet<&str> = symbols.iter().map(String::as_str).collect();
let macros: HashSet<&str> = macros.iter().map(String::as_str).collect();
self.candidates.refresh_names(&self.index, &symbols, &macros);
}
self.refresh_overlays();
OneFile::Changed
}
/// The half of [`Workspace::update_one_file`] for a file the index does
/// not hold, which it can settle only for an open buffer — one opened
/// after the last whole scan took its work list, from outside the
/// filelist or under an `exclude`, which a rebuild would take in because
/// every open buffer is taken in.
///
/// What a rebuild would re-read besides the buffer is every other file's
/// `` `include``s, and the only ones the file's arrival can answer
/// differently are those whose last component could be its name — so those
/// are re-resolved ([`IncludeGraph::refresh_naming`]), from the lines the
/// graph holds, against the disk as it is now. No witness of *when* the
/// file appeared is needed, and none is trusted: a birth time was, until
/// QA showed `mv`, `cp -p` and `tar x` set it back (F3).
///
/// The index is merged whole (every id after the new one moves), which
/// is in memory and reads nothing.
///
/// [`IncludeGraph::refresh_naming`]: crate::includes::IncludeGraph::refresh_naming
fn add_open_buffer(&mut self, path: &Path) -> OneFile {
let Some((facts, words)) = self.analysis_of(path) else { return OneFile::NotHeld };
let Some(text) = self.current_text(path) else { return OneFile::NotHeld };
if self.holds_another_spelling_of(path) {
// A rebuild would take the buffer's spelling *instead of* the
// held one (`discover.rs`'s `Aliased`), which is not an add.
return OneFile::NotHeld;
}
let (symbols, macros) = facts.declared_names();
let symbols: HashSet<String> = symbols.into_iter().map(str::to_string).collect();
let macros: HashSet<String> = macros.into_iter().map(str::to_string).collect();
self.index.update_facts(facts);
self.candidates.set_file_words(path, words);
let symbols: HashSet<&str> = symbols.iter().map(String::as_str).collect();
let macros: HashSet<&str> = macros.iter().map(String::as_str).collect();
self.candidates.refresh_names(&self.index, &symbols, &macros);
self.includes.add_known(path);
self.includes.update_held(path, &text);
self.includes.refresh_naming(path);
self.write_through(path, &text);
self.refresh_overlays();
OneFile::Changed
}
/// Whether the index holds the file at `path` under another name — a
/// directory alias — by the test the scan's own overlay applies: the same
/// file name, then the same `(dev, ino)`.
fn holds_another_spelling_of(&self, path: &Path) -> bool {
let Some(id) = dir_id(path) else { return false };
let named = |held: &&PathBuf| held.file_name() == path.file_name();
// By reference: the id is `Copy` on unix and an owned path elsewhere.
self.index.files().iter().filter(named).any(|held| dir_id(held).as_ref() == Some(&id))
}
/// The half of [`Workspace::update_one_file`] for a held file that is
/// gone, capped or unreadable. The files whose `` `include``s could name
/// it are re-resolved, because their lines resolve against the disk and a
/// deleted file is no longer there to find.
fn remove_one(&mut self, path: &Path) {
self.index.remove_file(path);
self.candidates.remove_file(&self.index, path);
self.includes.remove_file(path, self.index.files());
self.includes.refresh_naming(path);
self.refresh_overlays();
}
/// Files appeared, vanished or moved at `paths`, wherever they are: the
/// include lines that could name any of them are re-resolved, in one pass.
/// The whole of what such an event owes the graph for a file the index
/// does not hold.
pub fn refresh_includes_naming(&mut self, paths: &[PathBuf]) {
self.includes.refresh_naming_all(paths);
}
/// The names the held record and `facts` put in the completion tables'
/// listings, both records' together — or `None` when the two declare the
/// same things ([`FileFacts::declares_the_same`]) and no listing can move.
fn declared_by_either(
&self,
path: &Path,
facts: &FileFacts,
) -> Option<(HashSet<String>, HashSet<String>)> {
let held = self.index.facts_for(path)?;
if held.declares_the_same(facts) {
return None;
}
let mut symbols: HashSet<String> = HashSet::new();
let mut macros: HashSet<String> = HashSet::new();
for record in [held, facts] {
let (names, defines) = record.declared_names();
symbols.extend(names.into_iter().map(str::to_string));
macros.extend(defines.into_iter().map(str::to_string));
}
Some((symbols, macros))
}
/// Write the file's record through to the persistent store, so an hour of
/// saves is an hour of work the next session does not repeat. The record
/// is the one the update just made — no second parse — and it is keyed by
/// the text it was made from, which is the buffer's when a buffer beat
/// disk; that record is simply never hit again if the file on disk says
/// something else. A save is the other thing that asks the store
/// something, so it opens a re-open a scan deferred rather than writing
/// into the store the previous rescan left in hand ([`StoreOpen`]).
///
/// [`StoreOpen`]: super::StoreOpen
fn write_through(&mut self, path: &Path, text: &str) {
self.open_store(&mut ScanTrace::default());
if let Some(facts) = self.index.facts_for(path) {
self.cache.record(facts, text);
}
}
/// Re-resolve every open buffer's cross-file references against the index
/// as it now stands, exactly as a rebuild does.
fn refresh_overlays(&mut self) {
for doc in self.docs.values_mut() {
doc.refresh_overlay(&self.index);
}
true
}
/// [`Workspace::update_one`], then a whole rebuild over the same
@@ -99,20 +235,39 @@ impl Workspace {
///
/// It is the incremental path's whole claim, checked rather than argued:
/// the index's fingerprint (ids, disambiguation order, member tables,
/// edges, define counts) and the completion word table, which is the one
/// piece of derived state that is patched rather than re-derived. The
/// workspace is left holding the *rebuilt* index, which is the same index,
/// so a test may keep using it.
/// edges, define counts, postings and who read what), the completion
/// tables and the include graph. The workspace is left holding the
/// *rebuilt* index, which is the same index, so a test may keep using it.
#[cfg(test)]
pub fn update_one_checked(&mut self, path: &Path) -> bool {
if !self.update_one(path) {
return false;
}
let index = self.index.fingerprint();
let words = self.candidates.words("").to_vec();
let before = self.derived_fingerprint();
self.rebuild_index();
assert_eq!(index, self.index.fingerprint(), "incremental index != rebuilt index");
assert_eq!(words, self.candidates.words(""), "incremental words != rebuilt words");
assert_eq!(before, self.derived_fingerprint(), "incremental state != rebuilt state");
true
}
/// Everything a rebuild derives from the sources, rendered for comparison:
/// the index, the completion tables, the include graph and every open
/// buffer's cross-file answers.
#[cfg(test)]
pub fn derived_fingerprint(&self) -> String {
let mut docs: Vec<(&lsp_types::Uri, &super::Document)> = self.docs.iter().collect();
docs.sort_by_key(|(uri, _)| uri.as_str());
let overlays: Vec<String> = docs
.iter()
.map(|(uri, doc)| {
format!("{} {:?}", uri.as_str(), doc.external.iter().collect::<Vec<_>>())
})
.collect();
format!(
"{}\n{}\n{}\n{}",
self.index.fingerprint(),
self.candidates.fingerprint(),
self.includes.fingerprint(),
overlays.join("\n")
)
}
}
+3
View File
@@ -36,13 +36,16 @@ mod scan;
mod scope;
mod sources;
mod views;
mod watched;
#[cfg(test)]
pub use document::mixed_buffer;
pub use document::{first_token_from, first_token_reaching, Document};
pub use incremental::OneFile;
pub use port_grace::PortGrace;
pub use scan::{IndexEvent, Scan};
pub use views::FileView;
pub use watched::Watched;
/// How many `workspace/symbol` hits are returned. Each one costs a file read
/// to turn its byte span into a line, so an unbounded answer to the empty
@@ -25,6 +25,7 @@ mod large_file;
mod lazy_read;
mod open_buffers;
mod persistence;
mod reindex_perf;
mod settings;
mod size_cap;
mod views;
@@ -0,0 +1,206 @@
//! What a save and a keystroke cost the index at OpenTitan scale — the
//! measurements behind `docs/features/localized-reindex/README.md`.
//!
//! Every test here is `#[ignore]`d and asserts nothing but its premises; run
//! them in release, one at a time, through the guard:
//!
//! `tools/guard.sh -- cargo test --release -p lucisv_server reindex_perf -- --ignored --nocapture --test-threads=1`
//!
//! The tree is `$LUCISV_OPENTITAN` or `~/.cache/lucisv-opentitan-full/hw`;
//! without it every probe says so and returns.
use std::time::{Duration, Instant};
use vlog_semantic::{FileId, SymbolKind};
use super::*;
/// The OpenTitan `hw` tree, when this machine has one.
pub(super) fn opentitan() -> Option<PathBuf> {
let root = std::env::var_os("LUCISV_OPENTITAN").map(PathBuf::from).or_else(|| {
std::env::var_os("HOME")
.map(|home| PathBuf::from(home).join(".cache/lucisv-opentitan-full/hw"))
})?;
root.is_dir().then_some(root)
}
/// A workspace over the whole OpenTitan tree, with `open` buffers open.
fn opentitan_workspace(root: &Path, open: &[&str]) -> Workspace {
let mut ws = Workspace::default();
ws.set_client_settings(wide(ClientSettings::default()));
ws.open_whole_workspace(vec![root.to_path_buf()]);
for rel in open {
let path = root.join(rel);
let text = fs::read_to_string(&path).expect("the probe's files are on disk");
ws.set_document(crate::uri::path_to_uri(&path).expect("uri"), text);
}
ws
}
fn median(mut runs: Vec<Duration>) -> Duration {
runs.sort();
runs[runs.len() / 2]
}
/// The edits a save is measured after: each is applied to the buffer, then
/// `update_one` runs, then the buffer is put back and updated again.
fn edits(text: &str) -> Vec<(&'static str, String)> {
let body = text.rfind("endmodule").or_else(|| text.rfind("endpackage")).unwrap_or(text.len());
let first = text.find('\n').map_or(0, |at| at + 1);
vec![
("no change (the watcher's echo of a save)", text.to_string()),
("comment appended", format!("{text}\n// an edit\n")),
(
"local signal added",
format!("{} logic probe_local_q;\n{}", &text[..body], &text[body..]),
),
("comment above everything", format!("{}// an edit\n{}", &text[..first], &text[first..])),
]
}
const TARGETS: [&str; 5] = [
"ip/uart/rtl/uart_tx.sv",
"ip/prim_generic/rtl/prim_flop.sv",
"ip/uart/rtl/uart_reg_pkg.sv",
"ip/prim/rtl/prim_assert.sv",
"top_earlgrey/rtl/autogen/top_earlgrey.sv",
];
#[test]
#[ignore = "perf measurement over OpenTitan — see docs/features/localized-reindex/README.md"]
fn what_one_saved_file_costs_the_index_at_opentitan_scale() {
let Some(root) = opentitan() else {
eprintln!("no OpenTitan tree — skipping");
return;
};
let mut ws = opentitan_workspace(&root, &TARGETS);
assert!(ws.index().files().len() > 3_000, "premise: the whole tree is indexed");
for rel in TARGETS {
let path = root.join(rel);
let uri = crate::uri::path_to_uri(&path).expect("uri");
let text = fs::read_to_string(&path).expect("on disk");
for (what, edited) in edits(&text) {
let mut runs = Vec::new();
for _ in 0..5 {
ws.set_document(uri.clone(), edited.clone());
let started = Instant::now();
assert!(ws.update_one(&path), "premise: a held file");
runs.push(started.elapsed());
ws.set_document(uri.clone(), text.clone());
ws.update_one(&path);
}
eprintln!("update_one {rel}, {what}: median {:?}", median(runs));
}
}
}
#[test]
#[ignore = "perf measurement over OpenTitan — see docs/features/localized-reindex/README.md"]
fn what_the_mention_census_costs_a_keystroke_at_opentitan_scale() {
// The three census rules ask `mentioned_outside` once per candidate
// declaration; every net and variable a file declares is the upper bound
// of what one lint pass over that file can ask.
let Some(root) = opentitan() else {
eprintln!("no OpenTitan tree — skipping");
return;
};
let ws = opentitan_workspace(&root, &[]);
let index = ws.index();
let (mut calls, mut total, mut worst) = (0usize, Duration::ZERO, (Duration::ZERO, 0, None));
for (id, path) in index.files().iter().enumerate() {
let Ok(text) = fs::read_to_string(path) else { continue };
let doc = Document::new(Some(path.clone()), text, index);
let names: Vec<&str> = doc
.semantics
.symbols()
.iter()
.filter(|s| matches!(s.kind, SymbolKind::Net | SymbolKind::Var))
.map(|s| s.name.as_str())
.collect();
let started = Instant::now();
for name in &names {
std::hint::black_box(index.mentioned_outside(name, Some(FileId(id as u32))));
}
let took = started.elapsed();
calls += names.len();
total += took;
if took > worst.0 {
worst = (took, names.len(), Some(path.clone()));
}
}
eprintln!(
"mention census over {} files: {calls} questions, {:?} each on average; \
worst file {:?} asks {} for {:?}",
index.files().len(),
total / calls.max(1) as u32,
worst.2,
worst.1,
worst.0
);
}
#[test]
#[ignore = "perf measurement over OpenTitan — see docs/features/localized-reindex/README.md"]
fn what_the_census_adds_to_a_real_lint_pass_at_opentitan_scale() {
// The bound above is every declaration; this is what the rules really
// ask: one buffer's whole lint pass against the indexed workspace, and the
// same pass with no workspace (no census at all), file by file.
let Some(root) = opentitan() else {
eprintln!("no OpenTitan tree — skipping");
return;
};
let ws = opentitan_workspace(&root, &[]);
let alone = Workspace::default();
let mut added: Vec<(Duration, Duration, PathBuf)> = Vec::new();
for path in ws.index().files() {
let Ok(text) = fs::read_to_string(path) else { continue };
// A fresh document per pass: a document remembers its last lint
// pass (`lint_snapshot`), and a remembered pass costs nothing.
let lint = |within: &Workspace| {
let doc = Document::new(Some(path.clone()), text.clone(), ws.index());
let started = Instant::now();
let run = crate::lint::LintRun::for_document(within, &doc);
std::hint::black_box(crate::diagnostics::all_in(&doc, &run));
started.elapsed()
};
let with = median((0..3).map(|_| lint(&ws)).collect());
let without = median((0..3).map(|_| lint(&alone)).collect());
added.push((with.saturating_sub(without), with, path.clone()));
}
added.sort();
let total: Duration = added.iter().map(|(d, _, _)| *d).sum();
eprintln!(
"census share of a lint pass over {} files: {:?} on average",
added.len(),
total / added.len().max(1) as u32
);
for (delta, with, path) in added.iter().rev().take(5) {
eprintln!(" {delta:?} of {with:?} in {}", path.display());
}
}
#[test]
#[ignore = "perf measurement over OpenTitan — see docs/features/localized-reindex/README.md"]
fn what_the_readers_table_holds_at_opentitan_scale() {
// The memory the narrowing costs: one key per table entry any file's
// resolution read, and one file id per reader of it — read back out of
// the fingerprint, which renders the table line by line.
let Some(root) = opentitan() else {
eprintln!("no OpenTitan tree — skipping");
return;
};
let ws = opentitan_workspace(&root, &[]);
let fingerprint = ws.index().fingerprint();
let lines: Vec<&str> = fingerprint.lines().filter(|line| line.starts_with("read ")).collect();
let readers: usize = lines.iter().map(|line| line.matches(',').count() + 1).sum();
let key_bytes: usize =
lines.iter().filter_map(|line| line.split(' ').nth(2)).map(str::len).sum();
eprintln!(
"readers table over {} files: {} keys ({} KiB of key text), {} reader entries ({} KiB of ids)",
ws.index().files().len(),
lines.len(),
key_bytes / 1024,
readers,
readers * 4 / 1024
);
}
+156
View File
@@ -0,0 +1,156 @@
//! What one path a file watcher named is to the index: a file it holds
//! (perhaps under another spelling), a file the scope provably cannot take,
//! or neither — which only a rescan can settle
//! (`docs/features/localized-reindex/README.md`).
//!
//! A watcher event for a `.sv` the index does not hold used to be a whole
//! rescan, progress bar and all, every time: a generated file under a
//! gitignored build directory, a file outside the folder scope or the
//! filelist, or a held file reported by its real path under a symlinked root.
//! Only the last kind of file can change what the index says, and none of
//! them needs the walk to find that out.
use std::fs;
use std::path::{Path, PathBuf};
use lucisv_core::config::Discovery;
use lucisv_core::walk::collect_files_below;
use super::discover::{oversize, Found};
use super::Workspace;
/// What a watched path is to the index.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Watched {
/// A file the index holds, by the spelling it holds it under — or an
/// open buffer it does not hold yet, which a rebuild would take in and the
/// one-file path adds (QA F4).
Held(PathBuf),
/// A file no scan of the scope in force would index. Nothing to do for
/// the index.
Outside,
/// A file the scope may take and the index does not hold: a new file, or
/// one the cap kept out until now. Only a rescan can say.
Unknown,
}
impl Workspace {
/// What `path` is to the index. Errs towards [`Watched::Unknown`]: a
/// wasted rescan costs time, a skipped one would cost a stale index.
pub fn watched(&self, path: &Path) -> Watched {
if let Some(held) = self.held_spelling(path) {
return Watched::Held(held);
}
if self.docs.values().any(|doc| doc.path.as_deref() == Some(path)) {
return Watched::Held(path.to_path_buf());
}
match self.scope_could_take(path) {
true => Watched::Unknown,
false => Watched::Outside,
}
}
/// The spelling the index holds `path` under: `path` itself, or the same
/// file reached through a scope directory's other name — a symlinked root,
/// or a different case on a case-insensitive disk. Resolved through the
/// directories the scope is anchored at, so it costs a handful of
/// `canonicalize` calls rather than one per held file.
fn held_spelling(&self, path: &Path) -> Option<PathBuf> {
let holds = |path: &Path| self.index.file_id(path).is_some();
if holds(path) {
return Some(path.to_path_buf());
}
let real = canonical(path)?;
let mut anchors: Vec<PathBuf> = self.roots.clone();
anchors.extend(self.scope_dirs());
anchors.into_iter().find_map(|anchor| {
let rest = real.strip_prefix(fs::canonicalize(&anchor).ok()?).ok()?;
let spelled = anchor.join(rest);
holds(&spelled).then_some(spelled)
})
}
/// Whether a scan of the scope in force could index `path` — `false` only
/// when it provably could not: a filelist that does not list it, or a
/// walk of the scope's directories that does not find it or finds it over
/// `lucisv.index.maxFileSize`. The walk is `lucisv_core`'s own, rooted
/// where the scan's is, so `.gitignore`, `exclude` and the config's
/// excludes rule it out exactly as they rule it out of a scan.
fn scope_could_take(&self, path: &Path) -> bool {
if let Some(list) = self.filelist_path() {
// An unreadable filelist sends the scan to the rungs below, and
// so it sends this.
if let Ok(list) = lucisv_core::filelist::read(&list) {
return list.files.iter().any(|listed| same_file(listed, path));
}
}
let Some(dir) = path.parent() else { return true };
let dirs = match self.walks_the_workspace() {
true => self.roots.clone(),
false => self.scope_dirs(),
};
if self.roots.is_empty() && self.client.index_scope_depth == 0 {
// The flat read of a rootless session: siblings only.
return dirs.iter().any(|scope| scope == dir);
}
dirs.iter()
.filter(|scope| path.starts_with(scope))
.any(|scope| self.walk_finds(scope, path))
}
/// Whether a walk of `scope` finds `path` under its cap.
fn walk_finds(&self, scope: &Path, path: &Path) -> bool {
let Some(dir) = path.parent() else { return true };
let excludes = self.walk_excludes(&mut Discovery::new(true), scope);
let mut found = None;
let take = &mut |file: PathBuf, len| {
if file == path {
found = Some(Found { path: file, len });
}
};
if collect_files_below(scope, dir, &excludes, true, take, &mut |_| {}).is_err() {
// The directory is gone or unreadable: nothing in it can be read
// either, and the scan would say the same.
return false;
}
found.is_some_and(|found| oversize(&found, self.client.max_file_size, &mut 0).is_none())
}
/// The exclude patterns a walk rooted at `dir` applies: the governing
/// config's, then the client's `lucisv.exclude`. *Appended*, never
/// substituted — the CLI appends a config's excludes to `--exclude` the
/// same way, and a setting that silently dropped a checked-in exclude
/// would put vendored code back in the index for one user only.
pub(super) fn walk_excludes(&self, discovery: &mut Discovery, dir: &Path) -> Vec<String> {
// A broken `lucisv.toml` must not stop the server from indexing: an
// index that excludes nothing is a far better failure than a server
// that comes up empty. The error is reported when the user formats a
// file in this tree (`format::settings_for`).
let mut exclude = discovery.for_dir(dir).unwrap_or_default().exclude.unwrap_or_default();
exclude.extend(self.client.exclude.iter().cloned());
exclude
}
}
/// Whether two spellings name one file: equal, or equal once resolved. The
/// names are compared first, case-insensitively, so a filelist of thousands
/// costs a resolution only for the entries that could be the one.
fn same_file(listed: &Path, path: &Path) -> bool {
if listed == path {
return true;
}
let name = |p: &Path| p.file_name().map(|n| n.to_string_lossy().to_lowercase());
name(listed) == name(path)
&& canonical(listed).is_some()
&& canonical(listed) == canonical(path)
}
/// `path` with every symlink resolved and, on a case-insensitive disk, every
/// component in the case the disk holds it in. A file that is gone resolves
/// through its directory, so a deletion can still be matched.
fn canonical(path: &Path) -> Option<PathBuf> {
fs::canonicalize(path).ok().or_else(|| {
let real = fs::canonicalize(path.parent()?).ok()?;
Some(real.join(path.file_name()?))
})
}
+20 -13
View File
@@ -112,16 +112,16 @@ pub fn touches_scope(changes: &[FileEvent], filelist: Option<&Path>) -> bool {
.any(|path| watched(&path, filelist))
}
/// The one file an event named, when it named exactly one and that one is not
/// the filelist.
/// Every path an event named that the index reads, each once and in order —
/// or `None` when one of them is the filelist, whose change moves the whole
/// scope and is a rebuild by definition. A client is free to send `Changed`
/// and `Created` for one file, and that is still one file.
///
/// The gate on the incremental rescan path (`server.rs`'s `reindex_one`): a
/// checkout fills this list, and a list of one is the case a single file's
/// contribution can be replaced in place. The filelist is excluded because a
/// change to it moves the whole scope, which is a rebuild by definition. An
/// event naming the same path twice — a client is free to send `Changed` and
/// `Created` for one file — is still one file.
pub fn one_scope_file(changes: &[FileEvent], filelist: Option<&Path>) -> Option<PathBuf> {
/// What `server/index.rs`'s `reindex_watched` sorts into held, outside and
/// unknown files (`docs/features/localized-reindex/README.md`); until
/// 2026-11-19 this was `one_scope_file`, which gave up on any list longer
/// than one.
pub fn scope_files(changes: &[FileEvent], filelist: Option<&Path>) -> Option<Vec<PathBuf>> {
let mut named: Vec<PathBuf> = changes
.iter()
.filter_map(|change| uri_to_path(&change.uri))
@@ -129,10 +129,17 @@ pub fn one_scope_file(changes: &[FileEvent], filelist: Option<&Path>) -> Option<
.collect();
named.sort();
named.dedup();
match named.as_slice() {
[only] if Some(only.as_path()) != filelist => Some(only.clone()),
_ => None,
}
(!named.iter().any(|path| Some(path.as_path()) == filelist)).then_some(named)
}
/// Whether an event names a `lucisv.toml` (either spelling) — a change to
/// which moves the scope's excludes and filelist and the lint configuration
/// together. The names are `lucisv_core::config::NAMES`, the CLI's own.
pub fn names_a_config(changes: &[FileEvent]) -> bool {
changes.iter().filter_map(|change| uri_to_path(&change.uri)).any(|path| {
let name = path.file_name().and_then(|n| n.to_str());
name.is_some_and(|n| lucisv_core::config::NAMES.contains(&n))
})
}
/// Whether one path is something the index reads: a source file, or the
+59 -13
View File
@@ -4873,6 +4873,12 @@ fn a_save_asks_a_capable_client_to_refresh_its_code_lenses_over_the_wire() {
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(LENS_SUB).expect("json")
)),
// An edit before the save: a save that moved nothing the index
// records refreshes nothing (localized-reindex, 2026-11-19).
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":2}},"contentChanges":[{{"text":{}}}]}}}}"#,
serde_json::to_string(&format!("{LENS_SUB}module lens_extra;\nendmodule\n")).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didSave","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
)),
@@ -8468,11 +8474,19 @@ fn indexed_neighbours(dir: &Path, files: usize) {
/// leave the request behind it waiting.
///
/// **An upper bound, not a benchmark, and a debug-build one.** `cargo test`
/// builds unoptimized, where one tolerant parse of 2 000 lines is ~53 ms all
/// by itself — measured on this machine, and stable to a millisecond across
/// runs. So the 200 ms here is that floor with room for a loaded CI box, not
/// the ≤ 25 ms §46 asked for: **that figure is a release number**, and the
/// release binary opens the same buffer in 2–4 ms.
/// builds unoptimized, where one tolerant parse of 2 000 lines is 11–53 ms
/// all by itself on the dev machines and 50–70 ms on the Linux runner. The
/// ≤ 25 ms §46 asked for is **a release number** (the release binary opens
/// the same buffer in 2–4 ms), so it is not what is asserted here.
///
/// **The budget is measured, not written down.** A fixed 200 ms was that
/// floor with room on the dev machine, and nothing anywhere else: the Linux
/// CI box (4 CPUs, under the whole suite) took 205 ms for its *best* of
/// three. So the floor is measured in this process, next to every open: one
/// tolerant parse of the same buffer, through the same parser in the same
/// build. The open must cost at most [`OPEN_OVER_PARSE`] of those — which is
/// what "bounded" means for an open that must parse its buffer anyway — and
/// a machine or a moment that is slower slows both.
///
/// **What this test does and does not catch.** It catches an open that starts
/// doing something *unbounded* — the shape §46 fixed. It cannot catch the
@@ -8484,15 +8498,16 @@ fn indexed_neighbours(dir: &Path, files: usize) {
/// which counts the questions instead of timing them
/// (`docs/features/didopen-cost/README.md`).
///
/// Best of three distinct buffers: the first open of a process pays cold code
/// paths that have nothing to do with the buffer, and a wall-clock assertion
/// that cannot tolerate one scheduling hiccup is a flake, not a pin.
/// Best of [`OPEN_ROUNDS`] distinct buffers, and the best of as many parses:
/// the first open of a process pays cold code paths that have nothing to do
/// with the buffer, and a wall-clock assertion that cannot tolerate one
/// scheduling hiccup is a flake, not a pin.
#[test]
fn opening_a_two_thousand_line_buffer_does_not_delay_the_request_behind_it() {
let dir = temp_dir("didopen_cost");
indexed_neighbours(&dir, 40);
let mut generated = Vec::new();
for n in 0..3 {
for n in 0..OPEN_ROUNDS {
let name = format!("gen{n}");
// The generator the perf tables use: a thousand declarations, every
// one declared, driven and read — the cheap case for the *findings*
@@ -8508,20 +8523,51 @@ fn opening_a_two_thousand_line_buffer_does_not_delay_the_request_behind_it() {
let warm = format!("file://{}", dir.join("pkg0.sv").display());
open_then_hover(&mut live, 10, &warm, "package pkg0;\n localparam int K0 = 0;\nendpackage\n");
let mut best = std::time::Duration::MAX;
// Each round times the floor, then the open, so load that comes and goes
// lands on both kinds of sample alike.
let (mut open, mut parse) = (std::time::Duration::MAX, std::time::Duration::MAX);
for (n, (path, text)) in generated.iter().enumerate() {
parse = parse.min(one_tolerant_parse(text));
let uri = format!("file://{}", path.display());
best = best.min(open_then_hover(&mut live, 20 + n as u32, &uri, text));
open = open.min(open_then_hover(&mut live, 20 + n as u32, &uri, text));
}
live.finish();
let _ = std::fs::remove_dir_all(&dir);
let ratio = open.as_secs_f64() / parse.as_secs_f64();
eprintln!("didOpen of 2 000 lines: best open {open:?}, best parse {parse:?}, {ratio:.2}x");
assert!(
best <= std::time::Duration::from_millis(200),
"a didOpen of a 2 000-line buffer delayed the next request by {best:?}"
ratio <= OPEN_OVER_PARSE,
"a didOpen of a 2 000-line buffer delayed the next request by {open:?}, \
{ratio:.2}x one parse of it ({parse:?}); the budget is {OPEN_OVER_PARSE}x"
);
}
/// Distinct 2 000-line buffers opened, and parses timed, by the test above.
const OPEN_ROUNDS: usize = 5;
/// How many parses of its own buffer an open may cost, request included.
///
/// Measured 2026-11-19 (best of five each, debug build): the open costs
/// 2.5–3.2 parses on the dev machine, quiet or under 36 busy loops on its 18
/// CPUs; 2.3–3.6 on the 4-CPU Linux runner when quiet; and 2.5–3.3 there
/// under 8 busy loops, where the open itself took ~1 s (the old fixed
/// 200 ms would have failed every run there). The ratio holds still while the wall
/// clock moves 6x. Six is ~1.7x over the worst ratio seen; an open made to
/// parse its buffer four extra times fails it (6.9x on the dev machine,
/// where the old 200 ms passed that at 84 ms), three extra times is ~5.9x
/// (`docs/features/linux-test-portability/README.md`, round 2).
const OPEN_OVER_PARSE: f64 = 6.0;
/// The wall clock of one tolerant parse of `text`, in this process.
fn one_tolerant_parse(text: &str) -> std::time::Duration {
let started = std::time::Instant::now();
let (file, _) = vlog_parser::parse_source_tolerant(text);
let took = started.elapsed();
std::hint::black_box(file);
took
}
/// The other half of §46's contract: the request after an open is answered
/// from the **buffer**, not from what is on disk.
///
@@ -0,0 +1,152 @@
//! Which files' references read which merged-table keys: recorded while a
//! file's references are resolved, and asked when an update moves a key, so
//! that only the files that read it are resolved again
//! (`docs/features/localized-reindex/README.md`).
//!
//! The recording is a thread-local switch rather than a parameter because the
//! resolution walk (`external.rs`, `reexport.rs`, `hierarchy.rs`) is shared
//! with every request-time caller through a dozen functions that take a
//! `&WorkspaceIndex`; threading a recorder through all of them would change
//! every signature for the one caller that wants it. The lookups note what
//! they read with [`note`], which costs one thread-local check when nothing is
//! recording — every request — and the index's own pass turns it on with
//! [`recording`]. `lint_trace` and `scan_trace` use the same shape.
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use super::FileId;
/// A merged table a resolution reads, named by what its key is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Table {
/// `units`, by file-scope name.
Unit = 0,
/// `members`, by the unit that exports the member.
Container = 1,
/// `hier_members`, by the unit that declares the member.
Hier = 2,
/// `bases`, by the class whose base it records.
Base = 3,
/// `reexports`, by the exporting package.
Exporter = 4,
}
const TABLES: [Table; 5] =
[Table::Unit, Table::Container, Table::Hier, Table::Base, Table::Exporter];
/// The keys one resolution pass read, table by table — misses included: a
/// lookup that found nothing is exactly the one a new declaration answers.
#[derive(Debug, Default)]
pub(super) struct Reads {
keys: [HashSet<String>; 5],
}
thread_local! {
static RECORDING: RefCell<Option<Reads>> = const { RefCell::new(None) };
}
/// Note that the resolution running on this thread read `table` under `key`.
pub(super) fn note(table: Table, key: &str) {
RECORDING.with(|cell| {
if let Some(reads) = cell.borrow_mut().as_mut() {
let keys = &mut reads.keys[table as usize];
if !keys.contains(key) {
keys.insert(key.to_string());
}
}
});
}
/// Run `body` and say every key it read. Nests: an outer recording is put
/// back afterwards, untouched by the inner one.
pub(super) fn recording<R>(body: impl FnOnce() -> R) -> (R, Reads) {
let outer = RECORDING.with(|cell| cell.replace(Some(Reads::default())));
let out = body();
let reads = RECORDING.with(|cell| cell.replace(outer)).unwrap_or_default();
(out, reads)
}
/// Key → the files whose last resolution read it, each list sorted and
/// without repeats.
///
/// It holds exactly what resolving every file against the tables as they
/// stand would record, which is what makes "the files that read a moved key"
/// a sound answer to "whose postings can have moved": a file that read no
/// moved key read only values that did not change, so its resolution — a pure
/// function of its own facts and those values — did not change either.
#[derive(Debug, Clone, Default)]
pub(super) struct Dependents {
readers: [HashMap<String, Vec<FileId>>; 5],
}
impl Dependents {
/// Forget every reader, for a rebuild from the records.
pub(super) fn clear(&mut self) {
self.readers.iter_mut().for_each(HashMap::clear);
}
/// Record that `file` read everything in `reads`.
pub(super) fn add(&mut self, file: FileId, reads: Reads) {
for (table, keys) in reads.keys.into_iter().enumerate() {
for key in keys {
let files = self.readers[table].entry(key).or_default();
// A whole rebuild adds files in id order, so the common case
// is a push; an update re-adds a few files in the middle.
match files.last() {
Some(last) if *last >= file => {
if let Err(at) = files.binary_search(&file) {
files.insert(at, file);
}
}
_ => files.push(file),
}
}
}
}
/// Take back what [`Dependents::add`] recorded for `file`.
pub(super) fn remove(&mut self, file: FileId, reads: &Reads) {
for (table, keys) in reads.keys.iter().enumerate() {
for key in keys {
let Some(files) = self.readers[table].get_mut(key) else { continue };
if let Ok(at) = files.binary_search(&file) {
files.remove(at);
}
if files.is_empty() {
self.readers[table].remove(key);
}
}
}
}
/// Take back everything recorded for every file `gone` says, by one pass
/// over the whole table.
pub(super) fn remove_all(&mut self, gone: &dyn Fn(FileId) -> bool) {
for readers in &mut self.readers {
readers.retain(|_, files| {
files.retain(|file| !gone(*file));
!files.is_empty()
});
}
}
/// The files that read `table` under `key`.
pub(super) fn readers(&self, table: Table, key: &str) -> &[FileId] {
self.readers[table as usize].get(key).map_or(&[], Vec::as_slice)
}
/// Every reader, one sorted line per key — for the index's fingerprint, so
/// the equivalence tests hold this table to a rebuild's as well.
pub(super) fn render(&self, out: &mut String) {
for table in TABLES {
let mut keys: Vec<(&String, &Vec<FileId>)> =
self.readers[table as usize].iter().collect();
keys.sort();
for (key, files) in keys {
let ids: Vec<u32> = files.iter().map(|file| file.0).collect();
out.push_str(&format!("read {table:?} {key} by {ids:?}\n"));
}
}
}
}
+23 -4
View File
@@ -13,6 +13,7 @@ use vlog_parser::defines::{Define, DefineTable};
use crate::model::{Surface, SymbolKind};
use super::dependents::{note, Table};
use super::external::{fold_path, last_segment, member_chain, own_members};
use super::hierarchy;
use super::record::{FileFacts, ReferenceFact};
@@ -67,6 +68,7 @@ impl WorkspaceIndex {
/// in disambiguation order (by file path, then by position in the file).
/// More than one means the workspace really does declare the name twice.
pub fn units(&self, name: &str) -> &[Def] {
note(Table::Unit, name);
self.units.get(name).map_or(&[], Vec::as_slice)
}
@@ -80,6 +82,7 @@ impl WorkspaceIndex {
/// hierarchical path may name besides is
/// [`WorkspaceIndex::member_in`]'s business ([`Surface`]).
pub fn member(&self, unit: &str, member: &str) -> &[Def] {
note(Table::Container, unit);
self.members.get(unit).and_then(|m| m.get(member)).map_or(&[], Vec::as_slice)
}
@@ -95,6 +98,7 @@ impl WorkspaceIndex {
/// — the completion list behind `p::` and behind an instantiation's
/// connection list.
pub fn members_of(&self, unit: &str) -> impl Iterator<Item = (&str, &[Def])> {
note(Table::Container, unit);
self.members
.get(unit)
.into_iter()
@@ -108,6 +112,7 @@ impl WorkspaceIndex {
&self,
unit: &str,
) -> impl Iterator<Item = (&str, &[Def])> {
note(Table::Hier, unit);
self.hier_members
.get(unit)
.into_iter()
@@ -116,6 +121,7 @@ impl WorkspaceIndex {
/// [`WorkspaceIndex::member`] on the hierarchical-only half alone.
pub(super) fn hierarchical_member(&self, unit: &str, member: &str) -> &[Def] {
note(Table::Hier, unit);
self.hier_members.get(unit).and_then(|m| m.get(member)).map_or(&[], Vec::as_slice)
}
@@ -187,6 +193,7 @@ impl WorkspaceIndex {
/// edges `reexport`'s two walks follow. Empty for every unit that
/// re-exports nothing, which is all but a handful in any workspace.
pub(super) fn reexports(&self, unit: &str) -> &[Reexport] {
note(Table::Exporter, unit);
self.reexports.get(unit).map_or(&[], Vec::as_slice)
}
@@ -262,6 +269,7 @@ impl WorkspaceIndex {
/// declare — which is what ends the chase in
/// [`resolve_external`](super::resolve_external).
pub fn base_of(&self, name: &str) -> Option<&str> {
note(Table::Base, name);
self.bases.get(name).map(String::as_str)
}
@@ -315,7 +323,7 @@ impl WorkspaceIndex {
/// Whether at least one use could name `def` or another declaration equally.
pub fn references_are_ambiguous(&self, def: &Def) -> bool {
self.ambiguous_references.contains(&DefinitionKey::of(def))
self.ambiguous_references.contains_key(&DefinitionKey::of(def))
}
/// Every file holding a use spelled `name` that this index had to look
@@ -429,15 +437,26 @@ impl WorkspaceIndex {
/// sorted by name and is not truncated, so a caller with a result limit
/// applies its own.
pub fn workspace_symbols(&self, query: &str) -> Vec<WorkspaceSymbol<'_>> {
self.symbols_where(|name| contains_ignore_ascii_case(name, query))
}
/// [`WorkspaceIndex::workspace_symbols`] for exactly these names, in the
/// same order — what a table built from the whole listing re-derives for
/// the names one update touched (`docs/features/localized-reindex`).
pub fn symbols_named(&self, names: &HashSet<&str>) -> Vec<WorkspaceSymbol<'_>> {
self.symbols_where(|name| names.contains(name))
}
fn symbols_where(&self, keep: impl Fn(&str) -> bool) -> Vec<WorkspaceSymbol<'_>> {
let mut out = Vec::new();
for (name, defs) in &self.units {
if contains_ignore_ascii_case(name, query) {
if keep(name) {
out.extend(defs.iter().map(|def| WorkspaceSymbol { name, container: None, def }));
}
}
for (unit, members) in &self.members {
for (name, defs) in members {
if contains_ignore_ascii_case(name, query) {
if keep(name) {
out.extend(defs.iter().map(|def| WorkspaceSymbol {
name,
container: Some(unit),
@@ -626,7 +645,7 @@ impl IndexBuilder {
facts: self.files,
..WorkspaceIndex::default()
};
index.merge(None);
index.merge();
index
}
}
+16 -3
View File
@@ -24,21 +24,26 @@
//! two member surfaces holds what, and the reads that take a
//! [`crate::Surface`] instead of assuming one.
mod dependents;
mod external;
mod hierarchy;
mod index;
mod path_units;
mod record;
mod reexport;
mod references;
mod replace;
mod update;
pub use external::{resolve_external, Definition, ExternalResolutions, ExternalTarget};
pub use index::{index_order, IndexBuilder};
pub use record::FileFacts;
use dependents::Dependents;
pub(crate) use record::{Decl, ReferenceFact, SiteFact};
pub(crate) use reexport::Reexport;
use std::collections::{BTreeMap, HashSet};
use std::collections::{BTreeMap, HashMap};
use std::path::PathBuf;
use vlog_parser::span::TextRange;
@@ -326,10 +331,18 @@ pub struct WorkspaceIndex {
macro_definitions: BTreeMap<String, Vec<(FileId, usize)>>,
/// Declaration → every unambiguous use, in file then source order.
reference_sites: BTreeMap<DefinitionKey, Vec<ReferenceSite>>,
/// Declarations touched by at least one ambiguous external reference.
/// Declarations touched by at least one ambiguous external reference,
/// each with how many such references touch it — counted so one file's
/// references can be taken back without re-resolving the rest.
/// Find-references refuses those rather than assigning the use to one of
/// several equally plausible declarations.
ambiguous_references: HashSet<DefinitionKey>,
ambiguous_references: HashMap<DefinitionKey, u32>,
/// The same, by the file whose references contributed them — so a sweep
/// can take a file's share back without re-resolving it.
ambiguous_by_file: HashMap<FileId, Vec<DefinitionKey>>,
/// Which files' references read which table keys — what lets an update
/// re-resolve only the files that read a key it moved.
dependents: Dependents,
}
/// The headline numbers of a built index.
+53 -1
View File
@@ -11,7 +11,7 @@ use std::collections::HashSet;
use std::path::{Path, PathBuf};
use vlog_parser::ast::SourceFile;
use vlog_parser::defines::{collect_defines, DefineTable};
use vlog_parser::defines::{collect_defines, Define, DefineKind, DefineTable};
use vlog_parser::span::TextRange;
use vlog_parser::token::Token;
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex};
@@ -271,6 +271,58 @@ impl FileFacts {
pub fn path(&self) -> &Path {
&self.path
}
/// Whether `other` declares what this record declares, as far as
/// [`WorkspaceIndex::workspace_symbols`](super::WorkspaceIndex::workspace_symbols)
/// and the `` `define`` table can see — the same units and
/// connection-surface members by name, kind and owning unit, in the order
/// that listing sorts them, and the same `` `define``s with the same
/// parameters in the same order — wherever in the file they now sit.
///
/// The completion tables are built from exactly those two views, so an
/// edit that moved no such declaration (a body change, a comment, a new
/// local signal) leaves them as they were and need not re-derive them
/// (`docs/features/localized-reindex/README.md`).
pub fn declares_the_same(&self, other: &FileFacts) -> bool {
let define = |define: &Define| (define.name.clone(), define.params.clone());
let defines = |facts: &FileFacts| -> Vec<(String, Option<Vec<String>>)> {
let entries = facts.defines.entries().iter();
entries.filter(|d| d.kind == DefineKind::Define).map(define).collect()
};
self.symbol_view() == other.symbol_view() && defines(self) == defines(other)
}
/// Every name this file puts in the workspace-symbol listing — its units
/// and its connection-surface members — and every macro it `` `define``s:
/// what a table built from those listings re-derives when the file moves.
pub fn declared_names(&self) -> (HashSet<&str>, HashSet<&str>) {
let units = self.units.iter().map(|decl| decl.name.as_str());
let members = self.members.iter().filter(|(_, decl)| decl.surface == Surface::Connection);
let symbols = units.chain(members.map(|(_, decl)| decl.name.as_str())).collect();
let entries = self.defines.entries().iter();
let macros =
entries.filter(|d| d.kind == DefineKind::Define).map(|d| d.name.as_str()).collect();
(symbols, macros)
}
/// This file's workspace symbols, spans aside: `(name, container, kind)`
/// in `workspace_symbols`' order, which within one file is by name, then
/// container, then position.
fn symbol_view(&self) -> Vec<(&str, Option<&str>, SymbolKind)> {
let units = self
.units
.iter()
.map(|decl| (decl.name.as_str(), None, decl.name_span.start, decl.kind));
let members =
self.members.iter().filter(|(_, decl)| decl.surface == Surface::Connection).map(
|(unit, decl)| {
(decl.name.as_str(), Some(unit.as_str()), decl.name_span.start, decl.kind)
},
);
let mut view: Vec<_> = units.chain(members).collect();
view.sort_by(|a, b| (a.0, a.1, a.2).cmp(&(b.0, b.1, b.2)));
view.into_iter().map(|(name, container, _, kind)| (name, container, kind)).collect()
}
}
/// One file's two identifier censuses, both read off the same token stream:
@@ -0,0 +1,176 @@
//! The declaration → use postings, built from every file's reference facts or
//! re-done for a few files: what an update calls once it knows which files
//! read a key it moved (`docs/features/localized-reindex/README.md`).
use std::collections::HashSet;
use super::dependents::{recording, Reads};
use super::external::{resolve_fact, ExternalTarget};
use super::record::ReferenceFact;
use super::{DefinitionKey, FileId, ReferenceSite, WorkspaceIndex};
/// What one reference puts into the postings.
enum Posting {
/// One use of one declaration.
Site(DefinitionKey, ReferenceSite),
/// A use that could name any of these declarations equally.
Ambiguous(Vec<DefinitionKey>),
}
impl WorkspaceIndex {
/// Rebuild every posting, the ambiguity counts and the readers table from
/// every file's facts.
pub(super) fn merge_references(&mut self) {
self.reference_sites.clear();
self.ambiguous_references.clear();
self.ambiguous_by_file.clear();
self.dependents.clear();
let every: Vec<FileId> = (0..self.facts.len()).map(|id| FileId(id as u32)).collect();
self.resolve_files(&every);
}
/// Put `files`' postings in, resolved against the tables as they stand.
///
/// `files` is in id order, and each file's postings go in after every
/// posting of a lower-numbered file and before every higher one — the
/// order [`WorkspaceIndex::merge_references`] produces by visiting the
/// files in that order, so a few files re-done in place give the lists a
/// whole rebuild gives.
pub(super) fn resolve_files(&mut self, files: &[FileId]) {
for &file in files {
let (postings, reads) = self.postings_of(file);
for posting in postings {
match posting {
Posting::Site(key, site) => {
let sites = self.reference_sites.entry(key).or_default();
let at = sites.partition_point(|held| held.file <= file);
sites.insert(at, site);
}
Posting::Ambiguous(keys) => {
for key in keys {
*self.ambiguous_references.entry(key).or_default() += 1;
self.ambiguous_by_file.entry(file).or_default().push(key);
}
}
}
}
self.dependents.add(file, reads);
}
}
/// Take `files`' postings out again.
///
/// Re-resolving them against the tables as they stand finds exactly what
/// [`WorkspaceIndex::resolve_files`] put in, because those are the tables
/// it was put in against — every update keeps the postings equal to a
/// resolution of every file over the current tables, and resolution is a
/// pure function of the two. So nothing per file has to be remembered to
/// undo it.
pub(super) fn unresolve_files(&mut self, files: &[FileId]) {
let leaving: HashSet<FileId> = files.iter().copied().collect();
let mut touched: HashSet<DefinitionKey> = HashSet::new();
for &file in files {
let (postings, reads) = self.postings_of(file);
for posting in postings {
match posting {
Posting::Site(key, _) => {
touched.insert(key);
}
Posting::Ambiguous(keys) => {
keys.iter().for_each(|key| self.forget_ambiguity(key))
}
}
}
self.dependents.remove(file, &reads);
self.ambiguous_by_file.remove(&file);
}
for key in touched {
let Some(sites) = self.reference_sites.get_mut(&key) else { continue };
sites.retain(|site| !leaving.contains(&site.file));
if sites.is_empty() {
self.reference_sites.remove(&key);
}
}
}
/// [`WorkspaceIndex::unresolve_files`] by one pass over the postings
/// rather than by re-resolving `files`: every site a file put in is
/// dropped wherever it is, its ambiguity taken back from what it is
/// recorded to have contributed, and its id struck from every reader
/// list. Linear in the postings, not in `files` — the cheaper way out when
/// `files` hold a large share of every reference (a package most of the
/// tree imports), where re-resolving them would be most of a whole merge.
pub(super) fn unresolve_by_sweep(&mut self, files: &[FileId]) {
let mut leaving = vec![false; self.facts.len()];
for file in files {
if let Some(slot) = leaving.get_mut(file.0 as usize) {
*slot = true;
}
}
let gone = |file: FileId| leaving.get(file.0 as usize).copied().unwrap_or(false);
self.reference_sites.retain(|_, sites| {
sites.retain(|site| !gone(site.file));
!sites.is_empty()
});
for file in files {
for key in self.ambiguous_by_file.remove(file).unwrap_or_default() {
self.forget_ambiguity(&key);
}
}
self.dependents.remove_all(&gone);
}
/// How many references `files` hold, against how many every file holds —
/// the two numbers that choose between the two ways out.
pub(super) fn reference_share(&self, files: &[FileId]) -> (usize, usize) {
let count =
|file: &FileId| self.facts.get(file.0 as usize).map_or(0, |f| f.references.len());
let total = self.facts.iter().map(|facts| facts.references.len()).sum();
(files.iter().map(count).sum(), total)
}
fn forget_ambiguity(&mut self, key: &DefinitionKey) {
let Some(count) = self.ambiguous_references.get_mut(key) else { return };
*count -= 1;
if *count == 0 {
self.ambiguous_references.remove(key);
}
}
/// One file's postings, and every table key resolving them read.
fn postings_of(&self, file: FileId) -> (Vec<Posting>, Reads) {
let Some(facts) = self.facts.get(file.0 as usize) else {
return (Vec::new(), Reads::default());
};
recording(|| {
let mut out = Vec::new();
for reference in &facts.references {
let site = ReferenceSite { file, name_span: reference.occurrence() };
match reference {
ReferenceFact::Local { definition, .. } => {
let key = DefinitionKey {
file,
name_start: definition.start,
name_end: definition.end,
};
out.push(Posting::Site(key, site));
}
ReferenceFact::External { name, base, paths, surface, .. } => {
match resolve_fact(self, name, base.as_deref(), paths, *surface) {
ExternalTarget::Resolved(def) => {
out.push(Posting::Site(DefinitionKey::of(&def), site));
}
ExternalTarget::Ambiguous(defs) => {
out.push(Posting::Ambiguous(
defs.iter().map(DefinitionKey::of).collect(),
));
}
ExternalTarget::StillUnresolved => {}
}
}
}
}
out
})
}
}
@@ -0,0 +1,345 @@
//! Replacing one held file's record with a different one, doing only the
//! work the change can reach: the tables re-merged for the keys either record
//! names, from the files that contribute to them, and the postings re-done for
//! the files whose resolution read a key whose value really moved
//! (`docs/features/localized-reindex/README.md`).
use std::collections::{BTreeMap, BTreeSet, HashSet};
use crate::model::SymbolKind;
use super::dependents::Table;
use super::record::FileFacts;
use super::reexport::Reexport;
use super::update::Affected;
use super::{Def, FileId, WorkspaceIndex};
/// One unit's members: member name → every declaration of it.
type MemberTable = BTreeMap<String, Vec<Def>>;
/// The entries an update names in the four tables resolution reads, held
/// aside: the old tables' entries, swapped back in for as long as it takes to
/// take the readers' old postings out.
#[derive(Default)]
struct Entries {
units: Vec<(String, Option<Vec<Def>>)>,
members: Vec<(String, Option<MemberTable>)>,
hier_members: Vec<(String, Option<MemberTable>)>,
reexports: Vec<(String, Option<Vec<Reexport>>)>,
/// The whole class → base table, when either record has a class with a
/// base — the only way it can move, and it is rebuilt whole when it does.
bases: Option<BTreeMap<String, String>>,
}
/// The keys whose value, as resolution reads it, an update changed.
#[derive(Default)]
struct Moved {
keys: Vec<(Table, String)>,
}
/// One declaration as resolution reads it — see [`seen`].
type Seen<'a> = (FileId, u32, u32, SymbolKind, Option<&'a str>);
/// What resolution reads of one declaration: which declaration it is (the
/// posting key is its file and name span), what kind, and the type a member
/// hop continues through. A declaration whose body grew moved its
/// `decl_span` and its lines, and no posting can tell.
fn seen(defs: &[Def]) -> Vec<Seen<'_>> {
defs.iter()
.map(|d| (d.file, d.name_span.start, d.name_span.end, d.kind, d.type_name.as_deref()))
.collect()
}
fn seen_members(members: Option<&MemberTable>) -> Vec<(&str, Vec<Seen<'_>>)> {
members.into_iter().flatten().map(|(name, defs)| (name.as_str(), seen(defs))).collect()
}
impl WorkspaceIndex {
/// Replace the record at `at` with a different one.
///
/// * The **tables** are re-merged for the keys either record names
/// ([`Affected`]), from the records of the files that contribute to those
/// keys — the same loop a whole merge runs, over fewer files.
/// * The **postings** are re-done for this file and for every file whose
/// last resolution read a key whose value moved
/// ([`Dependents`](super::dependents::Dependents)): taken out against the
/// old tables, put back against the new ones.
///
/// A file that read no moved key read only values this replacement did not
/// change, so its postings are already what a rebuild would give. "Moved"
/// is judged as resolution sees a value ([`seen`]): an edit inside a
/// module's body moves the module's extent and the declarations after the
/// edit, but not the module's name, so the files that only instantiate it
/// are left alone.
///
/// Returns the files whose postings were re-done, for the tests that pin
/// the narrowing itself.
pub(super) fn replace_facts(&mut self, at: usize, facts: FileFacts) -> Vec<FileId> {
let file = FileId(at as u32);
let mut affected = Affected::of(&self.facts[at]);
affected.add(&facts);
let contributors = self.contributors(&affected, at);
let mut old = self.take_entries(&affected);
let mut old_facts = std::mem::replace(&mut self.facts[at], facts);
self.merge_tables(Some(&affected), contributors.as_deref());
if old.bases.is_some() {
self.merge_bases();
}
let readers = self.readers_of(&self.moved(&old, &affected), file);
// The readers' old postings out: re-resolved against the tables and
// the record they were made from, which costs what putting them back
// costs — or, when the readers hold more than an eighth of every
// reference, swept out in one pass over the postings, which is then
// the cheaper of the two (QA F5: every importer of a widely imported
// package re-resolved twice was slower than the old whole merge).
let (share, total) = self.reference_share(&readers);
if sweeps(share, total) {
self.unresolve_by_sweep(&readers);
} else {
self.swap_entries(&mut old);
std::mem::swap(&mut self.facts[at], &mut old_facts);
self.unresolve_files(&readers);
self.swap_entries(&mut old);
std::mem::swap(&mut self.facts[at], &mut old_facts);
}
self.resolve_files(&readers);
readers
}
/// Take the entries `affected` names out of the tables resolution reads.
fn take_entries(&mut self, affected: &Affected) -> Entries {
Entries {
units: take(&mut self.units, &affected.units),
members: take(&mut self.members, &affected.containers),
hier_members: take(&mut self.hier_members, &affected.containers),
reexports: take(&mut self.reexports, &affected.exporters),
bases: (!affected.classes.is_empty()).then(|| std::mem::take(&mut self.bases)),
}
}
/// Exchange the held entries with the tables' — twice is no change.
fn swap_entries(&mut self, held: &mut Entries) {
swap_in(&mut self.units, &mut held.units);
swap_in(&mut self.members, &mut held.members);
swap_in(&mut self.hier_members, &mut held.hier_members);
swap_in(&mut self.reexports, &mut held.reexports);
if let Some(bases) = held.bases.as_mut() {
std::mem::swap(&mut self.bases, bases);
}
}
/// Every key whose value, as resolution reads it, differs between the
/// held entries and the tables now.
fn moved(&self, old: &Entries, affected: &Affected) -> Moved {
let mut out = Moved::default();
for (name, defs) in &old.units {
let now = self.units.get(name).map_or(&[][..], Vec::as_slice);
if seen(defs.as_deref().unwrap_or_default()) != seen(now) {
out.keys.push((Table::Unit, name.clone()));
}
}
for (table, held, now) in [
(Table::Container, &old.members, &self.members),
(Table::Hier, &old.hier_members, &self.hier_members),
] {
for (unit, members) in held {
if seen_members(members.as_ref()) != seen_members(now.get(unit)) {
out.keys.push((table, unit.clone()));
}
}
}
for (exporter, entries) in &old.reexports {
if entries.as_ref() != self.reexports.get(exporter) {
out.keys.push((Table::Exporter, exporter.clone()));
}
}
if let Some(bases) = &old.bases {
for class in &affected.classes {
if bases.get(class) != self.bases.get(class) {
out.keys.push((Table::Base, class.clone()));
}
}
}
out
}
/// This file and every file whose postings read a moved key, in id order.
fn readers_of(&self, moved: &Moved, file: FileId) -> Vec<FileId> {
let mut out: BTreeSet<FileId> = BTreeSet::from([file]);
for (table, key) in &moved.keys {
out.extend(self.dependents.readers(*table, key));
}
out.into_iter().collect()
}
/// Every file holding a record under a key in `affected`, in id order —
/// read off the merged tables, whose entries say which file each came
/// from. `None` means every file: a re-export entry does not carry its
/// file, so a record that names an exporter takes the whole loop.
fn contributors(&self, affected: &Affected, at: usize) -> Option<Vec<usize>> {
if !affected.exporters.is_empty() {
return None;
}
let mut out: BTreeSet<usize> = BTreeSet::from([at]);
let id = |file: FileId| file.0 as usize;
for name in &affected.units {
out.extend(self.units.get(name).into_iter().flatten().map(|def| id(def.file)));
}
for unit in &affected.containers {
for table in [&self.members, &self.hier_members] {
let defs = table.get(unit).into_iter().flat_map(|m| m.values()).flatten();
out.extend(defs.map(|def| id(def.file)));
}
}
for module in &affected.modules {
let edges = self.instantiations.get(module).into_iter().flatten();
out.extend(edges.map(|edge| id(edge.file)));
}
for base in &affected.bases {
let edges = self.subclasses.get(base).into_iter().flatten();
out.extend(edges.map(|edge| id(edge.file)));
}
for name in &affected.macros {
let defines = self.macro_definitions.get(name).into_iter().flatten();
out.extend(defines.map(|(file, _)| id(*file)));
}
Some(out.into_iter().collect())
}
}
/// Below this many references in the whole index a sweep never pays: the
/// re-resolution of a few small files is already sub-millisecond.
const SWEEP_FLOOR: usize = 20_000;
/// Whether the readers' old postings go out by a sweep ([`sweeps`]'s rule:
/// they hold more than an eighth of every reference in an index big enough
/// for that to cost something) or by re-resolution.
fn sweeps(share: usize, total: usize) -> bool {
#[cfg(test)]
if let Some(forced) = tests::FORCE_SWEEP.with(std::cell::Cell::get) {
return forced;
}
total >= SWEEP_FLOOR && share * 8 > total
}
/// Remove the entries under `keys`, keeping each with its key — an absent
/// one as `None`, so swapping it back in removes what is there.
fn take<V>(table: &mut BTreeMap<String, V>, keys: &HashSet<String>) -> Vec<(String, Option<V>)> {
keys.iter().map(|key| (key.clone(), table.remove(key))).collect()
}
/// Exchange each held entry with the table's entry under the same key, an
/// absent entry on either side included.
fn swap_in<V>(table: &mut BTreeMap<String, V>, held: &mut [(String, Option<V>)]) {
for (key, value) in held {
let current = table.remove(key.as_str());
if let Some(value) = value.take() {
table.insert(key.clone(), value);
}
*value = current;
}
}
#[cfg(test)]
mod tests {
use std::cell::Cell;
use std::path::PathBuf;
use super::*;
thread_local! {
/// Which way out a test forces, whatever the sizes say.
pub(super) static FORCE_SWEEP: Cell<Option<bool>> = const { Cell::new(None) };
}
/// Every edit of a small chained design, each checked against a whole
/// build, with the readers' postings taken out each way in turn — the
/// sweep is otherwise taken only on trees of 20 000 references and up.
#[test]
fn both_ways_out_give_the_index_a_whole_build_gives() {
let base = [
("a.sv", "package a_pkg;\n localparam int W = 8;\nendpackage\nclass base_c;\n int m;\nendclass\n"),
("b.sv", "module leaf (input logic clk);\n logic s;\nendmodule\nclass mid_c extends base_c;\nendclass\n"),
("c.sv", "module top;\n import a_pkg::*;\n logic c;\n leaf u (.clk(c));\n initial $display(u.s, W);\nendmodule\nclass leaf_c extends mid_c;\n function void f(); m = 1; endfunction\nendclass\n"),
("d.sv", "module dup (input logic a);\nendmodule\nmodule user;\n dup i (.a(1'b0));\nendmodule\n"),
("e.sv", "module user2;\n dup j ();\nendmodule\n"),
];
let edits = [
("a.sv", "// top\npackage a_pkg;\n localparam int W = 8;\n localparam int V = 1;\nendpackage\nclass base_c;\n int n, m;\nendclass\n"),
("b.sv", "module leaf (input logic clq);\n logic s;\nendmodule\nclass mid_c extends other_c;\nendclass\n"),
("b.sv", "module leaf (input logic clq);\n logic s;\nendmodule\nmodule dup;\nendmodule\n"),
("e.sv", "// a line\nmodule user2;\n dup j ();\nendmodule\n"),
("c.sv", "module top;\n logic c;\nendmodule\n"),
];
for forced in [true, false] {
FORCE_SWEEP.with(|cell| cell.set(Some(forced)));
let mut files: Vec<(String, String)> =
base.iter().map(|(p, s)| (p.to_string(), s.to_string())).collect();
let mut index = build(&files);
for round in 0..2 {
for (path, text) in edits.iter().chain(base.iter()) {
let slot = files.iter_mut().find(|(p, _)| p == path).expect("a held file");
slot.1 = text.to_string();
index.update_file(PathBuf::from(path), text);
assert_eq!(
index.fingerprint(),
build(&files).fingerprint(),
"sweep={forced}, round {round}: `{path}`"
);
}
}
FORCE_SWEEP.with(|cell| cell.set(None));
}
}
fn build(files: &[(String, String)]) -> WorkspaceIndex {
WorkspaceIndex::build(files.iter().map(|(p, s)| (PathBuf::from(p), s.as_str())))
}
const LEAF: &str = "module leaf (input logic clk);\n logic s;\nendmodule\n";
const TOP: &str = "module top;\n logic c;\n leaf u (.clk(c));\nendmodule\n";
const TB: &str = "module tb;\n top t ();\n initial $display(t.u.s);\nendmodule\n";
/// The files an update of `leaf.sv` to `text` re-resolves, by path.
fn re_resolved(text: &str) -> Vec<String> {
let mut index = WorkspaceIndex::build([
(PathBuf::from("leaf.sv"), LEAF),
(PathBuf::from("tb.sv"), TB),
(PathBuf::from("top.sv"), TOP),
]);
let facts = FileFacts::of(PathBuf::from("leaf.sv"), text);
let files = index.replace_facts(0, facts);
files.iter().filter_map(|&file| index.path(file)).map(|p| p.display().to_string()).collect()
}
#[test]
fn a_body_edit_re_resolves_only_the_file_itself() {
// The module's name, its port and its signal keep their spans; only
// its extent and its body moved, and no posting can see either. A new
// declaration would be a new member, and the hierarchical reader
// re-resolved for it — a member table is judged whole.
let grown = "module leaf (input logic clk);\n logic s;\n assign s = clk;\nendmodule\n";
assert_eq!(re_resolved(grown), ["leaf.sv"]);
}
#[test]
fn a_port_edit_re_resolves_the_file_that_connects_to_it() {
// Same length, so the signal after it keeps its span — but the
// hierarchical path asks the connection surface before the
// hierarchical one, so it read the port table too.
let renamed = "module leaf (input logic clq);\n logic s;\nendmodule\n";
assert_eq!(re_resolved(renamed), ["leaf.sv", "tb.sv", "top.sv"]);
}
#[test]
fn a_moved_internal_signal_re_resolves_the_file_whose_path_reaches_it() {
let moved = "module leaf (input logic clk);\n logic pad;\n logic s;\nendmodule\n";
assert_eq!(re_resolved(moved), ["leaf.sv", "tb.sv"]);
}
#[test]
fn an_edit_above_everything_re_resolves_every_reader() {
let shifted = format!("// above\n{LEAF}");
assert_eq!(re_resolved(&shifted), ["leaf.sv", "tb.sv", "top.sv"]);
}
}
+135 -138
View File
@@ -4,18 +4,15 @@
//! makes that hold by construction, and the [`WorkspaceIndex::fingerprint`]
//! that proves it.
use std::collections::{BTreeMap, HashSet};
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use vlog_parser::defines::DefineKind;
use crate::model::Surface;
use super::external::{resolve_fact, ExternalTarget};
use super::record::{facts_of, FileFacts, ReferenceFact};
use super::{
DefinitionKey, FileId, InheritanceEdge, InstantiationEdge, ReferenceSite, WorkspaceIndex,
};
use super::record::{facts_of, FileFacts};
use super::{DefinitionKey, FileId, InheritanceEdge, InstantiationEdge, WorkspaceIndex};
impl WorkspaceIndex {
/// Replace one file's contribution to the index — or add the file, when
@@ -38,8 +35,13 @@ impl WorkspaceIndex {
/// remove; nothing in this workspace holds one across an update (the
/// server refreshes every overlay after it, exactly as it does after a
/// rebuild).
pub fn update_file(&mut self, path: PathBuf, src: &str) {
self.update_facts(facts_of(path, src));
///
/// Reports whether the index moved: `false` exactly when the file's new
/// record equals the one held, which is the watcher's echo of a save and a
/// save that changed nothing — the cheapest answer there is, and a sound
/// one, since an index is a function of its records.
pub fn update_file(&mut self, path: PathBuf, src: &str) -> bool {
self.update_facts(facts_of(path, src))
}
/// [`WorkspaceIndex::update_file`] for a file whose facts are already
@@ -51,26 +53,28 @@ impl WorkspaceIndex {
/// [`IndexBuilder::add_file`](super::IndexBuilder::add_file) with
/// the parse already done: same contract, same result. Whether the record
/// really describes the file is the caller's business.
pub fn update_facts(&mut self, facts: FileFacts) {
///
/// Reports whether the index moved, as [`WorkspaceIndex::update_file`]
/// does.
pub fn update_facts(&mut self, facts: FileFacts) -> bool {
let path = facts.path.clone();
match self.facts.binary_search_by(|held| held.path.cmp(&path)) {
Ok(at) if self.facts[at] == facts => return false,
// The common case — a saved file the index already holds. Only the
// names this file declared before or declares now can have moved,
// and the file list has not, so ids are untouched.
Ok(at) => {
let mut affected = Affected::of(&self.facts[at]);
affected.add(&facts);
self.facts[at] = facts;
self.merge(Some(&affected));
self.replace_facts(at, facts);
}
// A file the index did not hold: every id from here on shifts, so
// every table is rebuilt from the records. No parse, no read.
Err(at) => {
self.files.insert(at, path);
self.facts.insert(at, facts);
self.merge(None);
self.merge();
}
}
true
}
/// [`WorkspaceIndex::update_facts`] and [`WorkspaceIndex::remove_file`] for
@@ -117,7 +121,7 @@ impl WorkspaceIndex {
}
}
}
self.merge(None);
self.merge();
}
/// Drop one file from the index, reporting whether it was there.
@@ -130,7 +134,7 @@ impl WorkspaceIndex {
};
self.files.remove(at);
self.facts.remove(at);
self.merge(None);
self.merge();
true
}
@@ -185,11 +189,11 @@ impl WorkspaceIndex {
));
}
}
let mut ambiguous: Vec<DefinitionKey> = self.ambiguous_references.iter().copied().collect();
let mut ambiguous: Vec<(&DefinitionKey, &u32)> = self.ambiguous_references.iter().collect();
ambiguous.sort();
for definition in ambiguous {
for (definition, count) in ambiguous {
out.push_str(&format!(
"ambiguous-ref {}:{}..{}\n",
"ambiguous-ref {}:{}..{} x{count}\n",
definition.file.0, definition.name_start, definition.name_end
));
}
@@ -238,17 +242,36 @@ impl WorkspaceIndex {
));
}
}
// Not an answer any caller reads, but the table that decides which
// files the *next* update re-resolves: one that drifted from a
// rebuild's would be a stale posting waiting to happen.
self.dependents.render(&mut out);
out
}
/// Rebuild the merged tables from the per-file records.
/// Rebuild every merged table, the postings and the readers table from
/// the per-file records.
///
/// `affected` names the keys that may have moved; `None` means all of
/// them. Either way this is one loop over the path-sorted records pushing
/// in the order it meets them, which is the *only* place any table's order
/// is decided — so a restricted merge and a whole one agree by
/// construction, and both agree with [`IndexBuilder::finish`](super::IndexBuilder::finish).
pub(super) fn merge(&mut self, affected: Option<&Affected>) {
/// The tables are one loop over the path-sorted records pushing in the
/// order it meets them ([`WorkspaceIndex::merge_tables`]), which is the
/// *only* place any table's order is decided — so a restricted merge over
/// a few files and a whole one agree by construction, and both agree with
/// [`IndexBuilder::finish`](super::IndexBuilder::finish).
pub(super) fn merge(&mut self) {
self.merge_tables(None, None);
self.merge_bases();
// A changed declaration can change how references in any file resolve,
// even when only one file's facts moved. Re-resolving compact facts is
// one in-memory pass; no source is read or parsed.
self.merge_references();
}
/// The table half of [`WorkspaceIndex::merge`]: clear the keys `affected`
/// names (all of them for `None`) and push back every record under them,
/// visiting `files` — the files that hold such records, in id order — or
/// every file for `None`. Visiting fewer files is the same loop, because a
/// file with no record under a cleared key pushes nothing.
pub(super) fn merge_tables(&mut self, affected: Option<&Affected>, files: Option<&[usize]>) {
match affected {
None => {
self.units.clear();
@@ -281,117 +304,87 @@ impl WorkspaceIndex {
}
}
}
for (id, facts) in self.facts.iter().enumerate() {
let file = FileId(id as u32);
for decl in &facts.units {
if affected.is_some_and(|a| !a.units.contains(&decl.name)) {
continue;
}
self.units.entry(decl.name.clone()).or_default().push(decl.def(file));
}
for (unit, decl) in &facts.members {
if affected.is_some_and(|a| !a.containers.contains(unit)) {
continue;
}
// The record's own tag picks the table; the two are keyed
// alike, are cleared together above, and a caller that names
// no surface reads the connection one.
let table = match decl.surface {
Surface::Connection => &mut self.members,
Surface::Hierarchical => &mut self.hier_members,
};
table
.entry(unit.clone())
.or_default()
.entry(decl.name.clone())
.or_default()
.push(decl.def(file));
}
for (module, edge) in &facts.instantiations {
if affected.is_some_and(|a| !a.modules.contains(module)) {
continue;
}
self.instantiations.entry(module.clone()).or_default().push(InstantiationEdge {
file,
owner: edge.owner.clone(),
site_span: edge.site_span,
instances: edge.instances.clone(),
});
}
for (base, subclass) in &facts.subclasses {
if affected.is_some_and(|a| !a.bases.contains(base)) {
continue;
}
self.subclasses
.entry(base.clone())
.or_default()
.push(InheritanceEdge { file, subclass: subclass.clone() });
}
for (exporter, entry) in &facts.reexports {
if affected.is_some_and(|a| !a.exporters.contains(exporter)) {
continue;
}
self.reexports.entry(exporter.clone()).or_default().push(entry.clone());
}
for (entry, define) in facts.defines.entries().iter().enumerate() {
if define.kind != DefineKind::Define
|| affected.is_some_and(|a| !a.macros.contains(&define.name))
{
continue;
}
self.macro_definitions.entry(define.name.clone()).or_default().push((file, entry));
}
match files {
Some(files) => files.iter().for_each(|&id| self.push_records(id, affected)),
None => (0..self.facts.len()).for_each(|id| self.push_records(id, affected)),
}
// The reverse inheritance edge is rebuilt whole every time, whatever
// `affected` says: it is one entry per `extends` written anywhere (a
// few thousand on opentitan), and rebuilding it is both cheaper to
// reason about and the reason a restricted merge cannot leave it
// half-updated. First in file order wins, which is `units`' rule.
}
/// Push one file's records under the keys `affected` names (every key for
/// `None`), in the order the record holds them.
fn push_records(&mut self, id: usize, affected: Option<&Affected>) {
let file = FileId(id as u32);
let Some(facts) = self.facts.get(id) else { return };
for decl in &facts.units {
if affected.is_some_and(|a| !a.units.contains(&decl.name)) {
continue;
}
self.units.entry(decl.name.clone()).or_default().push(decl.def(file));
}
for (unit, decl) in &facts.members {
if affected.is_some_and(|a| !a.containers.contains(unit)) {
continue;
}
// The record's own tag picks the table; the two are keyed
// alike, are cleared together above, and a caller that names
// no surface reads the connection one.
let table = match decl.surface {
Surface::Connection => &mut self.members,
Surface::Hierarchical => &mut self.hier_members,
};
table
.entry(unit.clone())
.or_default()
.entry(decl.name.clone())
.or_default()
.push(decl.def(file));
}
for (module, edge) in &facts.instantiations {
if affected.is_some_and(|a| !a.modules.contains(module)) {
continue;
}
self.instantiations.entry(module.clone()).or_default().push(InstantiationEdge {
file,
owner: edge.owner.clone(),
site_span: edge.site_span,
instances: edge.instances.clone(),
});
}
for (base, subclass) in &facts.subclasses {
if affected.is_some_and(|a| !a.bases.contains(base)) {
continue;
}
self.subclasses
.entry(base.clone())
.or_default()
.push(InheritanceEdge { file, subclass: subclass.clone() });
}
for (exporter, entry) in &facts.reexports {
if affected.is_some_and(|a| !a.exporters.contains(exporter)) {
continue;
}
self.reexports.entry(exporter.clone()).or_default().push(entry.clone());
}
for (entry, define) in facts.defines.entries().iter().enumerate() {
if define.kind != DefineKind::Define
|| affected.is_some_and(|a| !a.macros.contains(&define.name))
{
continue;
}
self.macro_definitions.entry(define.name.clone()).or_default().push((file, entry));
}
}
/// The reverse inheritance edge, rebuilt whole: one entry per `extends`
/// written anywhere (a few thousand on opentitan), first in file order
/// winning, which is `units`' rule.
pub(super) fn merge_bases(&mut self) {
self.bases.clear();
for facts in &self.facts {
for (base, subclass) in &facts.subclasses {
self.bases.entry(subclass.name.clone()).or_insert_with(|| base.clone());
}
}
// A changed declaration can change how references in any file resolve,
// even when only one file's facts moved. Re-resolving compact facts is
// one in-memory pass; no source is read or parsed.
self.merge_references();
}
/// Rebuild declaration-to-occurrence postings from compact per-file facts.
fn merge_references(&mut self) {
let mut sites: BTreeMap<DefinitionKey, Vec<ReferenceSite>> = BTreeMap::new();
let mut ambiguous: HashSet<DefinitionKey> = HashSet::new();
for (id, facts) in self.facts.iter().enumerate() {
let file = FileId(id as u32);
for reference in &facts.references {
let site = ReferenceSite { file, name_span: reference.occurrence() };
match reference {
ReferenceFact::Local { definition, .. } => {
let key = DefinitionKey {
file,
name_start: definition.start,
name_end: definition.end,
};
sites.entry(key).or_default().push(site);
}
ReferenceFact::External { name, base, paths, surface, .. } => {
match resolve_fact(self, name, base.as_deref(), paths, *surface) {
ExternalTarget::Resolved(def) => {
sites.entry(DefinitionKey::of(&def)).or_default().push(site);
}
ExternalTarget::Ambiguous(defs) => {
ambiguous.extend(defs.iter().map(DefinitionKey::of));
}
ExternalTarget::StillUnresolved => {}
}
}
}
}
}
self.reference_sites = sites;
self.ambiguous_references = ambiguous;
}
}
@@ -399,33 +392,37 @@ impl WorkspaceIndex {
/// file can leave every other key alone.
#[derive(Debug, Default)]
pub(super) struct Affected {
units: HashSet<String>,
pub(super) units: HashSet<String>,
/// Keys of the `members` table — the *unit* a member is exported by, not
/// the member itself. A whole unit's sub-table is the smallest thing worth
/// rebuilding: one file adding a member to a package cannot move any other
/// package.
containers: HashSet<String>,
modules: HashSet<String>,
bases: HashSet<String>,
pub(super) containers: HashSet<String>,
pub(super) modules: HashSet<String>,
pub(super) bases: HashSet<String>,
/// Keys of the `reexports` table — the package that writes the `export`,
/// never the package it takes the name from: a file changing what `a_pkg`
/// re-exports moves `a_pkg`'s edges and no one else's.
exporters: HashSet<String>,
macros: HashSet<String>,
pub(super) exporters: HashSet<String>,
pub(super) macros: HashSet<String>,
/// Keys of the `bases` table — the *extending* class, which is what a
/// member lookup up the `extends` chain asks it by.
pub(super) classes: HashSet<String>,
}
impl Affected {
fn of(facts: &FileFacts) -> Affected {
pub(super) fn of(facts: &FileFacts) -> Affected {
let mut out = Affected::default();
out.add(facts);
out
}
fn add(&mut self, facts: &FileFacts) {
pub(super) fn add(&mut self, facts: &FileFacts) {
self.units.extend(facts.units.iter().map(|decl| decl.name.clone()));
self.containers.extend(facts.members.iter().map(|(unit, _)| unit.clone()));
self.modules.extend(facts.instantiations.iter().map(|(module, _)| module.clone()));
self.bases.extend(facts.subclasses.iter().map(|(base, _)| base.clone()));
self.classes.extend(facts.subclasses.iter().map(|(_, class)| class.name.clone()));
self.exporters.extend(facts.reexports.iter().map(|(exporter, _)| exporter.clone()));
self.macros.extend(facts.defines.entries().iter().map(|define| define.name.clone()));
}
@@ -0,0 +1,350 @@
//! The localized update's whole claim, attacked: after any sequence of
//! one-file updates, the index is the index a whole build over the same file
//! contents gives — postings, ambiguity, edges and the readers table that
//! decides which files the *next* update re-resolves included
//! (`docs/features/localized-reindex/README.md`).
//!
//! Each case is a design whose references reach across files through one of
//! the hops resolution takes — a port connection, a package import, a
//! re-export, an `extends` chain, a typedef alias, a hierarchical path through
//! instances, a qualified miss — and a sequence of edits to the file at the
//! far end of the hop, chosen so that a narrowing which forgot that hop would
//! leave a stale posting the fingerprint shows. The randomized sweep at the
//! bottom drives the same designs through seeded mutations.
use std::collections::BTreeMap;
use std::path::PathBuf;
use vlog_semantic::WorkspaceIndex;
fn build(files: &BTreeMap<String, String>) -> WorkspaceIndex {
WorkspaceIndex::build(files.iter().map(|(p, s)| (PathBuf::from(p), s.as_str())))
}
/// Apply `steps` one update at a time, checking the index against a whole
/// build after every one of them.
fn holds(initial: &[(&str, &str)], steps: &[(&str, &str)]) {
let mut files: BTreeMap<String, String> =
initial.iter().map(|(p, s)| (p.to_string(), s.to_string())).collect();
let mut index = build(&files);
for (at, (path, text)) in steps.iter().enumerate() {
files.insert(path.to_string(), text.to_string());
index.update_file(PathBuf::from(path), text);
assert_eq!(
index.fingerprint(),
build(&files).fingerprint(),
"step {at}: updating `{path}` must give the index a whole build would have"
);
}
}
const PORTS: [(&str, &str); 2] = [
("leaf.sv", "module leaf (input logic clk, output logic q);\nendmodule\n"),
("top.sv", "module top;\n logic c, d;\n leaf u_leaf (.clk(c), .q(d));\nendmodule\n"),
];
#[test]
fn a_port_connection_follows_every_edit_of_the_instantiated_module() {
holds(
&PORTS,
&[
// A body edit: the ports keep their spans, the module's extent grows.
("leaf.sv", "module leaf (input logic clk, output logic q);\n logic s;\nendmodule\n"),
// A comment above everything: every span moves.
("leaf.sv", "// moved\nmodule leaf (input logic clk, output logic q);\nendmodule\n"),
// A port renamed, then removed, then the module renamed away.
("leaf.sv", "module leaf (input logic clock, output logic q);\nendmodule\n"),
("leaf.sv", "module leaf (output logic q);\nendmodule\n"),
("leaf.sv", "module other (input logic clk, output logic q);\nendmodule\n"),
// And back, so a key that went missing comes home.
(PORTS[0].0, PORTS[0].1),
// The instantiating side moves too.
("top.sv", "module top;\n logic c, d;\n leaf u_leaf (.q(d), .clk(c));\nendmodule\n"),
],
);
}
const PACKAGES: [(&str, &str); 3] = [
("a_pkg.sv", "package a_pkg;\n localparam int W = 8;\n typedef logic [W-1:0] word_t;\nendpackage\n"),
("b_pkg.sv", "package b_pkg;\n import a_pkg::*;\n export a_pkg::*;\nendpackage\n"),
(
"user.sv",
"module user;\n import b_pkg::*;\n word_t w;\n localparam int X = W + a_pkg::W;\nendmodule\n",
),
];
#[test]
fn an_import_and_a_reexport_follow_every_edit_of_the_package_at_the_end() {
holds(
&PACKAGES,
&[
("a_pkg.sv", "package a_pkg;\n // shifted\n localparam int W = 8;\n typedef logic [W-1:0] word_t;\nendpackage\n"),
("a_pkg.sv", "package a_pkg;\n localparam int W2 = 8;\n typedef logic [7:0] word_t;\nendpackage\n"),
// The middle package stops re-exporting, then starts again.
("b_pkg.sv", "package b_pkg;\n import a_pkg::*;\nendpackage\n"),
(PACKAGES[1].0, PACKAGES[1].1),
// The package at the end renamed: every qualified use becomes a miss.
("a_pkg.sv", "package c_pkg;\n localparam int W = 8;\nendpackage\n"),
(PACKAGES[0].0, PACKAGES[0].1),
],
);
}
const CLASSES: [(&str, &str); 3] = [
("base.sv", "class base_c;\n int m;\n function void f(); endfunction\nendclass\n"),
("mid.sv", "class mid_c extends base_c;\nendclass\n"),
("leaf_c.sv", "class leaf_c extends mid_c;\n function void g();\n m = 1;\n f();\n this.m = 2;\n endfunction\nendclass\n"),
];
#[test]
fn an_inherited_member_follows_every_edit_along_the_extends_chain() {
holds(
&CLASSES,
&[
// The member two hops up moves, is renamed, comes back.
(
"base.sv",
"class base_c;\n int pad;\n int m;\n function void f(); endfunction\nendclass\n",
),
("base.sv", "class base_c;\n int n;\n function void f(); endfunction\nendclass\n"),
(CLASSES[0].0, CLASSES[0].1),
// The middle of the chain changes what it extends.
("mid.sv", "class mid_c extends other_c;\nendclass\n"),
("mid.sv", "class mid_c;\nendclass\n"),
(CLASSES[1].0, CLASSES[1].1),
// The middle class declares the member itself, shadowing the base.
("mid.sv", "class mid_c extends base_c;\n int m;\nendclass\n"),
],
);
}
const ALIASES: [(&str, &str); 3] = [
("hdr.sv", "package hdr_pkg;\n typedef struct packed { logic [7:0] addr; logic v; } hdr_t;\nendpackage\n"),
("pkt.sv", "package pkt_pkg;\n import hdr_pkg::*;\n typedef struct packed { hdr_t hdr; logic [31:0] data; } pkt_t;\nendpackage\n"),
("use.sv", "module use_it;\n import pkt_pkg::*;\n pkt_t p;\n assign p.hdr.addr = 8'h0;\nendmodule\n"),
];
#[test]
fn a_member_chain_through_struct_types_follows_every_edit_of_the_innermost_type() {
holds(
&ALIASES,
&[
("hdr.sv", "package hdr_pkg;\n typedef struct packed { logic v; logic [7:0] addr; } hdr_t;\nendpackage\n"),
("hdr.sv", "package hdr_pkg;\n typedef struct packed { logic [7:0] address; logic v; } hdr_t;\nendpackage\n"),
("pkt.sv", "package pkt_pkg;\n import hdr_pkg::*;\n typedef struct packed { logic [31:0] data; hdr_t hdr; } pkt_t;\nendpackage\n"),
(ALIASES[0].0, ALIASES[0].1),
],
);
}
#[test]
fn a_member_whose_type_alone_changes_moves_the_hop_through_it() {
// `hdr_t` and `oth_t` are the same length, so the member `hdr` keeps its
// span and only its declared type — the hop `p.hdr.addr` takes — moves.
let hdr = "package hdr_pkg;\n typedef struct packed { logic [7:0] addr; } hdr_t;\n \
typedef struct packed { logic v; logic [7:0] addr; } oth_t;\nendpackage\n";
holds(
&[("hdr.sv", hdr), ALIASES[1], ALIASES[2]],
&[
("pkt.sv", &ALIASES[1].1.replace("hdr_t hdr", "oth_t hdr")),
("pkt.sv", &ALIASES[1].1.replace("hdr_t hdr", "nop_t hdr")),
ALIASES[1],
],
);
}
#[test]
fn a_unit_whose_kind_alone_changes_moves_a_path_rooted_at_it() {
// `module h_x` and `package h_x` put the name, and the member after it,
// at the same offsets: only the unit's kind moves, and a top-rooted
// hierarchical path roots only at a module.
holds(
&[
("h_x.sv", "module h_x;\n logic s;\nendmodule\n"),
("h_xtb.sv", "module h_xtb;\n initial $display(h_x.s);\nendmodule\n"),
],
&[
("h_x.sv", "package h_x;\n logic s;\nendpackage\n"),
("h_x.sv", "module h_x;\n logic s;\nendmodule\n"),
],
);
}
const HIERARCHY: [(&str, &str); 4] = [
("h_leaf.sv", "module h_leaf;\n logic sig;\nendmodule\n"),
("h_mid.sv", "module h_mid;\n h_leaf u_leaf ();\nendmodule\n"),
("h_top.sv", "module h_top;\n h_mid u_mid ();\nendmodule\n"),
(
"h_tb.sv",
"module h_tb;\n h_top dut ();\n initial $display(dut.u_mid.u_leaf.sig);\nendmodule\n",
),
];
#[test]
fn a_hierarchical_path_follows_every_edit_of_the_module_at_its_tail() {
holds(
&HIERARCHY,
&[
// The signal at the end moves, goes, comes back as another kind.
("h_leaf.sv", "module h_leaf;\n logic pad;\n logic sig;\nendmodule\n"),
("h_leaf.sv", "module h_leaf;\n logic other;\nendmodule\n"),
("h_leaf.sv", "module h_leaf;\n wire sig;\nendmodule\n"),
// An instance in the middle renamed, then its module swapped.
("h_mid.sv", "module h_mid;\n h_leaf u_leaf2 ();\nendmodule\n"),
("h_mid.sv", "module h_mid;\n h_top u_leaf ();\nendmodule\n"),
(HIERARCHY[1].0, HIERARCHY[1].1),
// The tail module turned into a port, which the connection
// surface answers first.
("h_leaf.sv", "module h_leaf (input logic sig);\nendmodule\n"),
],
);
}
const MISSES: [(&str, &str); 2] = [
("asker.sv", "module asker;\n localparam int K = later_pkg::K;\n later_m u ();\nendmodule\n"),
("other.sv", "module other;\nendmodule\n"),
];
#[test]
fn a_use_that_found_nothing_is_answered_the_moment_another_file_declares_it() {
holds(
&MISSES,
&[
// The other file starts declaring both names, then twice over,
// then stops — a miss, a hit, an ambiguity, a miss.
("other.sv", "package later_pkg;\n localparam int K = 1;\nendpackage\nmodule later_m;\nendmodule\n"),
("other.sv", "package later_pkg;\n localparam int K = 1;\n localparam int K = 2;\nendpackage\nmodule later_m;\nendmodule\nmodule later_m;\nendmodule\n"),
("other.sv", "module other;\nendmodule\n"),
],
);
}
#[test]
fn a_name_two_files_declare_stays_ambiguous_exactly_as_long_as_it_is() {
holds(
&[
("d1.sv", "module dup (input logic a);\nendmodule\n"),
("d2.sv", "module dup (input logic a);\nendmodule\n"),
("u.sv", "module u;\n logic x;\n dup i (.a(x));\nendmodule\n"),
],
&[
("d1.sv", "module dup_one (input logic a);\nendmodule\n"),
("d1.sv", "// back\nmodule dup (input logic a);\nendmodule\n"),
("d2.sv", "module dup (input logic b);\nendmodule\n"),
],
);
}
#[test]
fn a_define_a_broken_file_and_an_unchanged_save_all_hold() {
holds(
&[
("defs.svh", "`define W 8\n`define F(a) (a)\n"),
("m.sv", "module m;\n logic [`W-1:0] x;\nendmodule\n"),
],
&[
("defs.svh", "`define W 16\n`define F(a, b) (a+b)\n"),
("defs.svh", "`undef W\n`define W 16\n"),
("m.sv", "module m;\n logic [`W-1:0] x\nendmodule\n"),
("m.sv", "module m;\n logic [`W-1:0] x;\nendmodule\n"),
("m.sv", "module m;\n logic [`W-1:0] x;\nendmodule\n"),
],
);
}
#[test]
fn an_unchanged_record_reports_that_nothing_moved() {
let files: BTreeMap<String, String> =
PORTS.iter().map(|(p, s)| (p.to_string(), s.to_string())).collect();
let mut index = build(&files);
let before = index.fingerprint();
assert!(!index.update_file(PathBuf::from(PORTS[0].0), PORTS[0].1), "same text, same record");
assert_eq!(index.fingerprint(), before);
// A comment after the last token moves no span the record holds.
let trailing = format!("{}// trailing\n", PORTS[0].1);
assert!(!index.update_file(PathBuf::from(PORTS[0].0), &trailing), "{trailing:?}");
let renamed = PORTS[0].1.replace("clk", "clock");
assert!(index.update_file(PathBuf::from(PORTS[0].0), &renamed), "a port renamed moves it");
}
// ----------------------------------------------------------------------
// The seeded sweep
// ----------------------------------------------------------------------
/// xorshift64*: reproducible from a seed, no dependency.
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 >> 12;
self.0 ^= self.0 << 25;
self.0 ^= self.0 >> 27;
self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
}
fn below(&mut self, n: usize) -> usize {
(self.next() % n.max(1) as u64) as usize
}
}
/// One random edit of `text`: a line inserted, deleted, duplicated or swapped
/// with its neighbour, or one identifier-ish word renamed to another from
/// the design — the kinds of edit that move spans, names and whole
/// declarations.
fn mutate(text: &str, words: &[&str], rng: &mut Rng) -> String {
let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
let at = rng.below(lines.len() + 1);
match rng.below(5) {
0 => lines.insert(at, " // a comment".to_string()),
1 if at < lines.len() => {
lines.remove(at);
}
2 if at < lines.len() => {
let line = lines[at].clone();
lines.insert(at, line);
}
3 if at + 1 < lines.len() => lines.swap(at, at + 1),
_ => {
let from = words[rng.below(words.len())];
let to = words[rng.below(words.len())];
if let Some(line) = lines.iter_mut().find(|line| line.contains(from)) {
*line = line.replacen(from, to, 1);
}
}
}
let mut out = lines.join("\n");
out.push('\n');
out
}
#[test]
fn a_seeded_sweep_of_mutations_over_every_design_holds() {
let designs: [&[(&str, &str)]; 5] = [&PORTS, &PACKAGES, &CLASSES, &ALIASES, &HIERARCHY];
let words = [
"leaf", "clk", "q", "a_pkg", "b_pkg", "W", "word_t", "base_c", "mid_c", "m", "f", "hdr_t",
"addr", "pkt_t", "h_leaf", "u_leaf", "sig", "h_mid", "u_mid",
];
let mut checked = 0;
for seed in 1..=8u64 {
let mut rng = Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15));
let mut files: BTreeMap<String, String> = BTreeMap::new();
for design in designs {
files.extend(design.iter().map(|(p, s)| (p.to_string(), s.to_string())));
}
let mut index = build(&files);
let paths: Vec<String> = files.keys().cloned().collect();
for step in 0..40 {
let path = &paths[rng.below(paths.len())];
let text = mutate(&files[path], &words, &mut rng);
files.insert(path.clone(), text.clone());
index.update_file(PathBuf::from(path), &text);
assert_eq!(
index.fingerprint(),
build(&files).fingerprint(),
"seed {seed}, step {step}: `{path}` became {text:?}"
);
checked += 1;
}
}
assert_eq!(checked, 320);
}
+611 -4
View File
@@ -36,13 +36,52 @@ the assertion where it *can* run.
## Handshakes
- Consumes nothing new from production code. No production file, no
`verify.rs`, no workflow, version file or changelog changes.
`verify.rs`, no workflow, version file or changelog changes — **except**
the round 2 product fix the lead granted (2026-11-19):
`crates/lucisv_mcp/src/project/files.rs` and its test fixture
`project/tests.rs`. `Stamp`'s public shape changed (`identity` is now
`Option<Identity>`, new `read_mono`); its only users are inside
`lucisv_mcp::project`, nothing outside the crate sees it.
- `tools/linux_check.sh` (the lead's): used as written in round 1; changed
in the fix round (QA finding 5, see the work log). Its usage line gained
`--dry-run`; the single-string form is unchanged.
- Scope extension granted by the lead in the fix round:
`crates/lucisv_server/src/server/tests/scan_trace.rs` (test file only).
- Requests: none.
- Requests: none (round 1).
- **Round 2 request: a product bug, not a test flake. Owner: `lucisv_mcp`.**
`crates/lucisv_mcp/src/project/files.rs:166-184`, `Stamp::check`. The
racy rule (`mtime + RACY > read_at`, line 175) covers the mtime only. The
ctime half of `identity` (line 214) has no racy rule. On Linux 6.8
(luhpe: ext4 under overlayfs, `CONFIG_HZ=1000`) the kernel stamps ctime
from the coarse clock, in 1 ms steps. Suppose a file's ctime moves (here a
rename-over), the server stats and reads it, and the file is rewritten at
the same size with its old mtime put back (`cp -p`, `rsync -t`,
`touch -r`), all within the same 1 ms tick. Then size, mtime, ctime and
inode all match the stamp. The check answers `Same`, and the stale
contents are served **for good**, because every later stat says the same.
- Reproduction:
`tools/linux_check.sh 'for i in $(seq 150); do cargo test -q -p lucisv_mcp --test qa_m1 qa_rework_a_rename_over_with_an_old_mtime_and_the_same_size_is_seen -- --exact; done'`.
Result: 12/150 failed as root with nothing else running, and 39/300 in
an earlier loop. It also failed once in the full suite as `--user` before
this round.
- Instrumented, by printing `(ctime, ctime_nsec, ino)` of `c.sv` after the
rename and after the rewrite (a temporary edit, since reverted). Every
failure had the two identical to the nanosecond. In every pass (261
printed) they were 1 or 2 ms apart, never 0. The `find` between them
took 0.44–0.66 ms. The failing answer was
``no declaration named `chyrlie`.``
- macOS: APFS ctime comes from a fine clock, so it always moves, and the
test has never failed there.
- **Resolved in round 2 by the lead's scope extension** (work log,
"the stamp fix"). The suggestion was: give ctime the racy
rule mtime has. A stamp whose ctime is within `RACY` of `read_at` is
`Suspect`, so it is re-read and re-hashed until it is older. The same
argument as git's racily-clean entries.
- The test was **left unchanged** on purpose, and still is. It is right,
and making it wait for the clock to tick would hide the bug. Before the
fix it failed about 1 in 10 runs alone on that box. Under load it fails less
often, because the `find` then takes longer than a tick: 0/200 under
8 busy loops.
## Status / TODO
@@ -67,8 +106,31 @@ the assertion where it *can* run.
times a copy of the `Server::large_scan` loop, not the production loop
at `server/large_file.rs:151`, so a per-hit rescan reintroduced there
would not be caught. Needs a test that drives the production path.
- [ ] Re-run on Linux once ssh to luhpe is back: everything in the fix round
and everything since 0.65.2 is unverified there (list in the work log).
- [x] Re-run on Linux once ssh to luhpe is back. Done in round 2, against
0.65.6 plus this round (see the round 2 work log).
### Round 2 (flakes on Linux)
- [x] Census: 2 090 single-test iterations on Linux (alone and under load)
and 57 whole-suite runs (Linux root and `--user`, macOS under load).
Every test that failed even once is in the table in the work log.
- [x] stdin `BrokenPipe` on a child that exits before reading: `cli.rs`
(both stdin helpers) and `qa_m8.rs` (`run`) tolerate that one error
and still assert on the exit code and output.
- [x] `e2e.rs` didOpen budget: a multiple of one parse of the same buffer
measured in the same process, instead of a fixed 200 ms.
- [x] `qa_m3.rs` CLI-while-formatting hang on macOS (an inherited pipe):
the server is spawned before the checker thread starts.
- [x] Every other wall-clock assertion reviewed; each left as it was, with
the reason (work log).
- [x] **Product bug, fixed (scope extended by the lead):** `qa_m1.rs`
`qa_rework_a_rename_over_with_an_old_mtime_and_the_same_size_is_seen`
failed on Linux about 1 run in 10 alone — a real staleness bug in
`Stamp::check` (Handshakes). The racy rule now covers the ctime, the
window is 3 s, and a wall clock stepped back distrusts every stamp;
the test itself is unchanged.
- [x] Audit of the other caches for the same hole: none has it (work log).
- [x] Deterministic unit tests of the racy decision; mutations shown.
## Work log
@@ -276,6 +338,335 @@ Unverified on Linux (all of it rests on round 1, against 88546c8 + lane):
- everything trunk added in 0.65.2 and 0.65.3;
- the second root run, which never happened in round 1 either.
### Round 2
**2026-11-19 (dev, round 2: the Linux flakes).** Tree: 58d3db3 (0.65.6) plus
this round, in `lucisv-wt/70b`. The brief reported master's record on Linux
as 9 full runs, 3 with a failure, each from a different test. Linux means
`tools/linux_check.sh` on luhpe: the CI job image, 4-CPU cap, kernel
6.8.0, ext4 under overlayfs, `CONFIG_HZ=1000`, debug build. macOS means
arm64 with 18 CPUs; another lane was running there too. Every macOS
`cargo test` went through `tools/guard.sh`, and there was no guard kill.
*Method.*
- Loops of the single test, in the job image, run alone and then under 8
busy loops on the 4-CPU cap. The baseline was rebuilt in the same
container with `git apply -R` of this round's patch, so before and after
share one build cache and one box.
- Whole-suite runs with `--no-fail-fast`. Each one keeps its result totals
and every failing test's output.
- Temporary instrumentation where the output was not enough. It was taken
out again, and each touched file was restored from a copy and checked
with `cmp`.
**Flake census**
| test | platform | before | cause | fix | after |
|---|---|---|---|---|---|
| `lucisv/tests/cli.rs` `stdin_and_lines_are_usage_errors_with_a_filelist` | Linux root | 2/9 master runs; 1/5 baseline runs; loop 0/200 alone, **42/200 loaded** | `run_with_stdin` `expect`ed the stdin write. A usage error exits before reading, so the write races the exit and gets `BrokenPipe`. | Both stdin helpers write through `feed`, which ignores `BrokenPipe` only; `run_with_stdin` is now `run_with_stdin_raw` plus `--no-cache`. | loop 0/200 alone, **0/200 loaded**; 0 in 30 Linux suite runs |
| `lucisv_mcp/tests/qa_m8.rs` `qa_argument_order_and_repetition_cannot_undo_read_only` | Linux root | 1/5 baseline runs; loop 0/200 alone, **37/100 loaded** | Same race: `run` `unwrap`ped `writeln!` to a server that refuses `--read-only=false` and friends with exit 2. Found by the census; not in the brief. | `run` stops writing on `BrokenPipe` and `unwrap`s any other error. | loop 0/200 alone, **0/100 loaded**; 0 in 30 suite runs |
| `lucisv_server/tests/e2e.rs` `opening_a_two_thousand_line_buffer_does_not_delay_the_request_behind_it` | Linux root | 2/9 master runs (205.15 ms against 200) | A fixed 200 ms against a measured floor of 146–179 ms best of three, quiet. Under 8 busy loops the open took 0.5–1.1 s, so the old bound would fail every time. | The budget is `OPEN_OVER_PARSE` (6) times the best of 5 in-process tolerant parses of the same buffer, interleaved with the 5 opens. | 0/20 alone, 0/20 loaded; 0 in 30 suite runs |
| `lucisv_mcp/tests/qa_m1.rs` `qa_rework_a_rename_over_with_an_old_mtime_and_the_same_size_is_seen` | Linux | 1/9 master runs (`--user`); loop **39/300 and 12/150 alone**, 0/200 loaded | **A product bug** (Handshakes): ctime moves in 1 ms ticks, and a same-size rewrite with the old mtime put back inside the tick is invisible to `Stamp::check`. All 12 instrumented failures had identical `(ctime, nsec, ino)`; all 261 instrumented passes were 1–2 ms apart. | **None, on purpose.** The test is right. | unchanged: 0 in the last 30 Linux suite runs, but about 1 in 10 alone |
| `lucisv_mcp/tests/qa_m3.rs` `qa_lucisv_check_over_the_same_tree_while_the_server_formats` | macOS, under 18 busy loops | **hung** once in 2 runs (still running after 9 min) | `sample` showed the checker thread in `Command::output` → `read`, with no `lucisv` child alive. `lsof` showed the test's `lucisv-mcp` server holding the other end of that pipe: it had inherited the pipe when it was spawned while the checker was making one (macOS has no `pipe2`). `join` waited on the checker, and the server lived until the test ended. Found by the census. | The server is spawned before the checker thread starts. | 0 hangs in 20 macOS runs under load; 0 in 20 Linux runs |
Nothing else failed in any run: Linux root 5 baseline runs, then 10 + 10 on
the fixed tree; Linux `--user` 10; macOS 2 + 20 under load (the second
batch under 9 busy loops, since 18 put one suite run over 20 min). Round 1's
`scan_trace` and `large.rs` fixes ran on Linux in all of them and never
failed.
**The wall-clock assertions** (an inventory of every test-code assertion on
measured time):
- **Changed:** e2e.rs didOpen (above).
- **Ratios already:** `large.rs` `assert_grows_linearly` (round 1);
`lens.rs:756` (`whole_file * 10 < walk`); `scan_trace.rs` (round 1).
- **Algorithmic guards with absolute bounds, left as they are:**
`pairs.rs:1159/1171/1190` (2 s, ~45x the honest 5–44 ms, against 7–17 s
quadratic); `regex.rs:631` (500 ms against microseconds, exponential
matcher far past it); `lexer.rs:1313` (5 s, "three orders of magnitude"
in either build); `e2e.rs:5780` (10 s, 25x the measured 0.4 s). The
regression each one guards is two or more orders of magnitude past its
bound, and the honest cost is one or more below it, so a ratio would buy
nothing. None failed in any run.
- **"Nothing was waited for" bounds, left as they are:** `startup.rs:488`
and `:1071` (< 1 s, against a 2 s bound and a 25 ms bound),
`startup.rs:528` (< 5 s against a 30 s bound), `e2e.rs:9118/9130` (< 1 s
against the 1.5 s grace). Each has to stay under the wait it proves was
skipped, so raising it is not free, and none failed.
- **Lower bounds** (`e2e.rs:9096/9193`, `startup.rs:182`): load can only
make them pass.
- **Corpus-only latency budgets**: `hierarchy.rs:1123`, `lens.rs:754`,
`type_hierarchy.rs:1289/1291`, `completion/mod.rs:787-789/856`,
`vlog_refactor/tests/corpus.rs:100/175`, `vlog_semantic/tests/workspace.rs:977`.
These skip without `corpus/`, which the Linux tree does not have. They
are budgets for a known machine. Not changed, and not exercised on
Linux.
- **`#[ignore]`d:** `large.rs:727-735`, `:764`.
**The mtime/sleep review.**
- `set_modified` users:
- `wire.rs:1250`, `qa_m6.rs:568` and `qa_f1.rs:666` set an hour-old mtime
on purpose. They do not rely on it moving.
- `qa_m1.rs:588`, a rename-then-recreate, gets a new inode.
- `qa_m1.rs:605`, a same-mtime rewrite, rests on the racy rule.
- `qa_m1.rs:617` restores an old mtime. Its ctime moves across a process
spawn and two calls, far more than a tick.
- `qa_m1.rs:936` is the product bug above.
- Sleeps: `qa_m3.rs:598/622`, `e2e.rs:9151` (the 1.7 s that outlasts the
1.5 s grace) and `cancel.rs:347`. None failed, so all are left.
**Stdin writers reviewed.** Every test that writes to a child's stdin was
checked:
- The interactive sessions (`cache`, `qa_m2/3/4/6`, `qa_f1/f2`, `attacks`,
`read_only`, `wire`, `opentitan*`, `e2e`'s `Live`) only write to a server
the test expects to be alive. A `BrokenPipe` there means the server died,
which is a failure, so those writes stay strict.
- The one-shot sessions write to a server that reads to EOF and exits only
when told to, so the strict write stays: `e2e.rs` `talk_with`,
`ifdef_folding.rs` `talk`, `qa_m7.rs`, `hierarchy_cap.rs`.
- `qa_m1.rs` `one_shot` already ignored write errors.
**Evidence the stdin fixes neither hide anything nor weaken anything** (macOS):
- With a 300 ms sleep before the write (the race made certain), the **old**
helpers fail 1/1 with `BrokenPipe` (`cli.rs:104`, `qa_m8.rs:117`). The
fixed ones pass, and so does the whole of `cli` (113/113) and `qa_m8`
(6/6) with the sleep in. So no test needed the write to succeed. It never
meant the child had read anything: every input is far smaller than a pipe
buffer.
- Sleeps removed; both files compared with `cmp` against copies.
**Mutation table** (production sabotage on macOS, restored from a copy and
checked with `cmp` / `git status`):
| test | sabotage | failed? | restored |
|---|---|---|---|
| cli `stdin_and_lines_are_usage_errors_with_a_filelist` | `args.rs:486` `if false && …` (accept `-` with `-f`) | yes, cli.rs:1942 `left: 0, right: 2` | yes |
| qa_m8 `qa_argument_order_and_repetition_cannot_undo_read_only` | `lucisv_mcp/src/main.rs:93` accept `--readonly` as `--read-only` | yes, qa_m8.rs:342 "started a server" | yes |
| e2e didOpen | `server/notification.rs` didOpen: parse the buffer 4 extra times | yes, 3/3 at 6.94x (84 ms; the old 200 ms would pass) | yes |
| e2e didOpen (sensitivity) | the same, 3 extra times | no, 3/3 passed at 5.82–5.97x | yes |
| qa_m3 `qa_lucisv_check_over_the_same_tree_while_the_server_formats` | `apply.rs` `commit` writes `after` plus `"\n"` | yes, qa_m3.rs:745 `m00.sv` | yes; then 3/3 pass |
*The didOpen ratio, measured.*
| where | load | best open | best parse | ratio |
|---|---|---|---|---|
| macOS | quiet, 8 runs | 31 ms | 11 ms | 2.66–2.77x |
| macOS | 36 busy loops on 18 CPUs, 15 runs | 34–41 ms | 12–14 ms | 2.48–3.15x |
| Linux root | quiet, 20 runs | 146–179 ms | 50–73 ms | 2.29–3.55x |
| Linux root | 8 busy loops on 4 CPUs, 20 runs | 0.50–1.12 s | 188–394 ms | 2.50–3.29x |
The wall clock moves 6x and the ratio stays in 2.3–3.6x, so 6 has about
1.7x headroom over the worst ratio seen.
- What it buys: on this Mac the new bound is *stricter* than the old one.
Four extra parses fail it at 84 ms, where 200 ms needed about 15 extra.
- What it costs: on the quiet Linux runner it is looser. There the old
bound sat at the box's floor, which is why it flaked.
- What it still cannot catch: the §46 defect itself, at this fixture's
size, as the test's doc comment always said.
**Counts.**
- `#[test]` attributes: 5 471 at HEAD and in this tree. No test was added
or removed.
- macOS whole suite: 97 result lines, **5413 passed, 0 failed, 64 ignored**
on every run here.
- Linux: **5407 passed, 0 failed, 64 ignored**. The six macOS/Windows-only
tests are not compiled there.
**Final runs on the final tree** (Linux, all of the above changes):
- root: `cargo clippy --all-targets -- -D warnings` exit 0; `cargo test
--workspace --no-fail-fast` green **10 consecutive runs of 10**, each 97
result lines, 5407 passed, 0 failed, 64 ignored.
- `--user`: clippy exit 0; tests green **10 consecutive runs of 10**, the same
totals.
- macOS, after the last `crates/` edit: `tools/gates.sh` **PASS**
(`target/gates/20261119-111810/`). That covers fmt, clippy, build and docs,
suites 521/435/743/376/672/119/151/2011/384 all with 0 failed, corpus 814/6
and node 37/0. The 20 loaded macOS runs above were also on this tree.
- No guard kill anywhere. The `lucisv-wt/70b/.lane70b/` probe scripts the
Linux runs used are deleted from the tree; copies are in the session
scratchpad.
Not done or not verified:
- The `qa_m1` product bug: reported, not fixed. Its test still fails about
1 run in 10 on Linux when run alone.
- The `qa_m3` fix is argued, and the `lsof` evidence shows the mechanism,
but the hang has no deterministic reproduction.
- The corpus-only budgets never ran on Linux.
**2026-11-19 (dev, round 2 continued: the stamp fix; scope extended by the
lead to `lucisv_mcp/src/project/files.rs`).**
*How the stamp works.*
- `read_source` stats a file, notes the time, reads it and hashes it. That
gives the `Stamp`: size, mtime, hash, `read_at` and `identity`.
`identity` was the `(ctime, ctime_nsec, ino)` triple on Unix and zeros
elsewhere.
- `Project::refresh` calls `check` on every file per tool call. `Same`
means the file is skipped. `Suspect` means `reread`: read and hash it
again, re-index only when the hash moved, and replace the stamp.
- So an extra `Suspect` costs one read and one hash. A missed change costs
stale answers, and stale *edit plans* in a tool agents use to write
files.
- The racy rule before: `current mtime + 2 s > read_at`. Nothing for the
ctime.
*What git does.* An index entry whose mtime is not older than the index
file itself is "racily clean": stat data cannot prove it unchanged, so it
is compared by content. The same idea applies to every timestamp the stat
comparison trusts.
*The fix* (`files.rs`, production lines ~150 → ~240):
- **Invariant**, as it is written in `Stamp::racy`: a stamp is trusted on
a later match only if every timestamp it trusts (the mtime, and the ctime
where there is one) is at least `RACY` older than the moment the stamp
was taken. A missing timestamp counts as racy, and so does one later than
the read.
- The test runs on the stamp's own values. On a match they equal the
current ones; on a mismatch the answer is `Suspect` anyway. All the
arithmetic is `checked_*`: the old `mtime + RACY` could panic on an
absurd mtime.
- **`RACY` 2 s → 3 s.** The window has to outlast the coarsest timestamp
plus the filesystem clock's lag behind `read_at`'s clock:
- Linux ticks (1–4 ms) and 1 s stamps (ext3, many NFS/SMB mounts) fit in
2 s.
- FAT's 2 s stamps do not. Take a timestamp `T` and a read at `T + 2 s`.
A write a tick later, from a coarse clock that lags, can truncate to
the same `T`. 3 s leaves a second of margin.
- Cost: a just-changed file is re-read on every call for 3 s instead
of 2.
- Not covered: a file server whose clock is more than ~1 s *behind*
ours. Git has the same assumption.
- **A wall clock stepped back** (new): after the read, a step back can give
a new write the very timestamp the stamp holds.
- The stamp now also keeps `read_mono` (an `Instant` taken with
`read_at`).
- `check` distrusts any stamp whose wall clock is now more than
`STEP_BACK` (100 ms) behind where the monotonic clock says it should
be. That holds until the file is re-read.
- A wall clock that ran *ahead*, as across a suspend the monotonic clock
slept through, is not doubted.
- A step back smaller than 100 ms stays inside `RACY`'s one-second
margin.
- **`identity` is `Option<Identity { ctime: Option<SystemTime>, ino }>`.**
`None` off Unix; a ctime that does not fit a `SystemTime` is racy.
- **The decision is a pure function**, `Stamp::compare(Seen, Clocks)`.
`check` is one `stat`, then `compare(Seen::of(meta), Clocks::now())`.
That is what lets the unit tests feed values without a file or a clock.
- **Off Unix** (no ctime in std on Windows): the racy rule still applies to
the mtime. The hole that remains there is old: a same-size rewrite that
restores an old mtime *outside* the window is invisible. There is
nothing else in the stat to see it with, as the `identity` doc says.
- **Test fixtures**: `project/tests.rs` `settle` and the existing
`a_stamp_sees_an_edit…` used to age a stamp by moving `read_at` alone.
That now looks exactly like a clock stepped back. They use the new
`#[cfg(test)] Stamp::taken_later`, which moves both clocks.
*New unit tests* (`project::files::tests`, deterministic, no file):
- `a_match_is_trusted_only_when_every_timestamp_was_settled_at_the_read`:
neither racy, mtime, ctime, both, `RACY − 1 ns` (suspect) and exactly
`RACY` old (same).
- `a_timestamp_later_than_the_read_or_missing_is_racy`: ctime after the
read, ctime `None`, mtime `None`, and off-Unix `identity: None` (mtime
decides).
- `a_wall_clock_stepped_back_since_the_read_distrusts_the_stamp`: stepped
back, behind the read, ahead (suspend), jitter under the tolerance, and a
stamp aged on both clocks.
- `any_moved_field_is_suspect_however_settled`: size, mtime, inode and
ctime each moved on a settled stamp.
*Mutations* (copies restored, `cmp` clean):
| sabotage | result |
|---|---|
| ctime dropped from the trusted list (`[Some(self.mtime), None]`) | FAILED: `…every_timestamp_was_settled…` at "ctime racy" (`Same` ≠ `Suspect`), and `…later_than_the_read…` |
| `clock_stepped_back` never consulted | FAILED: `a_wall_clock_stepped_back…` |
*The other caches, audited for the same hole* (none has it, so nothing was
stopped on):
- **Language server views** (`state/views.rs` `file_view`): no stamp at
all. A view is dropped on `set_document`, `close_document`, `update_one`,
`rebuild_index_with` and `begin_widen`, that is, on notifications. A disk
change no one reports is stale by design, as its doc says, with `hover`'s
`spells_exactly` guard. It never trusts a timestamp, so a same-tick
rewrite does nothing worse to it than any unreported write.
- **Persistent index cache** (`index_cache.rs`, `known_facts` →
`facts_now`/`facts_for`): keyed by `content_hash` of the text about to be
indexed. The bytes are always read, so there is no timestamp to fool.
- **MCP own store** (`lucisv_mcp/src/cache.rs`, `Records::take(path,
hash)`): by content hash, after `read_source` read the bytes. Its one
`modified()` only ages temporary files for removal. `Project::analysis`
reads the file every time and caches by hash.
- **CLI format cache** (`lucisv_core/src/cache.rs`): `Entry.content` is the
FNV-1a of the bytes, read on every run; no mtime.
- No `modified()`/ctime freshness check exists anywhere else outside tests
(`rg modified\(\)|mtime` over `lucisv_server`, `vlog_semantic`,
`lucisv_core` and `lucisv` sources).
*Performance* (temporary `eprintln!` of stat checks and suspects per
`refresh` in `project/mod.rs`, one binary before and one after, the source
restored with `cmp`; driver `drive.py` in the session scratchpad, guarded):
| session | calls | stat checks | re-reads before | re-reads after |
|---|---|---|---|---|
| OpenTitan `hw/ip`, 37 read calls (find/outline ×18, hierarchy) | 37 | 78 498 | 0 | 0 |
| copy of `hw/ip/uart`, 3 rounds of `format` then 8 reads | 33 | 1 120 | 120 | 120 |
| copy of `hw/ip/uart`, `chmod` every file, 8 calls at once, 3.5 s pause, 4 calls | 13 | 420 | 35 | **315** |
- Ordinary reads never re-read. An edit already makes the mtime fresh, so
it costs the same as before.
- The extra re-reads come only from a file whose ctime moved while its
mtime stayed old (`chmod`, `cp -p`, `touch -r`, rename-over). Each such
file is re-read on every call for 3 s, then never again.
- A re-read whose hash did not move re-indexes nothing.
*Checks, final tree.*
- macOS:
- `cargo fmt --all -- --check` exit 0.
- `cargo clippy --all-targets -- -D warnings` clean.
- `tools/guard.sh -- cargo test -p lucisv_mcp`: all pass, 388 tests, 4
of them new.
- `tools/gates.sh` **PASS** (`target/gates/20261119-114518/`): suites
521/435/743/376/672/119/151/2011/388, all with 0 failed; corpus 814/6;
node 37/0.
- Cross-check, the lead's command, for `-p lucisv -p lucisv_mcp`, on both
`x86_64-pc-windows-gnu` and `x86_64-unknown-linux-musl`, including
`lucisv_mcp`'s unit tests (`--profile test --bin lucisv-mcp`): clean, no
warning.
- `-p lucisv_server` fails on Windows at `state/incremental.rs:161`
(E0507, `dir_id` moved in a closure). That is the bug 0.65.7 fixed on
master, in a file this lane does not touch.
- `--all-targets` on Windows also fails in `tests/qa_m3.rs`, which uses
`std::os::unix` without a cfg. That predates this lane, and gates'
`cross` step does not build tests.
- Linux:
- the qa_m1 test alone: **0/300 failed as root and 0/300 as `--user`**
(before the fix: 39/300 and 12/150 as root).
- root: clippy exit 0; whole suite green **10 consecutive runs of 10**,
each 97 result lines, 5411 passed, 0 failed, 64 ignored. That is 5407
plus the 4 new unit tests.
- `--user`: clippy exit 0; green **10 of 10**, the same totals.
- The probe scripts are deleted from the tree again; copies are in the
session scratchpad.
*Changelog paragraph (for the lead):*
> **lucisv-mcp no longer serves stale contents after a same-size rewrite
> that restores an old mtime.** On Linux, ctime moves in 1 ms ticks. A
> file whose ctime had just moved (a rename-over, say), read by the server
> and then rewritten at the same size with its old mtime put back (`cp -p`,
> `rsync -t`, `touch -r`) inside the same tick, matched its stamp in every
> field. The server then answered from the old text until the file changed
> again. The "racy" rule now covers every timestamp the stamp trusts,
> ctime as well as mtime. Its window is 3 s (it was 2 s, too close to FAT's
> 2-second timestamps). A wall clock stepped back since a read now
> distrusts the stamp. Re-reads rise only for files whose metadata changed
> in the last 3 s. **Tests:** the suite is now stable on Linux.
> - Two stdin helpers tolerate a child that exits before reading.
> - The didOpen latency test measures its budget against a parse of the
> same buffer instead of a fixed 200 ms.
> - A macOS-only hang in an MCP concurrency test (a pipe inherited across
> threads) is fixed.
## QA log
**2026-11-19 (QA, macOS arm64, 18 CPUs; tree = 948f8a0 + this lane).**
@@ -422,6 +813,200 @@ Nothing here has run on Linux since the 0.65.2/0.65.3 fast-forwards.
*Fixed by QA:* finding 1 only. *Unverified:* everything on Linux, as
above.
### Round 2 QA
**2026-11-19 (QA, round 2; tree = 934d472 + f910554 in `lucisv-wt/70b`;
macOS arm64 18 CPUs, Linux = `tools/linux_check.sh` on luhpe).**
Verdict: **PASS WITH FINDINGS.** No stale read that the invariant claims to
prevent, no panic, no test that passes without testing, no Linux failure.
*Baseline (macOS).* `cargo fmt --all -- --check` exit 0. Guarded
`cargo test -p lucisv_mcp -p lucisv -p lucisv_server`: 24 result lines,
2569 passed, 0 failed, 53 ignored. Full `tools/gates.sh` **PASS** (fmt,
clippy, build, suites 521/435/743/376/672/119/151/2030/388, docs, corpus
814/6, node 37/0, cross). (`lucisv_server` is 2030 here, not the dev's 2011:
the dev measured on 0.65.6; 934d472 adds 19.) `#[test]` counts vs 934d472:
`cli.rs` 113→113, `e2e.rs` 109→109, `qa_m3.rs` 31→31, `qa_m8.rs` 6→6,
`project/tests.rs` 3→3, `files.rs` 3→7. The only removed assertion is
e2e's `best <= 200 ms`, replaced by the ratio. Cross, `--all-targets`, for
`lucisv_mcp`: linux-musl clean. Windows fails only in `tests/qa_m3.rs`
(12 errors, `std::os::unix` and `PermissionsExt` with no cfg). That is
pre-existing: the same 8 `std::os::unix` uses are at 934d472. Every other
target builds for Windows (`--bins --profile test` plus every `--test`
except `qa_m3`), including `files.rs`'s unit tests.
*PART 2: the stamp.*
- **Real files, the real binary.** A driver (`stale.py`, kept in the
session scratchpad) speaks MCP stdio to `lucisv-mcp` and asks `find` for
the new module name and then the old one. It covers 11 operations: in-place
same-size rewrite plus `utime(old)`; the same with `touch -r`;
rename-over of a same-size, old-mtime file; hard-link swap; `cp -p`-style
`O_TRUNC` rewrite plus `utime` plus `chmod`; truncate-and-rewrite plus
`utime`; mmap write plus msync, unmap and `utime`; vim-style
write-beside, rename and `utime`; replacing the file with a symlink to a
same-size file; `chmod` alone (expect the old content); and a directory
rename that brings in another same-size, old-mtime `c.sv`. It runs each at
delays of 0, 1 ms, 10 ms, 1 s, 2.9 s, 3.1 s and 10 s after the server's
read, with two preparations: stamp settled (ctime > 4 s old) and the
original hole (ctime made fresh by `utime(old)` just before the read).
That is 154 cases per run.
| platform / fs | cases | stale |
|---|---|---|
| macOS APFS | 154 | 0 |
| Linux root, overlayfs (`/w`) | 154 | 0 |
| Linux root, overlayfs `/tmp` | 154 | 0 |
| Linux root, tmpfs `/dev/shm` | 154 | 0 |
| Linux `--user`, the same three | 3 × 154 | 0 |
- **The exact hole, hit on purpose.** A sequential loop does
`utime(old)`, then `find` (the read), then a same-size rewrite plus
`utime(old)` immediately. It counts the runs whose stat after the write
equals the stat at the read: size, mtime, ctime and ino all identical.
| binary | fs | runs | stat-identical | stale |
|---|---|---|---|---|
| **934d472 (before)** | overlayfs | 300 | 65 | **65** |
| **934d472 (before)** | tmpfs | 300 | 87 | **87** |
| this lane, root | overlayfs | 300 | 65 | 0 |
| this lane, root | tmpfs | 300 | 125 | 0 |
| this lane, `--user` | overlayfs | 300 | 52 | 0 |
| this lane, `--user` | tmpfs | 300 | 106 | 0 |
| this lane, macOS | APFS | 100 | 0 | 0 |
So the driver does detect the bug. The old code is stale exactly when the
stat is identical, and the fix is fresh in every one of those runs.
- **Property test of `compare`.** I wrote my own xorshift generator and
included it temporarily in `files.rs` by `#[path]` from the scratchpad.
`files.rs` was restored from a copy and `cmp`-checked; `git status` is
clean. It ran **3 000 000 cases**: moved 970 519, racy 2 449 889, clock
step 677 250, and **232 760 cases where nothing doubted → all `Same`**
(no needless re-read). No `Same` was returned for any moved, racy or
stepped case. There was no panic, including at u64/i64 extremes, the
epoch, times before 1970, `RACY ± 1 ns`, `STEP_BACK ± 1 ns` and an
`Instant` behind the read. (Raw nsec ≥ 1e9 cannot be built as a
`SystemTime`. By reading `identity()`: `i64::MAX` s plus `i64::MAX` ns
fits a `Duration`, so the sum does not panic, and an out-of-range result
becomes `None`, which counts as racy.) Each of these mutations fails it:
ctime dropped, step check dropped, `>` → `>=`, identity ignored.
- **Clocks.** From the std 1.100 docs: `Instant` is `CLOCK_UPTIME_RAW` on
Darwin and `CLOCK_MONOTONIC` on Linux, both stopped in suspend; Windows
uses QPC. Through `compare` with injected clocks:
- 1 h suspend: `Same`, and also `Same` if `Instant` counts the suspend.
- 5 s backwards step: `Suspect`. After that one re-read: `Same`. A file
written 2 s before the step and read after it: `Suspect`.
- 5 s forwards step: `Same`, which is safe locally because the next
write is stamped after the step.
- Drift: 99 ms → `Same`, 115 ms → `Suspect`.
- On Linux NTP slews `CLOCK_MONOTONIC` along with the wall clock, so only
steps diverge. On macOS `UPTIME_RAW` is not slewed. Measured here, the
wall clock runs **ahead** of it by +6.37 ppm (stable over 300 s), so
the step rule never fires. A Mac drifting the other way at that rate
would distrust stamps older than ~4.4 h once: one re-read of each, with
no re-index. Benign.
- **TOCTOU.** The stat comes before `Clocks::now()`, which comes before the
read. A write between the stat and the read leaves an old stat with new
bytes, and the next stat differs, so this is safe. A write after the read
in the same tick is covered by the racy rule. `read_at` is earlier than
the read itself, which errs toward racy.
- **Skew tolerance** (by arithmetic). A later write can only carry the
stamp's timestamp if `RACY ≥ granularity + (local clock − file server
clock)`. That gives FAT (2 s) 1 s, 1 s filesystems (HFS+, ext3,
NFSv2/SMB1) 2 s, and ns filesystems ~3 s. Past that skew, an *ordinary*
same-size edit inside one server tick is invisible, not only an
mtime-restoring one. Not testable here (no FAT/NFS).
- **Audit of the other caches: confirmed.** The server's `file_view`
(`state/views.rs:74`) has no stamp. `index_cache.rs:226/298` is keyed by
`content_hash`. MCP `Records::take(path, hash)` (`cache.rs:110`) is too.
`Project::analysis` re-reads every call (`mod.rs:301`), so `read` and
`outline` were never exposed; only index answers (`find`, hierarchy,
names) were. The only other `metadata` uses outside tests are
`walk.rs:194` `(dev, ino)` for cycles and MCP temp-file aging.
Experiment: the CLI format cache with a formatted file, `--check` (from
cache), then a same-size unformatted rewrite with the mtime restored, then
`--check`. Result: "would reformat", exit 1. Correct.
*PART 1.*
- None of the four tests skips on macOS (`--nocapture`). My own mutations
(copies restored, `git status` clean):
| test | mutation | result |
|---|---|---|
| cli `stdin_and_lines…` | `args.rs:487` message reworded | FAILED cli.rs:1943 |
| qa_m8 `qa_argument_order…` | `main.rs:94` "unknown flag" | FAILED qa_m8.rs:345 |
| e2e didOpen | 100 ms sleep in the didOpen arm | FAILED 10.63x (142 ms; old 200 ms would pass) |
| qa_m3 CLI-while-formatting | CLI `--check` exits 3 instead of 1 | FAILED qa_m3.rs:743 |
- **BrokenPipe callers.** There are 22 `run_with_stdin(_raw)` callers. Each
asserts the exit code and/or output, except `cli.rs:2149-2150`, which
asserts only `stdout == ""` (finding 4). `qa_m8` `run` has 5 callers.
Each asserts the status or reads answers by id, so a server that died
leaves a missing answer and the test fails.
- **Ratio, 50× under load each.** macOS (36 busy loops): 0/50 failed,
2.40–3.09x. Linux root (8 busy loops, opens ~1 s): 0/50 failed,
**2.25–4.09x**. The worst is above the dev's 3.55; headroom to 6 is
1.47x. The blind spot of three extra parses is acceptable for a test named
for unbounded delay (see finding 5 for the machine dependence).
- **qa_m3.** The `lsof`/`sample` evidence fits the mechanism. On macOS std
creates pipes with `pipe()` and then sets `FD_CLOEXEC`. The fix removes
the only intra-test overlap: the main thread spawns nothing while the
checker runs. **100/100 green on macOS under 36 busy loops**, no hang.
Grep: `qa_m3.rs:721` is the only test thread that spawns children in a
loop; every other `thread::spawn` near a `Command` is a stdout pump.
Parallel *tests* in one binary can still inherit each other's pipes on
macOS, but the wait is bounded by the other test's lifetime, not a
deadlock.
*Linux, independently.*
- Root: clippy `--all-targets -D warnings` exit 0. Whole suite
`--no-fail-fast` **6/6 green**, each 97 result lines, 5430 passed,
0 failed, 65 ignored.
- `--user`: clippy exit 0. **6/6 green**, the same totals.
- `qa_m1` `qa_rework_a_rename_over…` alone, root: **0/300 failed**.
- No guard kill anywhere on macOS.
*Findings* (none is a FAIL):
1. (medium, documented-limit class) **A writable mmap kept open serves
stale contents indefinitely on Linux.** Map the file, store into it
(this sets mtime and ctime), wait 4 s, let the server read, then store
into the same already-dirty page. The stat is unchanged after the
store, after `msync` and after `munmap` (overlayfs and tmpfs, root and
`--user`), and `find` stays stale. On macOS it is stale until `msync`.
The kernel exposes nothing, so no stamp can see it (git has the same
limit). Repro: `stale.py BIN DIR mmap`. Suggest stating it in
Assumptions. Editors do not write through mmap.
2. (low, perf) **A future mtime makes a file racy forever**, so it is
re-read and re-hashed on every call (no re-index). Release binary,
macOS:
- 4 000 small files: 6.8 → **67.5 ms** median per `find`.
- A copy of OpenTitan `hw/`: 21 → **126 ms**.
- Fresh copy of `hw/` (every ctime new): burst median 58 ms against
33 ms settled, for ~3 s only.
Usable, but the cost lasts for as long as the clock stays behind. The
lead should decide whether a timestamp far in the future (> 1 day, say)
should stop counting as racy.
3. (low, docs) `docs/features/mcp-transport/README.md:53-58` still says
the 2 s window and mtime-only racy, and that identity is "0" elsewhere.
It is outside this lane's files: a Handshake request. The non-unix hole
is real: a same-size rewrite that restores the mtime ≥ 3 s after the
read is invisible, since std has no ctime and no stable `file_index`.
It is stated only in `files.rs` and this README, not where a Windows
user would see it (`docs/site/src/content/docs/guides/agents.md`).
macOS `setattrlist(ATTR_CMN_CHGTIME)` returns 0 but leaves ctime
unchanged, so an unprivileged ctime restore is not possible there.
4. (low, pre-existing) `crates/lucisv/tests/cli.rs:2149-2150` asserts only
that stdout is empty, so a child that crashes (before or after reading)
passes. The BrokenPipe tolerance does not materially widen this: the
inputs fit in the pipe buffer.
5. (info) The ratio test's sensitivity depends on the machine. A 100 ms
didOpen stall is 10.6x on this Mac but would be ~3–4x on the Linux
runner (parse 50–70 ms), which passes.
*Fixed by QA:* nothing. *Unverified:* FAT, NFS and SMB (skew arithmetic
only); Windows at run time (compile only); a real suspend or NTP step
(injected clocks only).
## Review
**Lead, 2026-11-19.** Accepted on macOS evidence; Linux line left open.
@@ -447,3 +1032,25 @@ above.
unticked until that run happens; the Linux job is not added blind.
- Open follow-up, recorded under Status: the references linear-time test
times a copy of `Server::large_scan`'s loop, not the production code.
**Lead, 2026-11-19 — Round 2.** Accepted for 0.65.9; §70 closed.
- Round 1 was accepted on macOS evidence with the Linux line open, and the
first Linux runs after ssh came back showed why that line mattered: clean
once, then 3 failing runs in 9. The dev's census (57 whole-suite runs,
2 090 loop iterations) is the right way to chase flakes — a ~10% flake does
not show in three runs.
- The dev stopped on the mtime test instead of loosening it, and it was a
real bug: `lucisv-mcp` could serve stale contents indefinitely. I extended
scope to fix it. QA reproduced the hole on purpose on the old binary
(65/65 and 87/87 stale when the stat was identical) and got 0 on the new
one across overlayfs, tmpfs and APFS, then property-tested `compare` with
three million cases under four mutations. That is the evidence.
- The `qa_m3` hang is the same test the guard killed in the 0.65.5 release
gates and in 71.7's QA; it now has a cause (a pipe inherited across
threads on macOS) and a fix, though no deterministic reproduction.
- `ci.yml` gains the `linux` job in this change, as §70 planned. It installs
Rust per job and builds cold — a few minutes; acceptable for now.
- Open, filed in TODO: future-mtime trees re-read on every call; the mmap
limit and the Windows gap are now written in `docs/features/mcp-transport`;
a weak assertion in `cli.rs`; `qa_m3.rs` does not compile for Windows.
File diff suppressed because it is too large. Load diff
+13 -6
View File
@@ -50,13 +50,20 @@ arrived.
a changed hash re-indexes it; a missing file is removed and triggers a
re-walk; the roots are re-walked when the last walk is older than 5 s and
on every `project_overview`, so new files appear. All changes go into the
index with one `absorb` (one merge). A file modified within 2 s of being
read is re-read on every sweep until it settles — git's "racy clean" rule —
so an edit that keeps a file's size inside one mtime tick is still seen.
On Unix the stamp also holds the file's ctime and inode (the same
index with one `absorb` (one merge). A file any of whose trusted timestamps
— its mtime, and on Unix its ctime — is within 3 s of the moment it was
read is re-read on every sweep until it settles — git's "racy clean" rule,
applied to every timestamp the stamp trusts since 0.65.9 (it covered the
mtime alone before, and a same-tick rewrite on Linux was served stale) —
so an edit that keeps a file's size inside one timestamp tick is still
seen. On Unix the stamp also holds the file's ctime and inode (the same
`stat`), so a same-size rewrite that puts the old mtime back (`cp -p`,
`rsync -t`, `touch -r`) is seen too; elsewhere they are 0 and size, mtime
and the racy rule are all there is. A by-name lookup that finds nothing
`rsync -t`, `touch -r`) is seen too. Elsewhere (Windows) there is no ctime
or inode: size, mtime and the racy rule are all there is, so a same-size
rewrite that restores the old mtime more than 3 s after a read is NOT
seen. Not seen anywhere: a store through a writable mmap that the kernel
has not yet reflected in the file's timestamps
(`docs/features/linux-test-portability`, Round 2). A by-name lookup that finds nothing
(`unit_interface`, `list_units` with a `glob`, `search_symbols`) walks
once more before it answers, unless this call already walked
(`Project::ensure_walked_for_miss`) — so a file the agent wrote a moment
+890
View File
@@ -0,0 +1,890 @@
# scan-ordering
## Goal
The owner's report: *"Sometimes when I find references on a port/signal, it
shows not found. But if I click somewhere else and then click back to the same
word, the find reference suddenly works again."* The investigation (TODO §71.7)
found the cause and two worse bugs beside it. **A1:** a caret just past a
name's last letter — where a double-click, a click on the right half of the
last letter, or a row of lucisv's own References view leaves it — asked the
server about the *next* character, and every "symbol under the cursor" request
answered nothing there. **B:** while a whole rescan answered messages, a
`didChange` drained mid-scan was applied ahead of an older `didChange` still
waiting, so under incremental sync the server's copy of a buffer silently
diverged from the editor's until the file was reopened. **C:** a burst
`[request, didOpen]` during the startup scan re-held the request at every
file, and the scan took ~300 s instead of ~1.7 s on OpenTitan. This round makes
a caret touching a name's right edge mean that name, establishes "no
notification overtakes an older notification" as the loop's rule, and makes
"only applied messages change a scan's state" true. P1, P2 and P3 are
documented, not changed (P2 was fixed in the first round and reverted in the
fix round for its cost, QA-1).
## Assumptions
- **VS Code's word rule is the one to match.** `getWordAtText`
(`src/vs/editor/common/core/wordHelper.ts`) accepts a word whose end equals
the caret, so VS Code titles a references search, highlights the word and
shows "No references found" for the name *before* a caret that touches it
on the right. Its default word pattern splits on `.`, `(`, `[`, `` ` `` and
`$`, so in `u_a|.sig` the word is `u_a` and in `u_a.|sig` it is `sig`; the
rule here agrees ([`caret::symbol_offset`]).
- **A name byte** is ASCII alphanumeric, `_` or `$` (IEEE 1800-2017 §5.6). A
macro after its backtick and a system task are covered by the same set; an
escaped identifier (`\a+b `) is handled by its terminating whitespace. A
number or keyword just before the caret is a "name" too: harmless for the
requests that resolve nothing there, and right for `documentHighlight`'s
keyword pairs (`begin|` now highlights its `end`, as VS Code's own word
highlight already did).
- **`vscode.open` puts the caret at a range's end.** Verified in VS Code's
source (`extHostTypeConverters.ts` converts `selection` with `Range.from`,
losing a `Selection`'s direction; `codeEditorWidget.ts`'s `setSelection(IRange)`
makes the range's end the position). VS Code's own references view passes
`range.with({ end: range.start })` and go to definition
`Range.collapseToStart(range)`; lucisv's view now does the same.
- **What is ordered (fix round, narrowed from "every client message"):**
every notification other than `$/cancelRequest` — the only messages that
change what the server holds — is applied in the order sent, across
documents (a `didClose` of one file and a `didOpen` of another stay in
order). A request is answered after every notification sent before it
(`must_wait`, unchanged), but **may** be answered after a newer
notification has been applied, when it was held and nothing older than
that notification was: it is then answered against newer state, exactly as
every request answered late on base was. Exempt altogether: **responses**
(they answer a request the server made; `take_the_answer_out_of_held`
relies on that) and the navigation requests the empty-answer rule set aside
(`deferred`, re-asked at a later publish). A **cancel** waits whenever
anything is held, so one naming a held request is honoured at replay; one
naming a request in the unapplied tail of the burst a scan is nested in is
dropped and the request computed, as on base.
- **Why narrowing is sound.** Buffer text, open/closed state, settings,
folders and watcher effects are changed only by non-cancel notifications.
Such a notification is applied only when no older one is unapplied in
`held` or in an enclosing burst's tail ([`Server::behind`]), `held` is
replayed in order, and nothing else defers a notification — so the
sequence of state changes is the client's. The broad rule's only extra
effect was to keep a notification from overtaking a held *request*, which
changes no state and cost the startup its first `didOpen` (QA-3). Checked
by the randomized test, f6.py, QA's seeds and hand scenarios (Work log).
- **Memory while holding is bounded by the scan's length times the client's
rate.** Requests were already held this way; a `didChange` under incremental
sync (what lucisv advertises) is a few hundred bytes. A full-sync client
flooding whole-buffer changes during a long rescan holds one copy per change
until the scan ends — the same order as the `dirty` text it would otherwise
have kept, times the number of changes. Not coalesced: coalescing two held
changes is only sound when nothing between them reads the buffer, which is
the analysis this round avoids.
- **P1 (directory-only watcher events) is a registration question, not a
handler one** — see Handshakes; nothing arrives today for the case that
matters.
## Handshakes
**Consumed:** `Scan::neighbourhood_indexed` and `open_next` (unchanged),
`sync::apply_changes_at` (unchanged). No `state/` file is touched after the
fix round (in particular not `incremental.rs`'s `holds_another_spelling_of`).
**Promised to the rest of the server (changed, read this):**
1. **`process_batch` holds notifications too** (`Server::must_hold`, mod.rs).
A non-cancel notification is held when an older one is still unapplied:
in `held`, or in the tail of a burst whose message started the scan now
draining (`Server::behind`, a count of those tails' non-cancel
notifications, kept by `process_batch`). A cancel is held when anything
is held. A request's rule is `must_wait`, unchanged. A response is never
held. `batch::changes_state` names the messages that are ordered.
Anything that adds a new caller of `process_batch` inherits the rule for
free; anything that applies a client message *without* going through
`process_batch` breaks it. **For lane 71.3 (viewport highlighting),
rebasing onto this:** the `process_batch` diff is the `behind`
bookkeeping (an `unapplied` counter), the `must_hold` call in place of
`must_wait() && Request`, a `cancel_deferred` before holding, and the
splice moved into `Server::hold` (which keeps `process_batch` under 80
lines). Nothing else in the loop moved.
2. **A `didOpen` changes a scan's order where it is applied.** The `didOpen`
arm sets `head_owed` and `opened_mid_scan` when `scanning`;
`answer_what_is_waiting` reads `opened_mid_scan` after the batch. `batch.rs`'s
`opened_in` is gone — nothing may read a batch's `didOpen`s again.
3. **Position → symbol requests resolve through `Server::symbol_offset`**
(dispatch.rs), which is `Server::offset` plus [`caret::symbol_offset`]. A
new request about the name under the cursor should use it; one with a
boundary rule of its own keeps `offset`. The table is below.
4. **Test-only:** `server/probe.rs` scripts bursts into a scan's interleave
points and counts hand-backs; it is `#[cfg(test)]` and thread-local, and
the one production line is `#[cfg(test)]` too.
**Requests to other modules / the lead (not done here):**
- **P1 needs a second watcher registration.** VS Code coalesces the deletes
under a deleted folder into one event for the folder
(`src/vs/platform/files/common/watcher.ts`, `EventCoalescer`: "remove all
DELETE events up to the root folder that got deleted"; `vscode.d.ts`: "file
events from deleting a folder may not include events for the contained
files"), and `extHostFileSystemEventService.ts` then drops the folder event
because its path does not match `**/*.{v,vh,sv,svh}`. So after `rm -rf dir`
or a `git checkout` that removes a directory, **the server receives
nothing** — no handler change can fix it. Created files are not coalesced:
`mkdir d && cp x.svh d/` or a checkout that adds a directory arrives as
per-file creates, which the server already handles; a directory *moved in*
arrives as one folder event, dropped the same way. The fix is a second
watcher, `**/*` with `kind: Create | Delete`, plus a handler that expands a
folder path to the held files under it (delete) or a rescan (create). That
changes the registration every client receives and the traffic it sends
(every create/delete outside `files.watcherExclude`), which is a decision
for the lead, so it is filed rather than done. QA's synthetic
`r2attack.py dir-create` / `held-dir-delete` still diverge (unchanged).
- **P3 (symlinked files held under one spelling or both)** is unchanged: the
rule "one file, one spelling, whatever is open" needs the walk
(`discover.rs`'s `Aliased`), the overlay and the one-file path changed
together. Not small; filed.
- **P2 (reverted, known, pre-existing — 0.65.6 behaviour).** An excluded or
unlisted buffer the index took in (a whole scan takes every open buffer;
the one-file path of a save or watcher event takes it too, QA F4 of
`localized-reindex`) **stays in the index after `didClose`**, where a fresh
server would not hold it: `oracle/r2attack.py excluded-close`, "closed" and
"saved then closed", 20 answers differ. The first round fixed it by taking
an unheld buffer in on `didOpen` and forgetting it on `didClose`; each is a
one-file add/remove, which shifts file ids and rebuilds the completion
tables and include naming — ~190 ms per open and ~225 ms per close on full
OpenTitan, 2 000 outside files opened and closed 806 s vs 0.7 s
(`qa717/drv/lat717.py`, `p2perf.py`, QA-1). Reverted. A fix must make the
removal cheap (a tombstone the next scan or publish folds in, say) — it is
an index-layer change, filed.
- **QA-2 (known, pre-existing): an unheld buffer opened while a scan runs is
not taken in by that scan**, and nothing takes it in when the scan ends;
opened before the scan it is held. `qa717/drv/race717.py BIN <OpenTitan
copy> 0.5`: an excluded file opened 0.5 s into the startup scan is still
unheld after settle, base and new alike. The same final state answers
differently depending on when the buffer was opened; QA's `QA_FRESH_SAVE`
exists to hide exactly this on the fresh side.
- **QA-7a (known, pre-existing): closing an unsaved in-scope buffer whose
text a rescan took into the index leaves that text in the index** after
the close; a fresh server holds the disk text. `qa717/drv/closeidx.py BIN
rescan`: `qd_buf` survives the close, the fresh server holds `qd_disk`.
Identical on base. Same root as P2: a close does not touch the index.
- **Notes for the lead's backlog (QA, not this lane):** QA-6 — the
`lucisv_mcp` test `qa_m3::qa_lucisv_check_over_the_same_tree_while_the_server_formats`
(`crates/lucisv_mcp/tests/qa_m3.rs:687`) hung to the guard's 600 s limit
once in QA's gate run (passed on the retry), also seen in the 0.65.5
release gate log. QA-7b — `rand_run.py` full OpenTitan seed 301 ×100
diverges at step 100 (13 answers, `top_earlgrey/ip/ast/rtl/usb_osc.sv`)
identically on base. QA-7c — renaming a port of a module defined twice
(`top_englishbreakfast/ip/ast/rtl/adc.sv:81` `rst_adc_ni`) gives an edit
or a refusal at random across fresh servers, base too (`qa717/drv/dup.py`).
- **lucisv_mcp** answers by name, not by caret position, so A1 does not
apply to it.
### Every position-taking request and its boundary rule (A1)
| request | what the position names | rule now |
|---|---|---|
| `textDocument/hover` | the name under the cursor | **shifted** (`symbol_offset`) |
| `textDocument/definition` | the name | **shifted** |
| `textDocument/typeDefinition` | the name whose type is wanted | **shifted** |
| `textDocument/references` | the name | **shifted** — the owner's bug |
| `textDocument/documentHighlight` | the name, or a scope keyword of a pair | **shifted** |
| `textDocument/prepareRename`, `textDocument/rename` | the name | **shifted** |
| `textDocument/prepareCallHierarchy` | the module under the cursor | **shifted** (already answered for the whole instantiation, so it changes nothing there) |
| `textDocument/prepareTypeHierarchy` | the class | **shifted** (already answered for the whole declaration) |
| `textDocument/linkedEditingRange` | a closing label being typed | as sent — `linked.rs`'s `covers` is already end-inclusive (`offset <= span.end`), which typing at a label's end needs |
| `textDocument/signatureHelp` | the call the caret is *in* | as sent — before `(` and after it are different answers on purpose |
| `textDocument/completion`, `textDocument/inlineCompletion` | the insertion point | as sent — "just past a name" is where the text goes |
| `textDocument/onTypeFormatting` | the character just typed | as sent |
| `textDocument/selectionRange` | where expansion starts | as sent — VS Code merges its own word ranges in |
| `textDocument/codeAction` (port refactorings, organize imports) | `range.start` as the cursor, resolved to the *instantiation* or *import* around it | as sent — the item's span contains a name's end |
| `textDocument/codeAction` (extract, inline module) | a range | as sent |
| `workspace/executeCommand` (port commands, lens) | positions the server itself issued | as sent |
| `inlayHint`, `semanticTokens/range`, `foldingRange`, `documentLink`, `documentSymbol`, `lucisv/scopePairs`, the hierarchy snapshot | a range or the whole document | no caret |
## Status / TODO
- [x] Reproduce A1, B, C on 58d3db3 with the investigation's drivers; record
- [x] A1: `caret::symbol_offset`, `Server::symbol_offset`, nine requests
- [x] A1: the References view puts the caret at the identifier's start
- [x] B: `Server::must_hold` + `Server::behind`
- [x] C: `opened_mid_scan`, set where a `didOpen` is applied; `opened_in` gone
- [x] P2: fixed in round 1, **reverted** in the fix round (QA-1); documented
- [x] Fix round: rule narrowed to notification-over-notification (QA-3);
`process_batch` split (`Server::hold`); QA-4 measured; QA-5 wording
- [ ] P1: filed (Handshakes) — needs a registration decision
- [ ] P3: filed (Handshakes)
- [x] Regression tests (fail on 58d3db3 + the probe, pass now)
- [x] Randomized ordering test, fast and `#[ignore]`d long
- [x] QA's seeds and hand scenarios against the binary
- [x] Timings
- [x] fmt, clippy `--all-targets -D warnings`, guarded `lucisv_server`
(fix round: 1 920 unit + 106 integration, 44 + 3 ignored),
`vlog_semantic` 435, `lucisv_mcp` 384, `node --test
editors/vscode/*_test.js` 37; ignored release runs (both re-index
sweeps, the 300-seed ordering run) pass
- [x] full `tools/gates.sh`: PASS, every step (corpus 814/6, the same six
known failures; `lucisv_server` 2 032/0)
**Not verified here (no VS Code on this machine):** double-click a port name
and run Find All References — results, not "No references found"; F12 and
hover with the caret just after a name; a row of lucisv's References view
opens with the caret at the name's start, and Shift+F12 from there finds the
same list; F2 with the caret just after a name opens the rename box.
## Work log
### 2026-11-19 — dev agent
Base is 58d3db3 (release 0.65.6). Drivers are the investigation's
(`scratchpad/inv717/drv`), QA's oracle (`scratchpad/qa711/oracle`) and the Q1
driver (`scratchpad/qa713/drv/livelock2.py`), copied to `scratchpad/dev717/`
with the guard pointed at this worktree; every tree they touch is a scratch
copy, every index store is under `dev717/st`.
**Reproduced on base, then fixed (same drivers, release binaries):**
| | 58d3db3 | now |
|---|---|---|
| A1 `refpos.py` uart_core.sv `tx`, caret just past the name (col 27) | refs 0, def 0, highlight null, hover null | refs 3, def 1, highlight 2, hover yes (= col 25) |
| A1 one column further right (col 28) | 0 / 0 / null / null | 0 / 0 / null / null (unchanged) |
| B `f6.py held`, full sync | server holds v2, client v3 | v3 |
| B `f6.py tail`, full / incremental | v2 / v3 lost (`{qa_v2_mod}` only) | v3 / both, in place |
| B `f6.py held`, incremental | right by luck (the two inserts commute) | right |
| C `livelock2.py hover`, cold full OpenTitan | hover and tokens answered at 318.6 s, scan ended 318.6 s | hover 0.68 s, tokens(B) 0.76 s, scan ends 1.70 s (median of 3; 4th run, `delta` variant: 0.67 / 0.76 / 1.70 s) |
**A1.** `caret.rs` is the rule (23 production lines): one byte left when the
caret's byte is not a name byte and the byte before is, or when the caret sits
on the whitespace that ends an escaped identifier. Applied after the UTF-16 →
byte conversion, so a multi-byte character before the name changes nothing.
`Server::symbol_offset` in dispatch.rs uses it for the nine requests in the
table. Decided against shifting *inside* the feature modules (`nav.rs` etc.):
one place, one rule, and the requests with their own boundary rule are visibly
the ones still calling `offset`. The References view's rows now open with a
collapsed selection at the identifier's start — `vscode.open` cannot carry a
backwards `Selection`, so "select the name, caret at its start" is not
expressible through it, and the start is where VS Code's own view and go to
definition put the caret.
**B.** `Server::must_hold` is the rule, `Server::behind` the bookkeeping. The
prototype held every notification while a rescan a message asked for was
running (`answering_a_rescan`). That is a superset of what is needed and it
cost something real: a watcher event arriving during a rescan was then
applied *after* it, one scan each, instead of coalescing into one more scan.
`behind` is exact: `process_batch` sets it, for the message it is handling, to
"how many older messages are unapplied in the bursts around me", so a scan's
drain holds a notification only if something older really is waiting. Pinned
by `a_rescans_trigger_alone_in_its_burst_still_lets_newer_changes_apply_at_once`
(two bars: the rescan, and one more for both watcher events). Cancels follow
the same rule, so a cancel arriving after its held request now waits *with* it
and is honoured when the batch is replayed (before, it was dropped and the
request computed); a cancel naming a deferred request is still honoured where
it lands.
Answers to the brief's questions:
- *Must didClose/didSave/watched/config keep order?* Yes, all of them: the
rule is about the stream, not the method. A `didSave` held behind a held
request is applied after it — as the cheap one-file update, where before it
was folded into a whole rescan.
- *Other documents?* Same stream, same rule — `didClose(a)` then `didOpen(b)`
(a rename) cannot cross. `a_reopen_behind_a_held_close…` pins the one-
document form, the randomized test the cross-document one.
- *Starvation?* The scan drains exactly as before (the drain still reads, it
only holds). Progress is the scan's and unaffected. `shutdown` was already
held behind a rescan a message asked for and still is: measured with
`dev717/drv/exitmid.py` (see Timings). `exit` is read by `handle_shutdown`
off the connection, never queued.
- *Memory?* Under Assumptions.
- **One exemption, kept:** a navigation request the empty-answer rule
deferred (`Server::deferred`, startup scan only) is re-asked at the next
publish, and a `didChange` applied in between moves the text under its
position. That is the perf5r-publication design, not a reordering of
applied messages; the worst it gives is a stale or empty navigation answer,
never a buffer change. Not changed.
**C.** As the prototype: the `didOpen` arm sets `head_owed` and
`opened_mid_scan` when a scan is running; `answer_what_is_waiting` clears the
flag before the batch and takes it after. **Bound:** a held batch is handed
back only when `!answering && !rescan_wanted && !head_owed`; handling it
re-holds something only behind a `didOpen` it *applied* (each message is
applied once) or a rescan it asked for (one per scan), so hand-backs ≤
applied `didOpen`s + scans + 1 — the randomized test asserts exactly that
inequality every round, and base breaks it at seed 1, round 0 (37 hand-backs
for 2 `didOpen`s and 1 scan).
**P2.** The index now holds every open buffer (a `didOpen` that moves no scope
takes an unheld buffer in through `update_one_file`, the path F4 already
used) and forgets a closed one that `scope_could_take` says no scan would
hold. Both halves were needed: closing alone fixed `r2attack.py
excluded-close` "closed" and "saved then closed" and broke "reopened". Mid-scan
the open half does nothing (as before) and the close half asks for one more
scan. One existing test changed fixture, not assertion:
`sync::closing_a_dirty_buffer…` opened two files that were not on disk, which
now costs an index change on close; the files are written to disk so the test
asks what it always asked.
**P1, P3:** not changed — see Handshakes for what VS Code actually sends and
why the fix is a registration decision.
**Tests** (new files; each failing test was run against 58d3db3 plus only the
`probe` hook, in `scratchpad/dev717/basecopy`):
| test | 58d3db3 |
|---|---|
| `scan_ordering::a_change_drained_mid_rescan_waits_behind_an_older_change_held_with_a_request` | FAIL (holds v2) |
| `scan_ordering::incremental_changes_held_mid_rescan_are_applied_in_the_order_they_were_sent` | FAIL (second insert one line off) |
| `scan_ordering::a_change_drained_mid_rescan_waits_behind_the_rest_of_the_burst_that_started_it` | FAIL (holds v2) |
| `scan_ordering::a_reopen_behind_a_held_close_leaves_the_buffer_open_with_its_new_text` | FAIL (buffer closed) |
| `scan_ordering::a_request_ahead_of_a_didopen_mid_startup_is_answered_and_the_drain_runs_once` | FAIL (answered after the bar) |
| `scan_ordering::a_request_behind_a_didopen_mid_startup_still_waits_for_the_buffer_it_names` | pass (kept behaviour) |
| `scan_ordering::a_rescans_trigger_alone_in_its_burst_still_lets_newer_changes_apply_at_once` | pass (kept behaviour) |
| `caret_boundary::every_symbol_request_answers_the_same_just_past_a_name_as_at_its_start` | FAIL (references `[]`) |
| `caret_boundary::a_caret_after_a_dot_is_on_the_member_and_before_it_on_the_instance` | FAIL |
| `caret_boundary::the_column_past_a_name_is_counted_in_utf16_after_non_ascii_text` | FAIL |
| `outside_buffers::an_excluded_buffer_is_held_while_open_and_forgotten_when_closed` | FAIL |
| `outside_buffers::a_buffer_not_on_disk_is_held_while_open_and_forgotten_when_closed` | FAIL |
| `outside_buffers::closing_a_buffer_the_scope_takes_leaves_the_index_alone` | pass (kept behaviour) |
| `ordering_random::random_bursts_keep_every_buffer_and_answer_every_request_once` | FAIL (C bound, seed 1 round 0; with that check disabled, B: seed 1 round 5, `a.sv` lost an edit) |
| `caret::tests` (7, the rule itself) | — (new module) |
**Randomized test** (`ordering_random.rs`): a seeded xorshift client with three
documents sends bursts of 1–4 messages — full and incremental `didChange`s
(insert or delete a line, ranges in the client's own current text),
`didOpen`/`didClose`, `$/cancelRequest` for a random earlier id, hover /
definition / documentSymbol / workspace/symbol, and watcher create/delete
events; 70 % of rounds put a rescan trigger at a random place in the round's
first burst, and 0–6 more bursts land at the scan's interleave points through
the probe. The startup scan gets 1–5 scripted bursts too (that is where C
lives). After every round: the server's open buffers are the client's and
their text is byte-equal; hand-backs ≤ `didOpen`s + scans + 1. At the end:
every request answered exactly once, and documentSymbol of every open buffer
plus the created packages equal a fresh server's on the same disk and
buffers. Normal suite: seeds 1–12 × 10 rounds, ≥ 200 bursts must land
mid-scan (300 do), 0.8 s debug. `#[ignore]`d long run: seeds 100–399 × 40
rounds, ≥ 10 000 mid-scan bursts, 32 s in release — passes.
**QA's oracle against this binary** (logs `scratchpad/dev717/logs/`), none
with `QA_REPAIR` (the "re-send buffers before each check" workaround):
| run | 58d3db3 / QA | now |
|---|---|---|
| `rand_run.py` corpus, push, seed 7 × 200 (every 25) | divergent at step 200 (F6) | 8 checks, 0 divergent |
| `rand_run2.py` OpenTitan sample, seed 42 × 500 (every 25), `QA_FRESH_SAVE=1` as in QA's run | step 350 divergent (F6) | 20 checks, 0 divergent |
| `rand_run.py` full OpenTitan `hw`, seed 21 × 50 (every 50) | 309 answers differ | 0 differ |
| `small.py`, workspace + folder scope, pull and push | — | 94 + 94 ok; only `NEGCTL-silent` diverges (both scopes), as it must |
| `outside.py`, pull and push | — | 14/14 and 14/14 ok (re-run on the final binary too) |
| `r2attack.py` (all cases) | `directory-create`, `held-directory-deleted` (P1), `excluded-open-close` closed / saved-then-closed (P2) diverge | only the two P1 cases diverge |
Seed 42 run *without* `QA_FRESH_SAVE` diverged at step 50 on an excluded
buffer (`qa_excl/qa_x0.sv`) the incremental server now holds while it is open
and the fresh side does not — the fresh server's documented startup race (a
buffer opened while its startup scan takes its work list is not taken in),
which is what `QA_FRESH_SAVE` exists to remove; with it, 0 divergent over 500
steps.
**Re-index lane sweeps** (release, `--ignored a_seeded_sweep`): corpus 3
seeds and OpenTitan sample 2 seeds, both pass.
**Timings** (release, full OpenTitan `hw` 4 061 files, workspace scope; the
machine is shared with another lane):
| | 58d3db3 | now |
|---|---:|---:|
| startup scan, cold (median of 3) | 2 104 ms | 2 077 ms |
| startup scan, warm (median of 3) | 1 124 ms | 1 124 ms |
| `perf.py`, median of 5, save → `reindex_one` line: uart_tx comment / uart_tx signal / prim_flop signal / prim_flop top / uart_reg_pkg member / prim_assert / prim_mubi member / prim_mubi top / tlul_pkg top / new `uvm_object` / new `` `define`` / clk_rst_if top | 0.04 / 8.2 / 8.1 / 67.3 / 22.8 / 3.5 / 97.9 / 98.8 / 85.4 / 13.4 / 9.5 / 28.6 | 0.04 / 8.6 / 8.4 / 67.1 / 23.5 / 3.4 / 106.5 / 103.2 / 84.3 / 10.5 / 14.6 / 30.0 |
| watcher echo, every row | 0.03–0.35 ms | 0.02–0.33 ms |
| C: `[hover, didOpen(B), tokens(B)]` in a cold startup (`livelock2.py`) | 318.6 s | 1.70 s scan, hover 0.68 s |
| `didClose` of a held file (P2's scope check), median of 3: prim_assert (174-file dir) / top_earlgrey / uart_core / dv_base_env | 0.02 / 0.16 / 0.13 / 0.02 ms | 1.22 / 0.41 / 0.27 / 0.22 ms |
| `didOpen` of the same four | 0.21 / 1.64 / 1.28 / 0.31 ms | 0.20 / 1.57 / 1.15 / 0.28 ms |
| shutdown sent mid-rescan, behind a held hover and change (`exitmid.py`) | answered 0.75 s, exit 0.92 s later | answered 0.76 s, exit 0.87 s later |
The save rows move by noise either way except `prim_mubi_pkg` (+5–9 ms of
~100) and the new `` `define`` (+5 ms), both single-digit and in rows whose
work this round does not touch (nothing here runs on a save); a `didClose`
now pays the scope walk of its directory, about a millisecond at worst.
**Test hook:** `server/probe.rs` (`#[cfg(test)]`, thread-local) — the
transport cannot be timed against a scan's files, so a test scripts what
arrives at each interleave point. One `#[cfg(test)]` line in
`answer_what_is_waiting`.
**Files** (production lines, non-blank non-comment, before `mod tests`; base
in parentheses): `server/mod.rs` 203 (186), `server/dispatch.rs` 491 (486),
`server/index.rs` 292 (265), `server/notification.rs` 252 (244),
`server/batch.rs` 74 (`opened_in` removed), `server/startup.rs` 173 (+2),
`state/watched.rs` 95 (+3), `state/incremental.rs` 145 (+4), new
`caret.rs` 23, new `server/probe.rs` 46 (test-only); `main.rs` +1;
`editors/vscode/referencesView.js` +5. Tests: `server/tests/{scan_ordering,
caret_boundary,ordering_random,outside_buffers}.rs` new, `tests/mod.rs`
+4 module lines, `tests/sync.rs` fixture, `referencesView_test.js` one
assertion.
### 2026-11-19 — dev agent: fix round (QA-1 … QA-5, the size note)
**QA-1 — P2 reverted.** `take_in_if_unheld`, `forget_if_outside`,
`Workspace::holds_outside_the_scope` and `Workspace::forget_file` are gone;
`state/watched.rs`, `state/incremental.rs` and `server/tests/sync.rs` are
byte-identical to 58d3db3 again (the `sync` fixture change is undone —
without P2 it is not needed), `server/tests/outside_buffers.rs` is deleted.
Making open/close of an unheld file cost < 1 ms is not reachable at the
server layer: adding or removing one file shifts ids and rebuilds the
completion tables and the include naming (QA's `sample`), so it is filed as
an index-layer change (Handshakes, with QA-2 and QA-7a). QA's drivers,
full OpenTitan, before the other lane's load test started:
| `lat717.py` (median of 5), didOpen / didClose | 58d3db3 | round 1 (QA) | now |
|---|---|---|---|
| held files | 0.83–2.72 / 0.11–0.27 ms | 0.47–1.74 / 0.39–1.02 ms | 0.80–3.43 / 0.11–0.29 ms |
| outside the root | 0.57–0.59 / 0.08–0.10 ms | 185–189 / 222–230 ms | 0.54–0.56 / 0.06–0.08 ms |
| excluded | 0.55–0.59 / 0.07 ms | 188–190 / 222–225 ms | 0.44–0.81 / 0.07–0.08 ms |
| outside / excluded, 200 buffers open | 0.47–0.60 / 0.07–0.08 ms | 201–228 / 258–279 ms | 0.52–0.58 / 0.06–0.08 ms |
| `p2perf.py`: 2 000 outside files opened and closed | 0.7 s | 806 s | 0.7 s |
| `p2perf.py`: didClose with ~200 open, in-scope / outside (median) | 0.13 / 0.09 ms | — | 0.11 / 0.09 ms |
**QA-3 — the rule narrowed** to "no notification overtakes an older
notification" (`must_hold`; the soundness argument is under Assumptions).
Chosen over a staging-only patch because it is the rule B actually needs and
the broad rule bought no state the client could see; the staging case then
needs nothing special. `live717.py staging`, first hover with a request ahead
of the first `didOpen`: 58d3db3 0.111–0.133 s, round 1 0.151–0.160 s, now
0.116–0.125 s (3 × 3 runs). Cancels: one waits whenever anything is held
(so a late cancel of a held request is still honoured); `changes_state`
excludes them from what makes a notification wait. New test
`a_change_behind_only_a_held_request_applies_at_once_and_a_late_cancel_waits_with_it`
pins both halves. Every earlier test, the randomized one (fast and the
`#[ignore]`d 300-seed run) and f6.py's six variants pass unchanged.
**QA-4 — documented, not changed.** QA's `c717.py` (cold full OpenTitan, 16–18
bursts `[request, didOpen×1–3]` in the first 0.2 s) on the narrowed rule:
scan ends 3.74–4.17 s (5 seeds), answers 0.02–4.17 s, median 1.40–1.68 s; QA
measured 2.8–4.2 s on round 1, the same 26 opens without requests 1.66–1.89 s.
Each request behind an applied `didOpen` is held until the work list
re-ordered round that buffer has indexed its neighbourhood, and the hand-back
then forces a publish (a merge over the index so far) so the answer can see
it — one per burst here. Coalescing hand-backs would mean answering a later
burst's requests before *its* neighbourhood is in, which is the §P4b `[]`
the head rule exists to prevent; cheaper publishes are the index layer's.
So the cost stays: bounded (≤ one forced publish per applied `didOpen`),
seconds, against ~400 s on base.
**QA-5 — the changelog** now names what is ordered: edits, opens, closes,
saves and the other notifications (not responses, not deferred navigation
requests).
**Size.** `process_batch` 95 → 69 lines: the splice into `held` is
`Server::hold`, and answering one request (cancelled / deferred / computed)
is `Server::answer_from_batch`. No behaviour moved.
**Fix-round checks against this binary** (`dev717/logs3`, none with
`QA_REPAIR`). Another lane ran an 18-busy-loop load test on this machine from
about 11:00 into the oracle runs, so the latency numbers below that window are
not comparable and were re-taken after it eased.
| run | result |
|---|---|
| `refpos.py` (A1) | col 27 = col 25 (refs 3, def 1, highlight 2, hover), col 28 nothing — unchanged |
| `f6.py` held / tail / control, full and incremental | all six: server holds v3, incremental inserts in place |
| `livelock2.py hover` (C), after the load eased | hover 0.66–0.90 s, tokens(B) 0.74–0.99 s, scan ends 1.67–2.15 s (3 runs) |
| `q1min.py` | answered 0.96 s, one progress cycle |
| corpus push 7 × 200 | 8 checks, 0 divergent |
| OpenTitan sample 42 × 500 (`QA_FRESH_SAVE=1`) | 20 checks, 0 divergent |
| full OpenTitan 21 × 50 | 0 divergent |
| new: corpus push 111 × 300 (`rand_run2.py`) | 12 checks, 0 divergent |
| new: OpenTitan sample 211 × 300 (`QA_FRESH_SAVE=1`) | 12 checks, 0 divergent |
| `small.py` pull and push, both scopes | 94 + 94 ok; only `NEGCTL-silent` diverges, as it must |
| `outside.py` pull and push | 14/14 and 14/14 |
| `r2attack.py` | P1's two cases and P2's two (excluded-open-close closed / saved then closed) diverge — 58d3db3's set, as the revert intends |
| full `tools/gates.sh` | PASS every step; `lucisv_server` 2 030/0, corpus 814/6 |
**Production lines now** (as before, base in brackets): `server/mod.rs` 215
(186), `server/index.rs` 267 (265), `server/notification.rs` 248 (244),
`server/batch.rs` 77 (`opened_in` removed, `changes_state` added),
`server/dispatch.rs` 491 (486), `server/startup.rs` +2, `caret.rs` 23,
`server/probe.rs` 46 (test-only); `state/` untouched.
## Changelog paragraph (for the lead)
**Find All References, Go to Definition, hover, highlight and rename now work
with the cursor just after a name.** A double-click, a click on the right half
of the last letter, or a click on a row of lucisv's References view leaves the
cursor there, and the server used to look at the character after the name —
so VS Code said "No references found" until you clicked away and back. The
References view now also puts the cursor at the start of the name it opens.
**An edit typed while the workspace was re-indexing could be applied out of
order**, leaving the server's copy of the file different from the editor's
until it was closed and reopened; edits, opens, closes, saves and the other
notifications the editor sends are now applied in the order it sent them. **A
file opened while the first index of a session was being built could make
that index take minutes instead of seconds** on a large workspace (about
300 s instead of 2 s on OpenTitan); fixed.
## QA log
### 2026-11-19 — QA agent (Opus 5.5)
**Verdict: PASS WITH FINDINGS.** No lost, duplicated or reordered message, no
deadlock, no wrong buffer text and no wrong rename found in anything below. One
**High** finding (QA-1, a P2 cost: opening or closing a file the index does not
hold now blocks the loop ~0.2 s on OpenTitan) should be fixed before release;
the rest are Low/Info or pre-existing. Everything ran against release binaries
built here (`qa717/bin/new` from this worktree, `qa717/bin/base` from
`git archive 58d3db3`, own `CARGO_TARGET_DIR`s). All drivers and logs are in
`scratchpad/qa717/{drv,oracle,logs}`; every tree was a scratch copy, every
index store under `qa717/st`; `~/.cache/lucisv-opentitan-full` `git status
--short` empty and nothing under either cache newer than this QA's start.
**Baseline.** `tools/gates.sh` (full, logs `qa717/gates/`): PASS — fmt,
clippy `-D warnings`, build, every suite (`lucisv_server` 2 032/0,
`vlog_semantic` 435/0, `lucisv_mcp` 384/0), docs, corpus 814/6, node 37/0.
One guard kill — see QA-6. Ignored release runs (`--ignored ordering_random
sweep_over_the_corpus sweep_over_an_opentitan`, guarded, trees from scratch
copies): 3/3 pass. Counts vs 58d3db3: `lucisv_server` unit 1 901 + 43 ignored →
1 922 + 44 (+14 server tests, +1 ignored long run, +7 `caret` unit); integration
106/3 unchanged; no pre-existing test removed or edited except `sync.rs`.
**The changed fixture:** with the base fixture on the new code the test fails
`generation 6 != 5` — P2's take-in/forget of two not-on-disk buffers is an extra
index change and republish. Writing the files to disk keeps the test's subject
(the closed buffer's dirty text is never analyzed, the other one flushes) and
every assertion's meaning; accepted. **New tests on base:** grafted
`probe.rs` + its one `#[cfg(test)]` call + the four test files onto the
58d3db3 archive: exactly the 11 the README lists fail, the 3 "kept behaviour"
tests pass. `probe` is `#[cfg(test)]` at `server/mod.rs:60` and
`server/index.rs:522`, no other reference. Sizes: every touched file under 600;
`process_batch` is 95 lines (78 on base), mostly comment — over the 80 line
"investigate" mark (Info).
**B/C code read.** `must_hold`, `behind`, `process_batch`,
`answer_what_is_waiting`, `waiting_for_this_scan`, `run`'s replay,
`take_the_answer_out_of_held` and the staging loops: every message put in
`held` is taken out by `run` (loop top) or by the startup scan's drain; `held`
non-empty never outlives a scan, and nothing waits on a client response except
staging's bounded waits (the only `recv_timeout`s). `behind` is restored on
every exit of `process_batch` that the caller reads. No path found where a
message is applied twice or dropped.
**B — ordering, own stdio driver** (`drv/ord717.py`, independent of the probe):
4 synthetic documents in 4 folders, seeded bursts of 1–5 messages written in
one `write()` — incremental single- and multi-change and full `didChange`s,
`didOpen` (disk or new text), save-then-`didClose`, `didSave` (±text),
documentSymbol / hover / definition / references / semanticTokens / highlight /
workspace/symbol, `$/cancelRequest` of a recent id, watcher create/delete of
package files, an unknown notification, a malformed `didChange` — while scans
run: the startup scan, workspace-folder add/remove, a pushed and an *empty*
(`workspace/configuration` pull) config change, a save of an unheld file,
watcher creates. Checked: **every documentSymbol answer equals the client's
text at the moment the request was sent** (the order contract, exact
names/lines/columns); after each settle every buffer's text, open/closed state
and the watcher/save effects; every id answered exactly once; a final battery
(documentSymbol, semantic tokens, hover/references/definition at both ends of
every name, workspace/symbol, push diagnostics) equal to a fresh server's.
Runs: corpus seeds 1–3 ×30 and 10–17 ×60 (workspace), 20–23 ×60 (folder); full
OpenTitan seeds 30–32 ×40 (workspace), 40–41 ×40 (folder): **≈ 8 700 bursts,
≈ 27 000 messages, 85 % of bursts sent while a scan was running, ≈ 4 500
at-send-time checks — 0 ordering/text/state failures, 0 duplicate or missing
responses.** Fresh oracle: equal in every run once the driver saved dirty
buffers before comparing (the 6 seeds that had differed, re-run, and the 5 that
never had); the 12 runs that differed before that correction differed *only* in
`workspace/symbol` for module names typed but not yet saved — the documented
index staleness of unsaved text, not this lane. The same driver on **base fails at once** (seed 1: 22 failures,
both scopes — stale documentSymbol answers, a buffer one edit behind).
(Two driver corrections were needed, both *my* model: duplicate wire names
collapse in documentSymbol; and unsaved buffer text reaches the index only at a
scan or save, so the final oracle saves dirty buffers first. A third thing the
driver found is pre-existing — QA-7.)
**Liveness / latency** (`drv/live717.py`, full OpenTitan, whole rescans of
~0.6–1.8 s; base vs new):
| case | 58d3db3 | now |
|---|---|---|
| hover held mid-rescan, then its cancel: cancel → answer | 0.55–0.59 s, honoured 4/5 (once computed) | 0.58–0.62 s, honoured 5/5 |
| shutdown behind a held hover + change mid-rescan: answer / exit | 0.65 s / 0.86 s; hover answered first | 0.66 s / 0.94 s; hover answered first |
| `exit` alone mid-rescan with a held queue | exits 0.8–1.6 s | exits 1.0–1.6 s |
| server's `workspace/configuration` (+ progress create, lens refresh) held by the client, answered mid-burst while notifications are held | no deadlock, final text right | no deadlock, final text right |
| 20 000 incremental `didChange`s flooded behind a held request across rescans | settle 23 s, RSS peak 686 MB, **text wrong** | settle 27 s, RSS peak 679 MB, text right |
| VS Code-like typing (change + tokens + highlight per key, 30 ms) through 5 rescans | scans 1.5–1.85 s, **text wrong at the end** | scans 1.6–1.86 s, text right |
| request before the first `didOpen` during staging: first hover | 0.11–0.13 s | 0.15–0.18 s (QA-3) |
(The shutdown case exits with rc 1 in 2 of 3 runs on *both* binaries — pre-existing, Info.)
**C bound** (`drv/c717.py`: cold startup on full OpenTitan, 26 `didOpen`s in
13–14 bursts `[request, didOpen×1–3]` every 2–10 ms): base — every answer at
406.9 s, scan ends 406.9 s. Now — scan ends 2.8–4.2 s (5 seeds), answers
0.03–4.15 s, no duplicate. Same 26 opens with no requests between them: scan
1.66–1.89 s; plain cold startup 1.65 s. So C is fixed and bounded, but see QA-4.
**A1 sweep** (`drv/a1sweep.py`): 200 corpus files × 25 tokens and 150 OpenTitan
files × 20 tokens (identifiers, keywords, macros, system tasks, numbers), all
nine requests: **69 030 token×request pairs; end == start == middle on the new
server in every one**; new == base at the start in all but 6 (all in
OpenTitan's duplicated `top_*/ip/ast` modules — `rename` there is
nondeterministic on base too: 4 edit / 4 refused in 8 fresh base servers; QA-7);
**one column right of the name (40 158 cases) new == base in every one.**
Edges (`drv/a1edge.py`, `drv/a1rename.py`): `\foo `/`\a+b ` (on the ending
space: the name; after it: nothing), `$bits(a|)`, `` `FOO| ``, `` `BAR|(b) ``,
`8'hFF|` / `8'hF|F` / `12|` (nothing — no `hFF`/`FF` signal resolved),
`begin|`/`end|`, `u_a|.b`/`u_a.|b`/`u_a.b|`, `pkg|::x`/`pkg:|:x`/`pkg::|x`/`pkg::x|`,
`a|+b`, `x|[i]`, `x[i|]`, `f|(a)`, `f(a|)`, end of line, `endmodule : d|` at EOF
with and without newline, empty file, column 0, CRLF, tabs, non-ASCII and an
astral character before the name, `ifdef`-out region: end-of-name == start
everywhere. Comments, strings and a `` `define`` body: nothing at start and end.
Rename/prepareRename at the end-of-name caret: placeholder and range are the
whole name and the applied edit is byte-identical to the one from the start in
all nine shapes — never the neighbour. A position past the end of a line now
resolves the line's last name (VS Code never sends one; Info). **Request table:**
every arm in `dispatch.rs` that reads a position is either one of the nine or in
the "as sent" rows (linked editing, signature help, completion, inline
completion, on-type, selection range, the two code-action uses of
`range.start`, executeCommand); declaration/implementation/moniker are not
served; nothing missed.
**P2** (`drv/p2.py`: excluded / outside-the-root / not-on-disk buffer ×
open-close, open, close-reopen, save-close, change-close, open-mid-scan-close,
close-mid-scan, open+close in one burst; fresh server with the same buffers
opened before its scan): workspace scope **24/24 equal (base 12/24)**. Folder
scope: the outside-the-root file stays held after close — the opened file's
folder widened the scope, which never shrinks; base does the same in an
isolated tree, by design. 2 000 distinct outside files opened and closed: RSS
695 → 718 MB, none left in the index — but see QA-1 for the time it took.
`QA_FRESH_SAVE` — see QA-2.
**Re-index oracle on this binary** (QA 71.1's scripts, no `QA_REPAIR`):
`small.py` pull and push, both scopes: only `NEGCTL-silent` diverges, as it must;
`outside.py` 14/14 both. Previously failing seeds: corpus push 7 ×200 — 8 checks,
0 divergent; full OpenTitan 21 ×50 — 0 differ; OpenTitan sample 42 ×500 with
`QA_FRESH_SAVE` — 20 checks, 0 divergent (without it: divergent at step 50, the
QA-2 race). New seeds: corpus 101–103 ×500 and push/folder 104 ×500 — 0 divergent;
OpenTitan sample 201–203 ×500 — 0 divergent with `QA_FRESH_SAVE`, divergent at
step 150–200 without (every diff an excluded `qa_excl` buffer, QA-2); full
OpenTitan 301 ×100 — 13 answers differ at step 100, **identically on base**
(QA-7).
**References view.** VS Code's `TextEditorOpenOptions.from` converts
`selection` with `Range.from` and `codeEditorWidget.setSelection(IRange)` makes
the range's *end* the position — so base put the caret just past the name, the
A1 spot; a collapsed range at `range.start` puts it at the name's start, where
Shift+F12 works on a base server as well as this one (VS Code's own references
view uses `range.with({ end: range.start })`). Cost: the row no longer
*selects* the identifier. The test asserts the new collapsed range. The P1
analysis checks out against `watcher.ts` (`coalesce`: deletes under a deleted
parent dropped) and `extHostFileSystemEventService.ts` (each event filtered by
the registered glob). The extension sets no `wordPattern`, so VS Code's default
word rule is the one in play.
**Timings** (release, full OpenTitan, workspace scope, medians of 5, machine
shared with this QA's own runs): cold startup 1 667 → 1 681 ms, warm 747 → 747
ms. Open/close (`drv/lat717.py`, didOpen → its publish, didClose → its clearing
publish):
| file | 58d3db3 open / close | now open / close |
|---|---|---|
| held (prim_assert, top_earlgrey, uart_core, dv_base_env) | 0.46–1.83 / 0.07–0.18 ms | 0.47–1.74 / 0.39–1.02 ms |
| outside the root, 0 other buffers | 0.33–0.36 / 0.06–0.07 ms | **185–189 / 222–230 ms** |
| excluded, 0 other buffers | 0.34–0.37 / 0.06–0.07 ms | **188–190 / 222–225 ms** |
| outside / excluded, 200 buffers open | 0.31–0.38 / 0.05–0.07 ms | **201–228 / 258–279 ms** |
Saves (QA 71.1's `perf.py`, 5 reps, save → `reindex_one` line, base / now):
uart_tx comment 0.05 / 0.04, uart_tx signal 5.4 / 4.2, prim_flop signal 4.4 /
4.3, prim_flop top 49.6 / 48.8, uart_reg_pkg member 12.9 / 12.1, prim_assert
1.4 / 1.5, prim_mubi member 93.5 / 91.2, prim_mubi top 90.3 / 85.1, tlul_pkg top
69.9 / 67.1, new `uvm_object` 4.8 / 4.1, new `` `define`` 6.9 / 6.2, clk_rst_if
top 16.6 / 26.2 ms; echoes 0.03–0.28 ms both. Unchanged within noise except
clk_rst_if, the one row that moved (the dev measured it 28.6 / 30.0, so most
likely noise; nothing in this lane runs on a save).
**Findings**
- **QA-1 (High, performance, P2).** `server/index.rs:212-224`
(`take_in_if_unheld`) and `:189-202` (`forget_if_outside`), called from
`notification.rs:109` and `:285`. Taking an unheld buffer in on `didOpen`
and forgetting it on `didClose` each run a one-file index update plus lens
refresh, hierarchy bump and `republish_all`, synchronously on the message
loop. On full OpenTitan that is ~190 ms per open and ~225 ms per close (table
above; ×500–3 000 vs base), with nothing else open; 2 000 outside files opened
and closed took **806 s vs 0.7 s** (`drv/p2perf.py`). A `sample` of the server
meanwhile sits in `Candidates::unit_tables`/`merge_words`/`take_index_tables`,
`IncludeGraph::refresh_naming_all`, `dependents::note`,
`WorkspaceIndex::push_records`. Every keystroke, hover and completion queued
behind such an open/close waits for it. Repro:
`python3 -I drv/lat717.py BIN <OpenTitan copy> 5`. The README's timing rows
measured only *held* files. Correctness of P2 is fine; its cost is not.
- **QA-2 (Low, P2 gap; on the `QA_FRESH_SAVE` question).** A buffer the index
does not hold that is opened while a scan is running is not taken in, and
nothing takes it in when that scan ends (`take_in_if_unheld` returns at
`scan_owed()`): `drv/race717.py BIN <OpenTitan copy> 0.5` — an excluded file
opened 0.5 s into the startup scan is still unheld after settle, base and new
alike; opened before the scan it is held. So "the index holds every open
buffer" (Handshakes 4) is true only for buffers opened outside a scan, and the
same final state answers differently depending on when the buffer was opened.
The dev's argument is sound as far as it goes — the divergence `QA_FRESH_SAVE`
removes is the *fresh* server losing this race, not the incremental one
getting anything wrong — but it is a real, user-visible nondeterminism of the
server (pre-existing in kind), and `QA_FRESH_SAVE` hides it. Suggest taking in
open unheld buffers when a scan finishes, or documenting the limit in
Handshakes 4 rather than only in the code comment.
- **QA-3 (Low, startup).** `startup.rs:283-296` (`await_opening_file`): a
request that arrives before the first `didOpen` during staging is held
(`staging`), and the `didOpen` behind it is now held too (`must_hold`:
`held` non-empty), so the "wait for the first buffer" loop never sees it,
waits its full 25 ms bound, and the startup scan does not lead with the user's
folder. Measured first hover 0.15–0.18 s vs 0.11–0.13 s (`live717.py staging`).
Harmless to correctness; not mentioned in the README.
- **QA-4 (Low, C cost).** The C bound holds (≤ one hand-back per applied
`didOpen` + 1), but each hand-back forces a `publish_scan`: 26 opens
interleaved with requests stretch the cold OpenTitan startup scan from
1.65–1.9 s to 2.8–4.2 s, and in 2 of 5 seeds a request is answered only at
the scan's end (3.7–4.2 s). Five minutes → four seconds, so this is a note,
not a blocker; the README's 1.70 s figure is for the 3-message `livelock2`
burst.
- **QA-5 (Info, docs).** The changelog's "every message is now handled in the
order it was sent" overstates it: responses and deferred navigation requests
are exempt (both explained in the Work log). Suggest "every edit".
- **QA-6 (Info, pre-existing, outside this lane).** `tools/gates.sh`:
`suite:lucisv_mcp` was KILLED by the guard at 600 s and passed on the retry;
the hung test was `qa_m3::qa_lucisv_check_over_the_same_tree_while_the_server_formats`
(`crates/lucisv_mcp/tests/qa_m3.rs:687`). `lucisv_mcp` does not depend on
`lucisv_server`, and the 0.65.5 release gates log shows the same KILLED →
retried. Not filed anywhere in `TODO.md`; reporting as CLAUDE.md asks.
- **QA-7 (pre-existing, outside this lane — file for the backlog).** (a)
Closing an **unsaved in-scope** buffer whose text a rescan took into the
index leaves that text in the index after the close (`drv/closeidx.py BIN
rescan`: `qd_buf` survives the close, a fresh server holds `qd_disk`) —
identical on base; P2 covers excluded/unlisted files only. (b) `rand_run.py`
full OpenTitan seed 301 ×100: 13 answers differ at step 100 (pull diagnostics,
references, incoming calls in `top_earlgrey/ip/ast/rtl/usb_osc.sv`) —
byte-identical divergence on base. (c) Rename of a port of a module defined
twice in OpenTitan (`top_englishbreakfast/ip/ast/rtl/adc.sv:81`
`rst_adc_ni`) is edit-or-refuse at random across fresh servers, base and new
(`drv/dup.py`). All three involve state this lane did not touch.
**Fixed myself:** nothing. **Not verified (no VS Code here):** the four items
under Status; that VS Code itself never sends a request ahead of its first
`didOpen` during staging (QA-3's trigger).
### 2026-11-19 — QA agent (Opus 5.5), round 2 (f1d4492 on dbb2349)
**Verdict: PASS WITH FINDINGS** (one Info-level note on the narrowed rule,
pre-existing in kind; nothing new). Binaries: `qa717/bin2/new` (this tree),
`qa717/bin2/base` (`git archive dbb2349`), `qa717/bin2/r1` (round 1's binary,
for comparison). Caches untouched as in round 1.
**Baseline.** Full `tools/gates.sh` (logs `qa717/gates2/`): PASS every step
including `cross`; `lucisv_server` 2 030/0 (dbb2349: 1 901 + 106 + 4 = 2 011 →
1 920 + 106 + 4, +19 and +1 ignored), `vlog_semantic` 435, `lucisv_mcp` 384 (no
guard kill this time), corpus 814/6, node 37. Ignored release runs 3/3 pass.
P2's revert is a clean one: no `state/` file and no `sync.rs` in
`git diff dbb2349`. `caret.rs`, `dispatch.rs`, `referencesView.js` and
`caret_boundary.rs` are byte-identical to round 1.
**What the narrowed rule promises, stated as checked** (`must_hold`,
`server/mod.rs`): (i) after settle every open buffer's text, and which buffers
are open, equal the client's; (ii) non-cancel notifications are applied in the
order sent, across documents — a notification is applied only when no older one
is in `held` or in an enclosing burst's unapplied tail; (iii) every request is
answered exactly once; (iv) a request is answered against the state after every
notification sent before it, and possibly after some sent after it — so its
answer reflects *some* client state between sending and answering, never one the
client did not have (each `didChange` is applied whole, in one handler call).
**Ordering driver** (`drv/ord3.py`: round 1's driver with check (iv) — every
documentSymbol answer must equal the expected symbols of the client's state at
send or of some later state the client had sent before the answer arrived, each
state recorded per message): corpus seeds 510–519 ×60 (workspace), 520–523 ×60
(folder); full OpenTitan 530–533 ×40 (workspace), 540–541 ×40 (folder);
incremental single/multi-change and full-sync changes, scans in flight as in
round 1. **20 runs, 9 118 bursts (≈ 87 % mid-scan), 28 663 messages, 4 693
state checks: 0 failures, 0 duplicate or missing responses, every fresh oracle
equal; 13 answers reflected a later state than at send, each one a state the
client had.** The same check fails at once on dbb2349 (seed 501: answers
matching no client state, a buffer an edit behind). An earlier run of my
coarser `ord2.py` (states recorded per burst, not per message) flagged one
answer (seed 514) that matched no burst-final state; with per-message states the
same seed ran clean three times — a driver limitation, recorded.
**Harm hunt** (`drv/harm2.py`, `GAP=0.2`, full OpenTitan, index not persisted so
the rescan really interleaves; a request sent against v1 is held, then a
`didChange` to v2 that inserts a line above it is applied mid-scan):
| request held, then v2 applied | dbb2349 | round 1 | now |
|---|---|---|---|
| rename of `beta` at its v1 position | answered on v2: renames **`alpha`** (the name now at that position); edit consistent with v2 | answered on v1; applied to the client's v2 it **corrupts** (`logic qqa;`, `alpqq`) | **as dbb2349** |
| hover / definition / references | about `alpha`, v2 ranges | about `beta`, v1 ranges | as dbb2349 |
| formatting | edits for v2, applied to v2 = v2's own formatting | same | same |
| hover held, then `didClose` applied | `null` | answered from the open buffer | `null` |
| documentSymbol(A) held, then `didClose A` + `didOpen A2` | `null` | from A | `null` |
| documentSymbol(B) sent before `didOpen B` | B's buffer | `null` | B's buffer |
| `[documentSymbol, change v2]` in one burst, then v3 | answered on **v3** (B) | v1 | v1 |
So the narrowing restores dbb2349's late-request behaviour exactly — no harm
that base did not already have — and keeps B fixed (last row). Rename edits are
unversioned (`changes` map; `extract.rs:185` sends `version: None`), so a client
cannot reject a stale one by version; VS Code drops a rename or format result
when the buffer changed while it waited (its editor-state cancellation), so the
practical exposure is a client without that guard. **QA-8 (Info, pre-existing):**
a held position-taking request can resolve a *different* symbol when a newer
edit moved the text under its position — identical on dbb2349. Round 1's
strict rule had the opposite trade (right symbol, ranges for text the client no
longer had).
**Liveness** (`live717.py`, dbb2349 / now): cancel of a held request mid-rescan
answered 0.58–0.62 / 0.55–0.60 s, honoured 5/5 / 5/5; shutdown behind a held
hover + change answered 0.70 / 0.70 s, hover first, exit < 1 s (rc 1 in 2 of 3
on both, as round 1); `exit` alone 0.8–1.6 s on both; server→client requests
held by the client and answered mid-burst: no deadlock, final text right on
both; 20 000-change flood (now): settle 27.7 s, RSS peak 680 MB, text right;
typing through 5 rescans: scans 1.67–1.90 / 1.69–1.93 s, **text wrong on
dbb2349, right now**; staging (QA-3): first hover 0.13–0.15 / 0.13–0.14 s —
fixed (round 1 was 0.15–0.18 s).
**C** (`c717.py`, 26 opens in 13–14 `[request, didOpen×1–3]` bursts, cold full
OpenTitan): scan ends 2.59–3.32 s, answers 0.02–3.32 s (5 seeds), 0 duplicates;
round 1 2.8–4.2 s; dbb2349-class base 407 s; plain cold startup 1.51 s
(dbb2349 1.51 s, now 1.53 s; warm 0.71 / 0.70 s). QA-4 as documented.
**P2 revert confirmed.** `lat717.py`: outside/excluded didOpen 0.41–0.72 ms,
didClose 0.07–0.12 ms (dbb2349 0.37–0.79 / 0.06–0.13 ms); held files as base.
`p2perf.py`: 2 000 outside open+close 0.6 s (dbb2349 0.7 s), RSS flat.
`r2attack.py`: the same four divergent cases on both binaries
(directory-create, held-directory-deleted, excluded-open-close closed and
saved-then-closed); `outside.py` 14/14 equal on both, push and pull.
**A1** (code byte-identical): sample sweep 60 corpus files × 15 tokens, 7 830
token×request pairs — end = start = middle everywhere, start and end+1 = base
everywhere; `a1edge.py` all end = start; `a1rename.py` 9/9 identical.
**Oracle (no repair workaround):** `small.py` push and pull — only
`NEGCTL-silent` diverges (both scopes); corpus push seed 7 ×200 — 0 divergent;
full OpenTitan 21 ×50 — 0; OpenTitan sample 42 ×500 (`QA_FRESH_SAVE`) — 0.
New: corpus seed 601 ×500 — 10 checks, 0 divergent; OpenTitan sample 602 ×500
(`QA_FRESH_SAVE`, for QA-2's race) — 10 checks, 0 divergent.
**Findings this round:** QA-8 above (Info, pre-existing). Round 1's QA-1 and
QA-3 are fixed, QA-4 documented, QA-5 reworded; QA-2, QA-6, QA-7 stand as
written (pre-existing, outside this lane). **Fixed myself:** nothing. **Not
verified:** a real VS Code (the Status items, and whether VS Code's editor-state
cancellation really sends `$/cancelRequest` for a held rename).
## Review
**Lead, 2026-11-19.** Accepted for 0.65.8, after two QA rounds.
- The owner asked whether it was VS Code or the server. It was the server,
and it was not a race: an end-exclusive span met a caret VS Code considers
to be on the word. The investigation's deterministic reproduction
(`refpos.py`, column 27) settled that before any code was written, and
ruled out the things I would have guessed first — cancellation, deferred
answers, caching.
- B and C were found by other lanes' QA and are worse than the reported bug:
one corrupts the server's copy of a buffer, the other turns a 2 s startup
into minutes. Both come from treating queued messages as applied. I kept
them in this lane because they live in the same loop.
- I asked for P2 "only if small"; the dev's attempt cost 190 ms per open of
an outside file and QA caught it (806 s for 2 000 files). Reverted. The
right fix is in the index layer and is filed.
- The ordering rule was narrowed in the fix round from "no message overtakes
an older message" to "no notification overtakes an older notification".
That changes the invariant, so I sent it back to QA instead of accepting
the dev's own run. QA's harm table is what decides it: under the narrow
rule a held request behaves exactly as on 0.65.7; under the broad rule a
held rename was answered on the old text and would have corrupted the
client's newer one. Narrow is both faster and safer.
- Not verified: a real VS Code, in particular whether it drops a rename or
format result when the buffer changed while the request was held (QA-8
rests on that for its "Info" grade).
+24
View File
@@ -1444,3 +1444,27 @@ A warm build is walk 210 ms + store read 87 ms + read/hash/decode 318 ms +
merge 204 ms; a cold one parses instead (1 387 ms). The rows are not
like-for-like with the server's (it scans in stages and answers during the
scan); they sit side by side so a regression in either shows.
### 2026-11-19 — localized reindex (TODO §71.1)
What one save costs the index on the full OpenTitan `hw` tree (4 058 files,
scope `workspace`, 10 buffers open), measured over LSP with the real release
server and in-process with `state::tests::reindex_perf` (release,
`--test-threads=1`); medians, the machine shared with another lane's builds.
Details and the method: `docs/features/localized-reindex/README.md`.
| | before (7408fac) | after |
|---|---:|---:|
| `reindex_one`, any edit, any file | 141–158 ms | — |
| …the watcher's echo of a save / an unchanged record | 153–176 ms, everything republished | 0.07–1.1 ms, nothing sent |
| …a local signal in a module (`uart_tx`, `prim_flop`) | 144–145 ms | 5.2 ms |
| …a package member added (`uart_reg_pkg`) | 148 ms | 11.7 ms |
| …a line above everything in `prim_flop.sv` (125 instantiating files) | 144 ms | 61 ms |
| watcher event for a `.sv` the scope cannot take | 746 ms whole rescan | 3.5 ms, nothing |
| whole merge (`absorb`, startup / cached rescan) | 135 / 165 ms | 158 / 189 ms |
| warm startup scan (fix round, QA's `perf.py`, two runs) | 1 113 / 1 124 ms | 1 171 / 1 148 ms |
| `prim_mubi_pkg` member added, 677 importers (fix round) | 162 ms | 92 ms |
| readers table | — | 13 806 keys, 69 222 entries |
| mention census, one lint pass (average / worst file) | 51 µs / 2.8 ms | unchanged |
Probes: `tools/guard.sh -- cargo test --release -p lucisv_server reindex_perf -- --ignored --nocapture --test-threads=1`.
+38
View File
@@ -5,6 +5,44 @@ for you. The extension and its bundled language server share one version
number; the full engineering notes live in the
[project changelog](https://git.luci.ooo/lucio/lucisv/src/branch/master/CHANGELOG.md).
## 0.65.9 — 2026-11-19
- **The bundled MCP server (`lucisv-mcp`) no longer answers from a file's old
contents** after a same-size rewrite that restores its old modification
time (`cp -p`, `rsync -t`) — a Linux timing hole in its change detection.
- Nothing changes in the editor itself.
## 0.65.8 — 2026-11-19
- **Find All References works with the cursor just after a name** — after a
double-click, or a click on the last letter. So do Go to Definition, hover,
highlight and rename. (It used to say "No references found" until you
clicked away and back.) Rows in the References view now open with the
cursor at the start of the name.
- **Typing while the workspace is indexing can no longer scramble the
server's view of your file** (wrong symbols and diagnostics until the file
was reopened).
- **Opening files during startup no longer stalls indexing** for minutes on
a large workspace.
## 0.65.7 — 2026-11-19
- **0.65.6, now for every platform.** 0.65.6 was never published — it did not
compile for Windows. This release carries its changes: saving no longer
re-indexes the workspace, no surprise "indexing" bar for generated or
out-of-scope files, and the line-length warning follows your formatting
style's width.
## 0.65.6 — 2026-11-19
- **Saving no longer re-indexes the workspace.** On a large project a save
used to cost a whole-index pass, twice (once for the save, once for VS
Code's file watcher). A typical edit now costs a few milliseconds, and a
save that changes nothing the index records costs nothing.
- **No more surprise "indexing" bar** for generated files, files outside the
filelist or folder scope, or files reached through a symlink.
- **The line-length warning follows your formatting style's width.**
## 0.65.5 — 2026-11-19
- **Formatting styles, from a drop-down.** `lucisv.format.style` picks the
+27 -1
View File
@@ -30,7 +30,7 @@ Install **lucisv — Verilog/SystemVerilog** from the VS Code Extensions view,
then open a Verilog or SystemVerilog file. There is no separate server or CLI
setup.
The current release is **0.65.5**. Its platform packages include
The current release is **0.65.9**. Its platform packages include
`lucisv-server`, the `lucisv` command-line tool and `lucisv-mcp` (see
[Agents (MCP)](#agents-mcp)):
@@ -440,6 +440,32 @@ default):
}
```
## Release 0.65.9 highlights
Version 0.65.9 fixes the bundled MCP server answering from a file's old
contents after a same-size rewrite that restores its old modification time
on Linux; the editor features are unchanged.
## Release 0.65.8 highlights
Version 0.65.8 fixes Find All References (and definition, hover, rename)
answering "not found" when the cursor sits just after a name, keeps edits
typed during indexing in order, and removes a startup stall that could last
minutes on a large workspace.
## Release 0.65.7 highlights
Version 0.65.7 is 0.65.6 built for every platform (0.65.6 was never published:
it did not compile for Windows): saving is cheap on large projects, because
the language server updates only what an edit can reach.
## Release 0.65.6 highlights
Version 0.65.6 makes saving cheap on large projects: the language server
updates only what an edit can reach instead of re-resolving the whole index —
on OpenTitan a typical save drops from about 160 ms (twice) to a few
milliseconds.
## Release 0.65.5 highlights
Version 0.65.5 adds named formatting styles — `google`, `lowrisc`, `ansi`,
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "lucisv",
"version": "0.65.5",
"version": "0.65.9",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "lucisv",
"version": "0.65.5",
"version": "0.65.9",
"license": "MIT",
"dependencies": {
"vscode-languageclient": "9.0.1"
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "lucisv",
"displayName": "lucisv — Verilog/SystemVerilog",
"description": "Fast Verilog/SystemVerilog formatting, linting, navigation, refactoring, semantic highlighting and RTL design intelligence.",
"version": "0.65.5",
"version": "0.65.9",
"publisher": "guoliangchen",
"author": "Guoliang Chen",
"license": "MIT",
+7 -2
View File
@@ -95,7 +95,7 @@ function fileItem(group) {
return item;
}
/** A reference's row: the whole line, the identifier highlighted; a click selects it in its file. */
/** A reference's row: the whole line, the identifier highlighted; a click puts the caret on it in its file. */
function referenceItem(reference) {
const label = reference.text === ''
? { label: `line ${reference.line}` }
@@ -105,10 +105,15 @@ function referenceItem(reference) {
item.description = reference.declaration ? `declaration · line ${reference.line}` : `line ${reference.line}`;
if (reference.declaration) item.iconPath = new vscode.ThemeIcon('symbol-key');
item.tooltip = `${vscode.workspace.asRelativePath(uri)}:${reference.line}:${reference.character}`;
// The caret goes to the identifier's start, as VS Code's own references
// view and go to definition put it. `vscode.open` makes a range's *end* the
// caret (a selection's direction does not survive it), and a Find All
// References from just past a name used to ask about the next character.
const { line, character } = range.start;
item.command = {
command: 'vscode.open',
title: 'Open Reference',
arguments: [uri, { selection: range, preserveFocus: false, preview: true }],
arguments: [uri, { selection: new vscode.Range(line, character, line, character), preserveFocus: false, preview: true }],
};
return item;
}
+4 -1
View File
@@ -181,7 +181,10 @@ async function theCommandFillsGroupsAndRevealsTheView() {
assert.equal(topRows[0].command.command, 'vscode.open');
const [target, options] = topRows[0].command.arguments;
assert.equal(target.toString(), 'file:///ws/top.sv');
assert.deepEqual(options.selection, new Range(1, 27, 1, 28), 'a click selects exactly the identifier');
// At the identifier's start, as VS Code's own references view and go to
// definition put it: `vscode.open` makes a range's *end* the caret, and a
// search started from there used to ask about the character after the name.
assert.deepEqual(options.selection, new Range(1, 27, 1, 27), 'a click puts the caret on the identifier');
const crlfRow = labels(view.getChildren(groups[2]))[0];
assert.deepEqual(crlfRow.label, { label: 'assign y = top.r;', highlights: [[15, 16]] }, 'tab and CRLF handled');
+5 -1
View File
@@ -119,7 +119,11 @@ for each workspace member in turn, the doc-tests (`cargo test --workspace
--doc`), the corpus gate (`scripts/corpus_gate.sh` over
`~/.cache/lucisv-corpus`, as CI runs it; skipped with a note when the corpus
is absent — fetch it once with `tools/corpus_fetch.sh ~/.cache/lucisv-corpus`)
and the extension's `node --test editors/vscode/*_test.js`. It prints one line
the extension's `node --test editors/vscode/*_test.js`, and `cross` — a
`cargo check` of the three binaries for Windows and Linux with the rustup
toolchain the release build uses (skipped with a note when it is absent;
added after 0.65.6 passed every other gate and then failed to compile for
Windows). It prints one line
per step start and end, then a table (step, result, seconds, passed/failed,
log); it exits non-zero if any step failed. A step the guard killed is
retried once and reported as `KILLED → retried → pass|fail` — a kill that
+21 -1
View File
@@ -12,6 +12,12 @@
# over ~/.cache/lucisv-corpus as CI does (skipped, with a
# note, when that directory is absent; -c overrides it)
# node node --test editors/vscode/*_test.js
# cross cargo check of the three shipped binaries for Windows and
# Linux with the rustup toolchain release.sh --cross uses
# (skipped, with a note, when that toolchain is absent).
# Platform-conditional code is compiled nowhere else before
# the release build: 0.65.6 passed every other gate and then
# failed to compile for Windows.
#
# Each step's output goes to its own log under the log dir (default
# target/gates/<timestamp>/, -o overrides); the terminal gets one line per
@@ -41,6 +47,9 @@ repo_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$repo_root" || exit 2
log_dir=
corpus=$HOME/.cache/lucisv-corpus
# The toolchain release.sh --cross builds with; the Homebrew rust on PATH has
# no std for other targets.
cross_toolchain=$HOME/.rustup/toolchains/stable-aarch64-apple-darwin
only=
skip=
@@ -84,7 +93,7 @@ all_steps() {
local c
echo fmt clippy build
for c in $(crates); do echo "suite:$c"; done
echo docs corpus node
echo docs corpus node cross
}
# Does step $1 match the comma list $2? "suites" matches every suite:<crate>.
@@ -119,6 +128,7 @@ limits() {
suite:*) echo "300 4" ;;
docs) echo "300 2" ;;
corpus) echo "900 6" ;;
cross) echo "900 6" ;;
esac
}
@@ -133,6 +143,9 @@ set_command() {
corpus) cmd=(bash -c 'cargo build --release -p lucisv && scripts/corpus_gate.sh "$1"'
corpus-gate "$corpus") ;;
node) cmd=(node --test editors/vscode/*_test.js) ;;
cross) cmd=(env RUSTC="$cross_toolchain/bin/rustc" "$cross_toolchain/bin/cargo" check
--target x86_64-pc-windows-gnu --target x86_64-unknown-linux-musl
-p lucisv -p lucisv_server -p lucisv_mcp) ;;
esac
}
@@ -201,6 +214,13 @@ for step in $steps; do
echo "skipped: no corpus at $corpus (tools/corpus_fetch.sh \"$corpus\")" >"$log"
echo " skip $step (no corpus at $corpus)"
rows="$rows$step|SKIPPED (no corpus)|0|-|$log
"
continue
fi
if [ "$step" = cross ] && [ ! -x "$cross_toolchain/bin/cargo" ]; then
echo "skipped: no rustup toolchain at $cross_toolchain (tools/RELEASING.md)" >"$log"
echo " skip $step (no rustup toolchain)"
rows="$rows$step|SKIPPED (no toolchain)|0|-|$log
"
continue
fi