Files
lucisv/docs/features/viewport-highlight/README.md
T
Guoliang ChenandClaude Mythos 5.2 71d13b5fbe
ci / checks (push) Successful in 1m0s
ci / corpus (push) Successful in 18s
ci / linux (push) Successful in 6m4s
release / build-and-publish (push) Successful in 5m31s
Release 0.66.2: every source file names its author
Every tracked file that can carry a comment (880 of them) now opens with
"Author: Guoliang Chen, a Senior Digital Design Engineer" and closes with
"Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love,
luciochen.com", in the file's own comment syntax. No behaviour change: the
diff outside the version bump and changelogs is comment lines only.

- tools/stamp_author.py: writes the lines; idempotent, `--check` lists
  what is missing. Headers go under a shebang and under Markdown front
  matter.
- Left alone: test fixtures, cases and snapshots (byte-exact inputs), JSON
  and JSONL, logs, images, lockfiles, docs/site/dist (regenerated) and the
  LICENSE files (already carry the copyright line).
- tools/linux_check.sh: --help reads its header from line 3, now that the
  author line sits under the shebang.
- tools/gates.sh green on this tree: 5 545 tests, corpus 814/6 as before.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-24 12:11:09 -08:00

832 lines
50 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!-- Author: Guoliang Chen, a Senior Digital Design Engineer -->
# viewport-highlight
## Goal
Semantic highlighting must never wait for the workspace index. The owner's
words: *"Syntax highlight should always be running a localized-only version on
the viewport if possible. This highlight might not be 100% correct, but can be
later fixed. I don't want to wait for the whole database to be indexed before
the basic syntax highlight works."* So: a semantic-token request (`range`,
`full`, `full/delta`) for a buffer whose text is current is answered **from
that buffer alone, immediately**, even while a scan holds every other request;
a range answer costs the window, not the file; and when the index settles in a
way that changes what a buffer's colours would be, the server sends **one**
`workspace/semanticTokens/refresh` so the client re-requests and gets the
accurate answer.
## Measured first (2026-11-19, before any code)
Real binary (`target/release/lucisv-server --stdio --verbose`, 0.65.5 at
`80017a5`) over LSP stdio against the full OpenTitan checkout
(`~/.cache/lucisv-opentitan-full`, 4 058 indexable files under `hw/`), replaying
what VS Code does on open: `initialize` (VS Code's capabilities: configuration,
work-done progress, `semanticTokens` range + full/delta, `refreshSupport`),
`initialized`, the settings answer, `didOpen`, then at once
`semanticTokens/full`, `documentSymbol`, `foldingRange`, `codeLens`, and
100 ms later (the viewport contribution's debounce) `semanticTokens/range` for
lines 0–120 and `inlayHint`. Cold = empty `storagePath`, warm = the same store
reused. Medians of 5 runs; the machine is shared with other lanes. Time from
`didOpen`; "first colour" is the earlier of the full and range answers.
| scope | file | cold first colour | warm first colour | mid-session rescan: tokens held |
|---|---|---|---|---|
| workspace | `spi_device_reg_top.sv` (545 KB) | **679 ms** | 400 ms | 650 ms |
| workspace | `aes_cipher_core.sv` (small) | **677 ms** | 365 ms | 646 ms |
| folder (default) | `spi_device_reg_top.sv` | 55 ms | 84 ms | 263 ms |
| folder (default) | `aes_cipher_core.sv` | 24 ms | 50 ms | 245 ms |
**Where the time goes** (verbose trace of a cold workspace run): configuration
round trip 1 ms; `didOpen` 1–16 ms (the buffer's own parse); discovery walk
78 ms; then **every request is HELD** (`head_owed`) until the user's
neighbourhood is indexed at ~650 ms, while the scan runs on to 1.6 s. Building
the tokens themselves costs **0.3 ms** (small file) and **6.5 ms** (545 KB) —
the token build was never the problem; waiting was. The range request was a
whole-file build plus a filter (5.7 ms for 545 KB). The mid-session rescan (a
watched-file *create* for a file the index does not hold, so a whole rescan)
holds `full/delta` and `range` for its whole length.
**Stale forever.** The held `full` was answered off the head prefix and never
refreshed: in folder scope **2 745 tokens** of `spi_device_reg_top.sv`
(26 in workspace scope) stayed different from what the settled index says
until the user edited the file.
**A `didOpen` that widens the scope** (folder scope, `aes_cipher_core.sv`
open, then `hw/top_earlgrey/rtl/autogen/top_earlgrey.sv`): the new file's
`full` waits for the whole widen, **336 ms** — `reindex_widened` drains
nothing.
### What VS Code does — read from source, not memory
From the VS Code 1.145.2 bundle on this machine
(`/Applications/Visual Studio Code.app/.../workbench.desktop.main.js`) and
`[email protected]` (`lib/common/semanticTokens.js`, unpkg):
1. **The range provider is asked only while the document has no complete
tokens.** `ViewportSemanticTokensContribution._tokenizeViewportNow` returns
at once on `model.tokenization.hasCompleteSemanticTokens()`; any answer of
the full provider (data, null, an empty delta) marks the model complete
(`setSemanticTokens(…, true)`); an error does not. So range is only the
*first paint*, until the first full answer lands.
2. **Both are asked at open.** The document feature schedules its first
fetch at `0` ms; the viewport contribution debounces 100–500 ms
(adaptive) and asks for `getVisibleRangesPlusViewportAboveBelow()`. It
re-asks on scroll, content change and on a range provider's `onDidChange`.
3. **Only one full request in flight per model**; edits made while it is
pending are applied to its result when it lands, and then it re-fetches.
The result is therefore assumed to be for the text at *request* time. The
range result is dropped outright if the model's version moved.
4. **Debounce adapts to response time** (300 ms min, 2 s max for the full
provider): a request held for seconds slows every later re-fetch of that
model.
5. **Refresh** (`workspace/semanticTokens/refresh`): the language client
fires the shared `onDidChangeSemanticTokens` emitter of the **document**
provider; the range provider gets no `onDidChange`. VS Code then re-fetches
full/delta for every model attached to an editor (`handleProviderDidChange`
→ `schedule(0)`, or after the in-flight request if one is pending).
6. **Capabilities** `vscode-languageclient` advertises: `requests: { range:
true, full: { delta: true } }`, `multilineTokenSupport: false`,
`overlappingTokenSupport: false`, `serverCancelSupport: true`,
`augmentsSyntaxTokens: true`, and `workspace.semanticTokens.refreshSupport:
true`. It registers both providers whenever the server advertises both. **No
extension configuration is needed** — `editors/vscode/extension.js` is
unchanged.
**What this decides.** VS Code does *not* use range only for "large"
documents — it uses it for every document, but only until the full answer
lands. So answering only `range` early would still leave the first full
answer — the one that makes the model complete and stops all range requests —
held behind the scan, and a held full also raises the adaptive debounce. The
full request has to be answered early too, and the refresh is what reaches the
full provider afterwards (it never reaches the range provider).
## Assumptions
- A buffer's `Document` (text, line index, tokens, tree, `Semantics`, overlay)
is only ever replaced wholesale or refreshed in place between two messages,
never left half-written when control returns to the loop. True today: the
loop is one thread and the scan publishes (`publish_scan`, `finish_scan`)
only between files.
- The index's overlay on a buffer (`ExternalResolutions`) only ever grows more
right during a scan: `publish_scan` absorbs records, it never takes the old
index away mid-rescan (`state/rescan.rs`), so an answer off it is a coherent
guess, never a regression to "nothing resolves".
- `Server::hierarchy_revision` is bumped by every index mutation
(`hierarchy_index_changed` in `reindex`, `reindex_one`, `reindex_widened` and
the startup). The refresh decision keys off it.
- A text-changing notification about a buffer carries that buffer in
`textDocument.uri` (`didOpen`, `didChange`, `didClose`, `didSave`).
- VS Code facts as quoted above; other clients may ask for range and full in
any mix — every answer is valid on its own whatever the mix.
## Design
**One exemption from the order contract, taken where requests are held.**
`process_batch` holds a message when `must_hold` says so (for a request:
`must_wait`); just before that, a semantic-token request is offered to
`answer_from_the_buffer` (`server/viewport.rs`). It is answered there and
then — and so is any colouring request behind a held one in the same burst
(`set_aside`) — when its buffer's text is **current**: the text the server
holds is exactly what the client had sent for that document when it asked,
i.e. no `didOpen`/`didChange`/`didClose` for it is queued unapplied.
**Rebuilt on the loop's own bookkeeping (2026-11-19, on 0.65.8).** Lane 71.7
(`docs/features/scan-ordering/README.md`) made the loop keep exactly the
fact this needs: a message older than the one being handled is either
applied or (a) in `held`, or (b) in the tail of the burst whose message
started the scan now draining, counted by `Server::behind` — the clause
`must_hold` uses so that no notification overtakes an older one. The
exemption reads the same two places, plus the two that are its own:
1. `held` — a notification naming the buffer there means its text is behind;
2. `Server::behind > 0` — an unapplied older notification exists; it is a
count and names no buffer, so it is taken to name this one (conservative:
the request is then held exactly as before);
3. `ahead` — the part of the request's own burst being set aside in front of
it, not yet in `held`;
4. `dirty` — a `didChange` applied to the text but not analyzed.
The first version kept its own stack of "buffers still behind this message"
lists (`Viewport::behind`, `enter`/`leave`, `handle_before`); it overlapped
`behind`/`must_hold` and is deleted. What that costs: a colouring request
inside a scan that a notification started, while that notification's burst
still has *any* unapplied notification, now waits — the old stack let it
through when none of them named its buffer. That shape is a mid-session
rescan with a second notification in the same write; it was not in any
measured scenario.
**Clients without `refreshSupport` get early `range` only** (QA Q3). An early
whole answer is cross-file-blind and only the refresh corrects it; a client
that cannot be refreshed would keep it until its next edit, which is worse
than waiting. So for such a client `full`/`full/delta` wait as they always
did, and early `range` answers (painted over by the first `full`) still go.
**A widen drains** (QA Q2). In folder scope — the default — a `didOpen` after
the settings answer, or any open in a folder not yet indexed, widens the
scope, and `reindex_widened` used to drain nothing: ~650 ms with no colour.
Now:
- `process_batch` hands a `didOpen` to `open_then_widen` with the rest of its
burst. The `didOpen` is applied as always; a widen it asks for is recorded
(`Viewport::defers_widen`) instead of run. Then the colouring requests in
the rest of the burst are answered from their buffers — the just-opened one
is applied, so VS Code's `full` in the same write colours at once — and the
widen runs; the rest of the burst then proceeds exactly as before.
- Between two of the widen's files, `answer_colours_mid_widen` drains the
queue: colouring requests that can be are answered, everything else goes to
`held` in arrival order (and `hold` splices the burst's own tail in front of
it, as for a scan that holds).
- `Viewport::widening` is set for the widen's length, so a range answered
then is owed the refresh, and the widen's revision bump triggers it.
Within 71.7's invariants: the widen is still the effect of the one applied
`didOpen` (only applied messages change scan state); nothing drained during a
widen is applied during it (it is held), so no notification overtakes an
older one; and while the burst's tail holds a notification, `behind > 0`
makes every drained colouring request wait.
**What the exempted handler reads** — the ordinary dispatch arm for the
method, run through `answer_flushed` (the dispatch *without*
`flush_dirty`):
- the one `Document` the request names (text, line index, tokens, tree,
`Semantics`, the `ExternalResolutions` overlay);
- `Workspace::has_large_documents`, `Document::large`,
`ClientAbilities::token_server_cancel` (the large-file decline);
- `Server::tokens`/`token_results` (the remembered answer and its id).
Never the workspace index, never another buffer, never a flush or a publish.
**Why that is valid mid-scan:** a request is only ever answered "during" a
scan by being reached from inside it — the startup's configuration wait
(`await_configuration`/`await_opening_file`), a scan's between-files drain
(`answer_what_is_waiting`), both through `process_batch`, or a widen's
between-files drain (`answer_colours_mid_widen`) — so the scan is between two
files, the buffer's state is whole, and its overlay is the index's answer as
of the last publish.
**A dirty buffer waits.** Answering it would need its analysis, i.e. a parse
of the newest text — and either the index (forbidden) or a cross-file-blind
re-analysis, which would flip every package type, imported enum and
parameter to `variable` on each keystroke during a rescan and back at the end
(right → wrong → right). Holding is the honest choice: VS Code keeps the
colours it has (it shifts them through the edit), only text typed during the
rescan waits for colour, and the rescan hold is now 70–156 ms (below; QA
round 2's figure on the final binary).
**`full`/`full/delta` before the index is ready: answered locally, now** — for a client with `refreshSupport` (see above for one without).
From the VS Code facts: the first full answer is the one that completes the
model and ends range requests, so holding it holds the colours that matter;
answering it early gives the whole file colour (scrolling needs no range
round trips), keeps the adaptive debounce short, and costs one refresh later.
The sequence the user sees is **local → accurate**, once: the overlay only
grows during a scan, and the refresh decision is taken once, at settle — never
at intermediate publishes, so there is no wrong → right → wrong. Once the
index is ready, nothing is exempt (`must_wait` is false) and full/delta are
exactly what they were.
**Delta consistency.** Every full/delta answer, local or accurate, goes
through `remember_tokens`, which stamps a fresh `resultId` and keeps *that*
data as the delta base. A client's `previousResultId` therefore always names
the exact data it holds, whichever kind of answer that was; a mismatched id is
answered with a full set, as before.
**The range answer costs the window** (`tokens::semantic_tokens_in_range`).
The range is snapped to whole lines (`large::line_window`, the uncapped half of
the large-file window's `bounds`), the tokens touching those lines plus one
neighbour each side (for the comments that hang off them, the EOF token's
included) are classified, and the instantiation-override AST walk visits only
items overlapping the window (`instantiation::overrides_within`). The answer is
still exactly the full answer filtered to the range. A buffer over the
large-file threshold keeps its lexer-only window (`large::window`, with its
block-comment back-scan) and its `full` decline, unchanged; the large window
was generalised (`line_window`) rather than duplicated. What "local" uses: the
lexer always (a large buffer's window lexes on demand); the buffer's own
parse/semantics, which every non-large buffer already has for its current
version (`didOpen` parses; the 4 MiB large-file threshold is the measured line
above which nothing parses — `docs/features/large-file-mode`); the overlay as
of the last publish; never the index.
**Refresh** (`refresh_tokens_if_stale`, called by `run` once `held` is empty,
before it blocks for the next message). At most once per index revision: if
`hierarchy_revision` moved since the last decision and nothing must wait, the
open, non-large, non-dirty buffers whose last answer was taken off an
**unsettled** index (a scan running or owed, or a widen running —
`Server::index_unsettled`) are checked: a remembered whole answer
(`Viewport::early`) is compared with a fresh classification, and a buffer last
painted by a range answer (`Viewport::guessed`) counts as stale. Any stale
buffer → one `workspace/semanticTokens/refresh`, gated on
`workspace.semanticTokens.refreshSupport`; both sets are then cleared. An
answer given once the index had settled is not checked again (QA Q6: checking
every open buffer on every index change cost 13 ms per save with 200 open).
**Cost:** one token build per buffer answered while unsettled, once (0.3–7 ms
each on OpenTitan; 12.9 ms for 200 buffers opened at startup); on the client
side, one `full/delta` per editor-attached model, which the prefix/suffix
trim keeps to the tokens that changed. This also fixes the old "stale
forever": a full answered off the head prefix mid-scan is unsettled, and so
compared at settle like any early answer. What it does not do: a later edit
in one file that changes another open file's colours (a package type
renamed) refreshes nothing — exactly as before this lane.
## Results
### Fix round, on 0.65.8 (2026-11-19, QA's harness, medians of 5)
QA's driver (`qa713/drv/meas.py`, copied with its tree to the dev scratch
dir), on a **copy** of OpenTitan `hw/` with every store under the scratch
dir. "before" is master 0.65.8 (`934d472`, built from `git archive` with its
own target dir); "after" is this lane. ms from `didOpen`; *late open* = the
`didOpen` arrives 30 ms after `initialized`, i.e. after the settings answer —
the ordering QA's Q2 is about. Rescan hold = a watcher *create* (whole
rescan) with a `full/delta` and a `range` sent 5 ms after it.
| scope / file | cold first colour | warm | **late open, cold** | rescan hold | refresh lands (cold / warm) |
|---|---|---|---|---|---|
| workspace / aes_cipher_core | 700 → **3.5** | 384 → **3.5** | 631 → **64** | 778 → **120** | 1 614 / 827 |
| workspace / spi_device_reg_top | 680 → **39** | 401 → **39** | 668 → **89** | 758 → **156** | 1 647 / 877 |
| folder / aes_cipher_core | 39 → **3.3** | 66 → **3.3** | 614 → **2.4** | 325 → **70** | 638 / 352 |
| folder / spi_device_reg_top | 71 → **38** | 100 → **38** | 643 → **32** | 341 → **87** | 680 / 352 |
Exactly one refresh in every "after" run (5/5 in every row), none in any
"before" run. **Opening a file in a folder not yet indexed, mid-session**
(folder scope, `aes_cipher_core.sv` settled, then `top_earlgrey.sv`): the new
buffer's `full` **350 → 3 ms** (5 runs each: 357/350/350/351/351 →
2.9/2.7/3.2/3.2/3.1).
**What remains, and why.** The 32–39 ms on `spi_device_reg_top.sv` is that
buffer's own parse at `didOpen` (16 ms) plus the token build (6.5 ms) — the
floor for a 545 KB file. The 64–89 ms of a late open in **workspace** scope is
the startup scan's discovery walk (~80 ms on OpenTitan), which drains nothing
(Handshake request 2, left documented). The rescan hold is the same walk at
the front of the rescan. A second file opened in the same write as a
request that is held during the startup's head phase colours at the head
(~650 ms): the tail of a burst behind a held request is held whole by
`process_batch` (71.7's rule), so its `didOpen` is not applied yet and its
buffer has no text to colour from — the exemption correctly refuses it
(QA's `livelock2.py hover`: `full(B)` at 658 ms, answered "from the buffer"
the moment the `didOpen` is applied).
**Refresh check cost (QA Q6)**, verbose timing line, OpenTitan, buffers
opened at startup and each sent a `full`, then five saves that each change
the index (a module appended): before restricting, every index change
re-tokenized every open buffer — **1.4–2.3 ms with 50 buffers (227 KiB),
12.7–14.2 ms with 200 (2 MiB), per save**. Restricted to buffers whose last
answer was taken off an unsettled index (`Viewport::early`/`guessed`): the
one post-startup check is unchanged (1.4 ms / 12.9 ms — those buffers were
answered mid-scan and are genuinely owed it), every later save **0.00 ms**.
### First round, on 0.65.5 (dev harness; superseded by the table above)
| scope | file | first colour cold: before → after | warm: before → after | rescan hold: before → after | refresh lands (cold / warm) | tokens recoloured by it |
|---|---|---|---|---|---|---|
| workspace | `spi_device_reg_top.sv` | 679 → **111 ms** | 400 → **174 ms** | 650 → **112 ms** | 1 594 / 779 ms | 2 771 |
| workspace | `aes_cipher_core.sv` | 677 → **1.8 ms** | 365 → **1.8 ms** | 646 → **99 ms** | 1 568 / 729 ms | 114 |
| folder | `spi_device_reg_top.sv` | 55 → 54 ms | 84 → 80 ms | 263 → **39 ms** | 648 / 307 ms | 2 745 |
| folder | `aes_cipher_core.sv` | 24 → 26 ms | 50 → **2.0 ms** | 245 → **20 ms** | 611 / 309 ms | 114 |
In every run the refreshed answer was **identical** to a `full` asked after
the scan had settled. (These runs passed a relative store path to a server
whose cwd was the OpenTitan checkout, and so wrote forty stores into it —
QA Q5; the fix round's numbers do not.)
## Correctness on real code
`tokens::viewport_sweep` (ignored; `tools/guard.sh -- cargo test --release -p
lucisv_server viewport_sweep -- --ignored --nocapture`): all 860 corpus files
and every 10th OpenTitan `hw` file (407), six windows each (five 60-line
viewports, one mid-line), **7 602 windows**. The local answer is the buffer
analyzed against an **empty** index (the cold start); the accurate one is the
same text analyzed against its whole tree's index.
- **Valid, every window:** sorted, non-overlapping, non-empty, inside the
range, never past its line's end, never a non-comment token inside a
comment, never a non-string token inside a string — for the analyzed path
and for the large-file lexer window on the same windows.
- **Exact:** the window answer equals the full answer filtered to the range on
every window (the windowing loses nothing).
- **Agreement with the accurate answer:** 559 725 accurate tokens, **541 616
agree (96.77 %)**, **18 109 disagree, and 0 "other"** — every disagreement
is a name the accurate buffer resolves *through the index*: almost all to
another file (package types, imported parameters and enum members,
cross-file modules), but not all. QA's own checker (Q4) found 7 of 1 501
that resolve to the **same** file — inherited class methods
(`core_ibex_test_lib.sv:1101`, `stress_debug()` through `extends`), whose
resolution goes through the index's class hierarchy even though the
declaration is local. My sweep classifies by "the resolution is
`Definition::External`", which those are, so it counted them as
"cross-file"; the accurate word is *index-resolved*. All of them are
exactly the colours the refresh replaces.
Mutation checks: dropping the "one token after the window" neighbour fails the
sweep's exactness assertion; restoring the whole-file build fails
`a_viewport_costs_the_window_not_the_file` (8.6× for 8× the file). Dropping the
"one token before" neighbour is caught by no real file (no trailing multi-line
comment reaches across a viewport edge in the corpus); it is kept because the
trivia model allows the shape, and `window_tests` pin the comment shapes.
## Handshakes
**Consumed:**
- `Server::must_hold`/`must_wait`, `held`, `behind` (lane 71.7's count of
unapplied notifications around a scan's trigger), `dirty`, `scanning`,
`staging` (read-only) and `hierarchy_revision` (read-only, as "the index
moved").
- `reindex_widened` (`server/index.rs`, now this lane's to touch): it defers
itself inside `open_then_widen`, drains colours between files, and sets
`Viewport::widening`.
- `Workspace::document`, `open_documents`; `Document` fields; `large::window`.
- The dispatch arms for the three token methods, via `answer_flushed`
(`answer_request` minus `flush_dirty`, a pure split).
**Promised:**
- `ClientAbilities::semantic_tokens_refresh` (new field, read in `main.rs`).
- `tokens::semantic_tokens_in_range` answers exactly what it did, at window
cost; `large::line_window` is new and public to the crate.
- A request answered ahead of held ones is a response sent out of arrival
order — allowed by the spec, and only ever for the three colouring methods.
**Touched outside the first round's scope:** `server/startup.rs`, one line —
`viewport: Default::default()` in `Server::empty`, because a `Server` field
cannot exist without its initializer; `server/index.rs` (fix round, by the
lead's ruling once the re-index lane had merged) for the widen.
**Requests.**
1. *Colours during a widen* — **done in this lane** (2026-11-19, after the
re-index lane merged and `server/index.rs` became this lane's): the drain
and the before-the-widen answers above. The original request missed the
same-burst `full`; `open_then_widen` is what reaches it.
2. *Drain during discovery* — **left documented.** The startup scan and every
whole rescan begin with a discovery walk (25–80 ms on OpenTitan) that
drains nothing; it is now the largest share of the cold first colour in
workspace scope and of the rescan hold. It is not small: the walk runs in
`state/discover.rs` with the `Workspace` borrowed mutably throughout
(`first_scope` inside `begin_scan`), and answering a request needs the
`Server` and a shared borrow of that same `Workspace`. A drain point means
splitting the walk into resumable steps the way `scan_step` splits the
indexing — a change to the scan's structure whose identical-result proof
is a lane of its own, not a hook.
## Status / TODO
- [x] Step 1: measure cold/warm/rescan/widen on OpenTitan over LSP; VS Code
client facts from source.
- [x] Range answer at window cost, exactly the full answer filtered
(`tokens.rs`, `tokens/instantiation.rs`, `large.rs`).
- [x] Exemption from `must_wait` for the three colouring methods on a
text-current buffer, without `flush_dirty` (`server/viewport.rs`,
`server/mod.rs`, `server/dispatch.rs`).
- [x] `workspace/semanticTokens/refresh`, coalesced per index revision, only
when a token would change, gated on `refreshSupport` (`main.rs`,
`server/viewport.rs`, hook in `run`).
- [x] Tests: `server/viewport/tests.rs` (16 tests, incl. a staged cold
start coloured at once and sharpened by one refresh, the widen's
same-burst and mid-widen answers, and a client without
`refreshSupport`),
`tokens/window_tests.rs`, `tokens/viewport_sweep.rs` (ignored sweep).
- [x] Before/after numbers (this README, `docs/perf/README.md`).
- [x] Widen drain and before-the-widen answers (QA Q2).
- [x] No early whole answers for a client without `refreshSupport` (QA Q3).
- [ ] Discovery drain — Handshake request 2, documented, not done.
- [ ] A dirty buffer during a rescan still waits (deliberate; see Design).
- [ ] Not verifiable here: a running VS Code. What a human should watch: open
a big file (`spi_device_reg_top.sv`) on a cold start with
`lucisv.index.scope: workspace` — module names, parameters, ports and
instance names colour at once; package types / imported names sharpen
once when the indexing bar ends; no flicker back to plain. Type during a
rescan (save a file in another folder): existing colours stay, new text
takes colour when the bar ends.
## Work log
- **2026-11-19 (dev).** Measured first (above). Design decided from the VS
Code source: answer full early as well as range, refresh once at settle.
`semantic_tokens_in_range` re-implemented at window cost (token slice + one
neighbour each side; item-filtered override walk; `large::line_window` split
out of `bounds`). `answer_request` split into flush + `answer_flushed`.
`server/viewport.rs`: the exemption (`answer_from_the_buffer`,
`answered_ahead`, `set_aside`, `handle_before` with the `behind` frames),
and `refresh_tokens_if_stale`. First cut only looked at the request at the
head of a held burst; the server tests showed a colouring request *behind* a
held hover in the same burst was still held — fixed with `set_aside`, which
also needed the `ahead` slice in the currency check. `process_batch` grew
77 → 86 lines (most of the growth is comments; the logic moved into
`viewport.rs` helpers). Production lines: `tokens.rs` 267 → 288,
`tokens/instantiation.rs` 278 → 290, `large.rs` 195 → 199,
`server/viewport.rs` 0 → 169, `server/mod.rs` 186 → 216,
`server/dispatch.rs` 486 → 489, `server/semantic_tokens.rs` 34 → 35,
`server/startup.rs` 171 → 172, `main.rs` 377 → 387.
- **2026-11-19 (dev, fix round on 0.65.8).** Re-applied onto master 0.65.8
(lead). Resolved the two `process_batch` conflict hunks by keeping 71.7's
`must_hold`/`hold` structure and putting the exemption in front of the
hold (`answered_ahead`, then `set_aside` for the rest of the burst, then
`hold`). Deleted as redundant with `Server::behind`/`must_hold`:
`Viewport::behind`, `enter`, `leave`, `owes` and `Server::handle_before`
(master's plain notification/response arms are back); the currency check
now reads `self.behind == 0` instead of its own per-buffer frames (the
trade is in Design). QA Q2: `open_then_widen` (a `didOpen` arm in
`process_batch`, 5 lines; the function is 74 lines) answers the burst's
colouring requests before the widen, `reindex_widened` records a deferred
widen (`Viewport::defers_widen`), drains between files
(`answer_colours_mid_widen`) and sets `Viewport::widening`. QA Q3: early
`full`/`full/delta` only for a client with `refreshSupport`. QA Q4: README
corrected (index-resolved, not "cross-file"; the test count stated as it is).
QA Q5: my harness passed a *relative* store path to a server whose cwd was
the OpenTitan checkout, which is how forty stores landed there; this
round measures on a copy under the scratch dir with absolute store paths.
Handshake 2 (discovery drain) assessed and left documented (reason under
Handshakes). QA Q6: measured 1.4–2.3 ms (50 buffers) and 12.7–14.2 ms
(200) per index-changing save; restricted the check to answers taken off
an unsettled index (`Viewport::early`), after which a later save costs
0.00 ms. To keep `process_batch` under 80 lines (78) the notification arm
calls `apply_in_burst`, which routes a `didOpen` to `open_then_widen`. Q1
re-checked with QA's and 71.7's drivers: the startup scan settles in
1.6–2.6 s with one progress cycle. Production lines (vs 0.65.8):
`tokens.rs` 267 → 288, `tokens/instantiation.rs` 278 → 290, `large.rs`
195 → 199, `server/viewport.rs` 0 → 208, `server/mod.rs` 215 → 224,
`server/dispatch.rs` 491 → 494, `server/semantic_tokens.rs` 34 → 36,
`server/startup.rs` 173 → 174, `server/index.rs` 267 → 276, `main.rs`
378 → 388. Tests: `server/viewport/tests.rs` 16, `tokens/window_tests.rs`
6, `tokens/viewport_sweep.rs` 1 (ignored).
## Changelog paragraph (for the lead)
Semantic highlighting no longer waits for indexing. A colouring request for a
buffer whose text is current is answered from that buffer alone even while a
scan or a widen holds every other request: on OpenTitan the first colours of
a newly opened file arrive in 2–39 ms instead of 600–700 ms (cold start in
either scope, opening a file in a folder not indexed yet), and a mid-session
rescan holds them 70–156 ms instead of 325–778 ms. Names resolved through the
index are coloured as local guesses until it settles; then the server sends
one `workspace/semanticTokens/refresh` and the client's next answer is the
accurate one (this also fixes colours that used to stay stale until the next
edit). A client that cannot be refreshed gets early viewport colours only.
Viewport (`range`) answers now cost the visible lines, not the file.
## QA log
- **2026-11-19 (QA, Opus 5.5).** Verdict **PASS WITH FINDINGS**. No corrupted
or stale-unrecoverable token state, no duplicated response, no invalid
encoding and no read of unsafe state found. The findings are one
pre-existing scan livelock (Q1), a widen gap that leaves the default scope's
common ordering where it was (Q2), and some smaller ones. The harness
(Python LSP driver against the real release binaries, its own delta
reconstruction and validity checker, nothing shared with the dev's sweep)
is in the QA scratchpad (`qa713/drv/`).
**Baseline.** `tools/gates.sh`: all steps pass (fmt, clippy, build, every
suite with lucisv_server at 2014/0, docs, corpus 814/6 as usual, node
37/0). Ignored `viewport_sweep` in release: 1267 files, 7 602 windows, 96.765 %
agree, 18 109 index-resolved, 0 other, which reproduces the dev's numbers. The
`#[test]` count went from 5 433 to 5 452 (+19, the new files only). No
existing test or assertion was removed or edited. None of the off-limits
files differ from `80017a5`. `process_batch` is 86 lines, in the
"investigate" band. It has no reason comment, but it reads top to bottom
and the new logic lives in `viewport.rs` helpers. Acceptable.
**Safety review** (`viewport.rs`, `process_batch`, `answer_flushed`,
`large_file_answer`, the three dispatch arms, `semantic_tokens.rs`,
`tokens.rs` window code). The exempt path reads only these: the named
`Document` (via `workspace.document`), `has_large_documents` and `doc.large`,
`abilities.token_server_cancel`, `self.tokens` and `token_results`, `held`,
`dirty`, `viewport.behind`, `scanning` and `staging`. It writes only
`self.tokens`, `token_results` and `viewport.guessed`. None of that is
half-written between two scan files. Scans start only from notification
and response handlers (every `reindex*` caller is in `notification.rs` or
the settings response), so the `behind` frames cover every outer burst. The
`didChange`/cancel skip is sound. Documents are keyed by exact `Uri`, so a
different spelling is a different document before and after the change;
the exemption adds no new hole. Mid-scan `didClose`+`didOpen` in one
burst answers from the new text. A never-opened document waits and gets
`null` at settle.
**Scenarios on a full OpenTitan `hw/` copy** (workspace scope unless
noted). Every answer was validated: 5-tuples, sorted, non-overlapping,
UTF-16 widths, inside the legend, inside the range. The client array was
rebuilt by applying deltas per spec and compared with a `full` from the
same server and from a fresh server.
| scenario | result |
|---|---|
| cold start; open small, then big, then a third file mid-scan; type plus delta mid-scan | valid; 1 refresh; client equals the same server's full and a fresh server's full for all 3 |
| warm start, same flow | same; 1 refresh |
| folder scope, same flow | same; 0 or 1 refresh depending on ordering (Q2) |
| client without refreshSupport | 0 refreshes ever; client keeps early colours (Q3) |
| after settle: 20 keystrokes each followed by a delta; save after edits; no-op save; unrelated file and a dependency changed on disk | **0 refreshes** each (no storm) |
| watcher *create* (whole rescan); range plus delta at once; hover; `full(B)` then `didClose(B)`; typing during the rescan | range/delta answered at 133 ms, hover held to 772 ms, typed delta held (dirty, by design), closed file's full answered once; 0 extra refreshes; client equals full |
| `didChangeConfiguration` mid-scan | valid; client equals full |
| cancel of a held token request, cancel in the same burst as an exempt request, delta against unknown id `999999`, `didClose`+`didOpen`+`full` in one burst, `full` for a never-opened document | -32800, -32800, full set, data for the new text, `null` at settle: one answer each |
| two documents with interleaved edits and deltas while unsettled | client equals full for both |
| 4.5 MiB generated buffer | full and delta declined -32802, range is the lexer window (640 ints, valid) |
| alternative URI spelling (`%5F`) `didChange` | answers for the real URI unchanged (pre-existing phantom document for the other spelling) |
**Accuracy, own checker** (settings answer withheld so the index is
*empty*; my own comment/string scanner; disagreements classified with a
real `textDocument/definition` after settle). 1 678 windows: 992 corpus
windows over 80 files and 686 OpenTitan windows over 60 files. Edge
windows included: inside a block comment, macro continuation,
`` `ifdef``, `(* *)`, instantiation edge, file start, past EOF, mid-line
columns, empty, reversed, beyond EOF, one line with column 9999.
Results:
- early and settled answers: **0 invalid**;
- settled window equals the full filtered to the range: **1 678/1 678**;
- early vs settled: 43 070 agree, 1 501 disagree;
- 1 494 of the disagreements resolve cross-file;
- **7 resolve to the same file** (Q4).
The checker flagged 10 comment and 428 string hits. All are tokens of a
`` `define``/`` `include``/macro-call directive whose text contains `//`
or a string (for example `kmac_test_vectors_kmac_vseq.sv:31`,
`dma_longer_transfer_vseq.sv:43`). The settled and base answers say the
same, so this is a pre-existing directive classification, not an early-answer
issue.
**Measured** (medians of 5, ms from `didOpen`, machine shared, load
around 20). 80017a5 is built from `git archive` with its own target dir.
"late open" means the `didOpen` arrives 30 ms after `initialized`, i.e.
after the settings answer.
| scope / file | cold first colour before → after | warm before → after | late-open cold before → after | rescan hold before → after | refresh lands cold / warm |
|---|---|---|---|---|---|
| ws / aes_cipher_core | 716 → **2.2** | 384 → **2.2** | 669 → 68 | 769 → **127** | 1 706 / 865 |
| ws / spi_device_reg_top | 736 → **39** | 433 → **36** | 687 → 99 | 781 → **163** | 1 673 / 945 |
| folder / aes_cipher_core | 35 → **2.1** | 62 → **3.3** | 650 → **627** | 327 → **70** | 659 / 310 |
| folder / spi_device_reg_top | 75 → **38** | 101 → **38** | 645 → **650** | 340 → **86** | 683 / 349 |
Exactly one refresh in every run that answered early; none in the
late-open folder runs, which never answered early.
**Findings.**
- **Q1 (HIGH, pre-existing in `80017a5`, `server/index.rs`
`answer_what_is_waiting` — not this lane's file).** A `didOpen` set
aside behind a held request makes `opened` true at every later
interleave. So `head_owed` is set again, the whole held burst is held
again, and each interleave publishes. The startup scan then takes
**287–304 s instead of 1.7 s**, and every held request waits it out.
*Repro:* cold workspace start on OpenTitan, open `aes_cipher_core.sv`
plus `documentSymbol`; at 150 ms, in one write, send `didChange(A)`,
`full/delta(A)`, `didOpen(uart_core.sv)` and `full(uart_core)`.
Result: `documentSymbol` answered at 304 s on base and 287 s on this
branch. This lane makes the trigger *more reachable*, because A now
colours at 2 ms and a user can type and open a second file inside the
head phase. My first VS Code-like replay hit it without being
constructed to.
- **Q2 (MEDIUM, goal gap and README accuracy).** In folder scope, the
default, when the first `didOpen` arrives after the settings answer
(VS Code with `onView:lucisv.hierarchy` activation, or any race), the
startup scans 0 files and the `didOpen` then *widens*.
`reindex_widened` drains nothing, so first colour is still **~630–650 ms**,
unchanged from base. Opening any file in an un-indexed folder later
behaves the same way. The README's results table shows only the
race-won ordering. Handshake request 1 as written does **not** fix this:
as the dev notes, it cannot reach the `full` in the same burst as the
`didOpen`, which is exactly VS Code's case. The request should ask for
the widen to run after the burst's exempt colour requests are answered,
or for the exemption to run before `reindex_widened`.
- **Q3 (LOW/MEDIUM, design trade-off).** A client without
`refreshSupport` keeps the cross-file-blind colours of an early full
until its next edit. `spi_device_reg_top.sv` and `uart_core.sv` stayed
different from the settled full in the norefresh run. Before this
change, workspace scope left ~26 stale tokens; now it can leave
thousands. VS Code is not affected. The lead should decide whether
non-refresh clients get the early `range` only.
- **Q4 (LOW, doc).** "Every disagreement is a name resolved to another
file" is not exact. 7 of 1 501 disagreements are inherited class
methods resolved through the index to the *same* file, for example
`ibex/dv/uvm/core_ibex/tests/core_ibex_test_lib.sv:1101` `stress_debug()`
in `core_ibex_directed_test extends core_ibex_debug_intr_basic_test`.
The refresh fixes them all the same. Also, Status says "13 claims on the
wire", but `server/viewport/tests.rs` has 12 tests.
- **Q5 (LOW, process).** Forty `st-before-*`/`st-after-*` index-store
directories (1.3 GB) were written into the off-limits
`~/.cache/lucisv-opentitan-full/` at 07:13–07:28. Their names match this
lane's measurement harness. QA did not remove them; that is for the lead.
- **Q6 (INFO).** `refresh_tokens_if_stale` re-tokenizes every open
non-large buffer once per index revision, and every save is a revision.
That is 0.3–7 ms per buffer on the `run` thread. It is not measured with
many open buffers.
VS Code facts 1, 2, 3 (range dropped on version change) and 5 (refresh
calls `schedule(0)` or waits for the in-flight request) check out against
the 1.145.2 bundle (`_tokenizeViewportNow`, `_requestRange`,
`handleProviderDidChange`). The `vscode-languageclient@9.0.1` claims
(fact 6) are unverified: no local copy, not fetched. A real VS Code was
not observed. Nothing fixed by QA.
- **2026-11-19 (QA round 2, Opus 5.5; worktree 71.3b on `934d472`).**
Verdict **PASS WITH FINDINGS** (minor findings only). Base `934d472` was
built from `git archive` with its own target dir. Every store and tree
lived under the QA scratch dir (`qa713b/`).
`git -C ~/.cache/lucisv-opentitan-full status --short` is empty, the forty
`st-*` stores are gone, and nothing in `~/.cache/lucisv-corpus` is newer
than this round.
**Baseline.**
- `tools/gates.sh`: every step passes, including `cross`. lucisv_server is
2052/0 and corpus 814/6.
- Ignored release runs, with the corpus and OpenTitan paths pointed at
scratch copies, all pass:
- `viewport_sweep`: 7 602 windows, 0 other;
- `ordering_random` long run;
- both `localized_reindex` sweeps.
- `#[test]` count went from 5 491 to 5 514. Nothing was removed or edited.
No file under `server/tests/`, `tests/`, `state/` or `vlog_semantic`
differs from `934d472`, so 71.7's scan_ordering, caret_boundary and
ordering_random tests and the re-index differential tests are untouched
and pass.
- `process_batch` is 79 lines and `open_then_widen` is 22.
**Safety on the new loop** (`process_batch`/`must_hold`/`hold`,
`answered_ahead`, `set_aside`, `apply_in_burst`, `open_then_widen`,
`answer_colours_mid_widen`, `reindex_widened`). Every place an unapplied
older message can sit is covered by `text_is_current`:
- this burst's older messages are applied, otherwise `process_batch` has
already returned holding them;
- `held` (a notification naming the buffer);
- `behind`, set to `outer` at the head and to `around` while the widen
runs, so the burst's unapplied tail makes every mid-widen colour request
wait;
- `ahead` (the set-aside part of its own burst);
- `dirty`.
The four 71.7 invariants hold:
- (i) No notification overtakes another. Messages drained mid-widen go to
`held` unapplied, and `hold` splices the burst tail in front of them.
- (ii) Scan state changes only through applied messages. The recorded
widen is the applied `didOpen`'s, and between recording it and running
it only colouring requests are answered; notifications are kept.
- (iii) Held messages are handed back a bounded number of times. Q1 does
not come back: on `livelock2.py` delta and hover the held requests are
answered at 741 and 665 ms, against 667 ms on base. On `c717.py`, seeds
1 and 2, the startup scan ends at 3.33 and 3.60 s, against 4.19 and
3.70 s on base (machine loaded).
- (iv) Exactly once: no request was lost or duplicated in any run.
One semantic note: a held settings notification does not stop an early
colour answer, because it names no buffer. The answer can therefore use the
previous settings' analysis. Colours only, and the early-answer refresh
corrects it at settle.
**Attack campaigns** (exact text oracle: the generated documents' tokens
are computed from the client's own text; deltas rebuilt as the LSP spec
says; every answer has to match a state the client had sent at or after
the request):
| campaign | runs | token answers checked | result |
|---|---|---|---|
| 71.7's `ord3.py` with range/full/delta mixed in, plus didOpen+full, didOpen+change+range/full, didOpen+didClose, change+delta (`ord3t.py`) | corpus 6 workspace + 4 folder, OT 2+2, corpus 2 without refresh: 16 runs, 26 refreshes | 6 918 (range 4 562, full 863, delta 1 493, 1 050 of them as edits) | **0 fails**; fresh-server oracle equal in every run; 0 stale at settle; 153 early answers |
| `wid.py`: folder scope on a full OT copy, 24 docs in 12 disjoint scope folders, 12 widens per run, 1–3 widening didOpens per burst each with its `full`, settings change between the recorded widen and its run, didOpen+didClose before the widen, watcher creates (rescans) mixed in | 8 seeds × (new, base) + 3 shutdown+exit mid-widen + 2 without refresh | 3 047 on new | **0 fails** |
In `wid.py`:
- **non-colouring requests in a widening burst were answered only after
the widen ended (63/63);**
- **all 978 non-colouring answers are identical to base, answer for
answer**;
- shutdown+exit mid-widen: the server exited in 0.1–0.9 s with `full` and
`shutdown` both answered.
Other comparisons with base:
- `f6.py` tail, held and control all report "server holds v3", the same
as base.
- `harm2.py` matches base. Base's first run gave one different
`definition`, which did not reproduce in two reruns of either binary, so
it is a pre-existing timing race.
**Re-index oracle** (qa711 `small.py`, `outside.py`):
- `small.py` and `outside.py` (push and pull): only the negative controls
diverge, as in 71.1.
- `rand_run2.py`, two seeds per tree × 300 steps (`QA_FRESH_SAVE=1` as
before): corpus 71/72 and otsample 73/74 all end with 0 divergent checks.
**Accuracy** (own checker, index empty): 726 windows (498 corpus, 228 OT).
- 0 invalid answers;
- windowed answer equals the full answer filtered to the range in 726/726;
- all 437 disagreements resolve through the index (go-to-definition lands
in another file);
- the directive and attribute string/comment hits are pre-existing, as in
round 1.
**Q3.** A client without refreshSupport gets `full` at 655 ms (held, as on
base at 672 ms), `range` early at 107 ms, and no refresh. With
refreshSupport: `full` at 2 ms and one refresh.
**Q6.**
- Trade-off (`q6.py trade`): an edit plus save in package A that changes
how open B colours sends no refresh, on base and on new, so "same as
before" holds.
- Check cost: with 50 or 200 buffers answered during the startup scan,
the one settle check takes 5.2 and 32 ms (machine loaded; the dev
measured 1.4/12.9 ms). Later saves run no check.
**Measured on the final binary** (medians of 5, ms from didOpen, OT copy;
before = 934d472):
| scope / file | cold | warm | late open, cold | rescan hold | refresh lands cold / warm |
|---|---|---|---|---|---|
| ws / aes_cipher_core | 660 → **3.5** | 374 → **3.5** | 626 → **62** | 756 → **141** | 1 616 / 839 |
| ws / spi_device_reg_top | 685 → **39** | 400 → **37** | 674 → **86** | 791 → **159** | 1 635 / 868 |
| folder / aes_cipher_core | 38 → **3.2** | 66 → **3.2** | 611 → **2.3** | 325 → **70** | 636 / 348 |
| folder / spi_device_reg_top | 74 → **32** | 98 → **31** | 641 → **32** | 344 → **70** | 699 / 372 |
Opening `top_earlgrey.sv` mid-session in folder scope: its `full` takes
**375 → 5.6 ms**. Refresh counts per run, 5/5 runs each:
- cold and late open: 1;
- warm with the rescan, and mid-session open: 2, i.e. one more at the
rescan's or widen's settle;
- base: 0.
No storm, and no early answer that was left without a refresh when
stale. The dev's table reproduces within noise.
**Findings.**
- **R2-1 (LOW/INFO, `server/viewport.rs` `answer_from_the_buffer`
`guessed.insert`).** A `range` answered during a rescan is always
counted stale, so it buys one refresh at settle even when nothing
changed. On `flick.py`, a `full` asked during the same rescan was
identical to the settled answer and drew 0 refreshes. With the measured
`range`, every warm run got a second refresh. VS Code asks for `range`
only until the first `full`, so this rarely fires there.
- **R2-2 (LOW, docs).**
- Design ("A dirty buffer waits") still says "rescan hold is now
20–112 ms"; it is 70–156 ms.
- The work log says `open_then_widen` "is 74 lines"; it is 22.
- The changelog says first colours arrive in "2–39 ms … cold start in
either scope". Late open in workspace scope is still 62–86 ms
(discovery walk), and the paragraph should say so.
- Handshake 2 (discovery drain) is still open and correctly described.
Unverified: a real VS Code, and the vscode-languageclient facts. Nothing
fixed by QA.
## Review
**Lead, 2026-11-19.** Accepted for 0.65.10, after two QA rounds and a re-application onto a changed loop.
- The owner asked for a viewport-only highlight. The dev's Step 1 found that
VS Code asks for the viewport only until its first whole-file answer, so
answering `range` early would not have been enough; `full` is answered
early too and corrected by a refresh. Reading the client before designing
is what made this work.
- Round 1 passed QA but left the default scope's common ordering untouched
(a file opened after settings arrive still waited ~630 ms) and I did not
ship it. It also could not be finished then: the fix sits in
`server/index.rs`, which the re-index lane held.
- Lanes 71.1 and 71.7 then changed the loop underneath it. I re-applied the
lane onto 0.65.8 by hand and had the dev rebuild the exemption on 71.7's
`must_hold`/`behind` instead of beside it; its own per-buffer lists were
deleted. One mechanism for "is anything for this buffer still queued",
at the price of one narrow shape where a colour request now waits.
- QA round 2 re-measured the whole table on the final binary (the dev had
measured before its last refactor), rebuilt client token state from deltas
for ~10 000 answers with no failure, and compared 978 non-colour answers
with base, identical. That, and 71.7's invariants holding under `wid.py`,
is what I accept this on.
- QA's two README corrections: I fixed the rescan-hold figure in Design; the
work log's "74 lines" is history and stays. The release notes state the
workspace-scope late-open figure the dev's paragraph left out.
- Not verified: a running VS Code; the `vscode-languageclient` facts (read
from a fetched copy, not the pinned one).
<!-- Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com -->