Files
lucioandClaude Fable 5 00c03eccf9 LSP §9b: semantic tokens range + full/delta
tokens.rs is now one tokenizer behind three pure steps — absolute()
classifies and splits, within() filters by overlap, encode() delta-
encodes — so textDocument/semanticTokens/range and /full share one
implementation and cannot drift; QA proved the refactor byte-identical
to the old encoder over a 41k-token corpus file against the pre-change
binary. Range answers are self-contained (overlapping tokens kept
whole, re-encoded from the document start) and carry no resultId — a
delta never diffs against a partial view.

/full/delta remembers each open buffer's last answer under a per-answer
id (dropped on didClose; stale or foreign ids answer full) and diffs by
common-prefix/suffix trim to a single edit, the suffix counted over
what the prefix left — the classic overlap trap, deliberately broken by
dev and QA separately and caught by the suite both times. Edit indices
are wire-array u32 positions (5 per token), pinned. No token request
touches the pull-diagnostics generation.

38 tests added (dev 29 + QA 9), including two independently written
edit appliers cross-checked over 200 random pairs and two differently
seeded randomized sweeps through the real tokenizer.

docs/features/semantic-tokens-delta/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-26 13:03:56 -07:00
..

semantic-tokens-delta

Goal

Serve the two semantic-token requests this server advertised nothing for: textDocument/semanticTokens/range, so the first paint of a large file costs the visible lines rather than the whole file, and textDocument/semanticTokens/full/delta, so a client that already holds an answer is told what changed instead of being handed the file's whole token set on every keystroke (TODO.md §9b). Both are the same tokenizer that already served full: the classification pass now produces an intermediate absolute form — line, column, length, type, modifiers — a range answer filters that form and the one encoder delta-encodes whatever is left, so the three requests cannot disagree about what a token is. The delta itself is the standard prefix/suffix trim rust-analyzer uses, with the one invariant that matters tested as a property: applying the returned edits to the old data reproduces the new data exactly.

Assumptions

  • A range answer is a self-contained SemanticTokens, not a slice of the full one. The relative encoding restarts from the start of the document exactly as a full answer's does; only the tokens outside the range are missing. So the first kept token's deltaLine/deltaStart are absolute, which is why the encoder had to be split out of the classifier rather than the range answer being a sub-slice of the full one. (A client that pasted a slice out of a full answer would draw line 40's tokens on line 0 — pinned by a_range_answer_re_encodes_from_the_start_of_the_document.)
  • A token that only overlaps the range is kept whole. The client asked which tokens to draw, not where to cut them, and a length trimmed to the range would be a lie about the source. Tokens are single-line by construction (every span is split at \n before encoding — the rule no_token_ever_spans_a_line_break has pinned since the first round), so "overlap" never has to reason across lines.
  • An empty range answers nothing. A zero-width range covers no characters, so nothing intersects it. Without the explicit guard the overlap test degenerates into containment and a collapsed cursor position would answer with the token it sits inside — tokens the client has no room to draw. No editor is known to send one; it is guarded because the arithmetic invites it.
  • resultIds are minted per answer, from one counter, and are not the diagnostics generation. A previousResultId must name the exact data the client holds, which the pull-diagnostics generation cannot do: that one is bumped by a buffer change and by an index rebuild, and it is shared by every open buffer. This counter counts answers — one per full and per delta, whatever the buffer — so an id is unambiguous and never reused. Answering the same unchanged buffer twice mints two ids and one empty edit list; that is a string per answer, not a recomputation.
  • A range answer is deliberately not remembered and carries no resultId. It is a partial view; a later delta computed against it would be a diff against something the client never held whole. Only full and full/delta write the remembered answer.
  • One answer per buffer is remembered, and it dies with the buffer. A client that asks again has moved on from the previous answer, so there is no history to keep. didClose drops the entry, so the map is bounded by the number of open buffers, not by the number of files ever opened. A delta naming an id from before a close is answered in full.
  • Mismatched, absent or stale previousResultId → a full answer. SemanticTokensFullDeltaResult allows either, and a delta against data we cannot see would be a guess. That is also what makes a server restart, a client restart and a didClose/didOpen cycle all self-healing.
  • Minimality beyond the prefix/suffix trim is not attempted. One SemanticTokensEdit replaces everything between the common prefix and the common suffix. A real diff would describe an insertion in the middle of a file as two small edits, but the encoding is relative: the first token after an inserted line carries a changed deltaLine, so a "middle" insertion already invalidates only that one token plus the ones that moved, and everything below it re-matches as suffix. rust-analyzer answers the same way. The payload is what the client re-parses, not what it re-renders.
  • The buffer that does not lex still round-trips. It has no tokens at all (the lexer is all-or-nothing), so a delta out of it deletes everything and a delta back into it inserts everything. Mid-keystroke this is the common case, and it is tested in both directions.
  • workspace/semanticTokens/refresh is out of scope and not sent. That request exists for the case where the server decides the client's tokens went stale without the client having edited anything — an index rebuild changing how a name resolves, say. The case that matters (the user typing) makes the client re-pull on its own. Recorded as backlog below, not built.

The delta algorithm, and the bug it is easy to write

prefix  = how many leading tokens are equal
old_rest, new_rest = both lists past the prefix
suffix  = how many trailing tokens of old_rest and new_rest are equal
edit    = replace old_rest[..old_rest.len() - suffix]
          with     new_rest[..new_rest.len() - suffix]

The suffix is counted over what the prefix left, never over the whole lists. That is the cap, and skipping it is the classic bug in this algorithm: when the two token lists repeat themselves, a suffix counted over the whole lists claims tokens the prefix has already claimed, and new_rest[..new_rest.len() - suffix] then runs backwards — a panic in debug, an edit that deletes a region it also re-inserts in the general case.

This is not hypothetical for Verilog. The encoding is relative, so identical lines encode to identical tokens: line 2 and line 3 of

module m;
  wire a;
  wire a;
  wire a;
endmodule

are byte-for-byte the same five numbers. Deleting one of those lines is exactly the old = [A, B, A], new = [A] shape. Both the hand-built shape and the real-Verilog one are tested (the_suffix_is_capped_so_it_cannot_overlap_the_prefix, repeated_lines_of_verilog_are_the_same_trap_on_real_tokens), and both were confirmed to fail — by panic — against a deliberately uncapped implementation before being committed to.

start and deleteCount count numbers, not tokens. The wire carries a flat u32 array of five numbers per token, and an edit indexes that. Both are five times a token index (FIELDS), pinned by an_edits_indices_count_numbers_and_not_tokens — the off-by-five here does not fail loudly, it silently corrupts a client's cache.

Handshakes

Consumed from lsp-types (0.97, no new dependency): SemanticTokensRangeParams, SemanticTokensRangeResult, SemanticTokensDeltaParams, SemanticTokensFullDeltaResult, SemanticTokensDelta, SemanticTokensEdit, and — for the capability — SemanticTokensOptions { range: Option<bool>, full: Option<SemanticTokensFullOptions> } with SemanticTokensFullOptions::Delta { delta: Some(true) }. The Delta variant is the full capability plus deltas, not a replacement: semanticTokens/full is still served and still answered.

Consumed from other crates: nothing new. vlog_parser, vlog_semantic, vlog_formatter, vlog_refactor, lucisv_core are untouched, as is every file outside crates/lucisv_server. This feature is protocol arithmetic over a classification that already existed.

Changed inside this crate, for whoever reads tokens.rs next:

  • tokens::semantic_tokens(doc) now returns Vec<SemanticToken> (the data) rather than a whole SemanticTokens. The resultId is the server's to stamp, because only the server knows what it remembered — the module owns no state.
  • New: tokens::semantic_tokens_in_range(doc, range) -> Vec<SemanticToken> and tokens::delta(old, new) -> Vec<SemanticTokensEdit>.
  • Private and new: Absolute (line, start, length, type, modifiers), absolute(doc), flatten(pieces, doc), within(tokens, range), encode(&[Absolute]). encode is pure — the same tokens always encode the same way, whether they are the whole file's or the handful a range kept — which is what lets full and range share it.
  • Server gains tokens: HashMap<Uri, TokenAnswer> and token_results: u64, written only by remember_tokens and cleared only by didClose. Neither touches generation: every token request is read-only, and bumping the diagnostics generation on a viewport repaint would throw away a pulling client's whole diagnostic cache several times a second (no_token_request_bumps_the_diagnostics_generation).

Requested of other modules: nothing.

Status / TODO

  • tokens.rs split into classification → Absolute → filter → encode, with full and range sharing all four steps.
  • textDocument/semanticTokens/range, advertised as range: Some(true), re-encoded from the document start, overlap kept whole, empty range empty.
  • textDocument/semanticTokens/full/delta, advertised as full: Delta { delta: Some(true) }, single-edit prefix/suffix diff with the suffix capped.
  • Per-buffer resultId bookkeeping: minted per answer, stored by both full and full/delta, dropped on didClose.
  • semanticTokens/full returns a resultId now (it did not before), so a client may mix the two requests.
  • Round-trip property tests: append, delete, middle change, identical, complete replacement, unlexable buffer both ways, empty buffer both ways, the prefix/suffix-overlap shapes, and a 300-iteration fixed-seed randomized sweep over real Verilog buffers.
  • Range/full agreement as a property over two corpus files, in 40-line windows (the size of an editor viewport request), stated line-wise so it is independent of the handler's own overlap test.
  • Server-level tests through the Session harness, and one e2e round trip through the real binary.
  • TODO.md §9b box, this README, and the lucisv-server capability table.
  • Not done, deliberately: workspace/semanticTokens/refresh. Nothing the server learns on its own (an index rebuild changing how a name resolves) currently invalidates a client's token cache; when something does, this is the request to send.
  • Not done: partial results / workDoneProgress on any of the three requests. The whole-file answer is sub-millisecond at Verilog file sizes; streaming it in chunks would be complexity for nobody.
  • Not measured: whether the delta payload is actually smaller than the full one for a typical edit. It must be by construction for an edit near either end of a file, and it is at worst the full set plus one edit header for an edit near the middle. No benchmark was written.

Work log

2026-08-26 — dev agent

  • Read first: CLAUDE.md, docs/features/lucisv-server/README.md (the capability table and the semanticTokens mapping section), docs/features/pull-diagnostics/README.md for the house style on result ids, tokens.rs in full, and lsp-types 0.97's semantic_tokens.rs for the exact shapes (range is a plain Option<bool> there, not an options struct; SemanticTokensFullDeltaResult has three variants and we use two).
  • The refactor came before either handler. semantic_tokens was one function doing classification, line splitting, sorting and delta encoding, and the range answer needs to cut in between the third and the fourth. It is now absolute(doc) (classify + split + sort, producing Absolute), within(tokens, range) (the filter) and encode(&[Absolute]) (pure delta encoding). The eleven pre-existing token tests were left with their assertions untouched — only the test helpers moved, because semantic_tokens now hands back the data rather than a SemanticTokens — which is the evidence that the factoring changed no behavior.
  • The overlap cap was verified by breaking it, not by reasoning. After writing the capped delta, the suffix computation was temporarily changed to count over the whole lists and the suite re-run: three tests failed with a subtraction-overflow panic (the_suffix_is_capped_so_it_cannot_overlap_the_prefix, repeated_lines_of_verilog_are_the_same_trap_on_real_tokens via the shared round-trip helper, and every_pair_of_real_buffers_round_trips_through_its_delta — the randomized sweep found it on its own, which is why the BODY line pool deliberately repeats " wire a;"). The implementation was then restored. CLAUDE.md's invariant #4 is about verify.rs, but its spirit — a normalization ships with the attack that would forgive a corruption — is what this check is.
  • The one design decision that is not the obvious one: a range answer carries no resultId and is not remembered. It would have been one line to remember it, and it would have silently made the next delta a diff against a partial view. Written down in Assumptions and pinned by a_range_request_is_not_the_answer_a_later_delta_is_computed_against.
  • The empty-range guard was written for the arithmetic, not for a client. from < range.end && range.start < to is the interval-overlap test only when the range is non-empty; for a collapsed range it is containment. One early return, one test, one sentence in Assumptions.
  • generation was deliberately not touched, and the test for it says so twice: directly on the field, and observably through a pull that is still unchanged after a token request. Pull diagnostics' README asks every new feature to audit whether it bumps the generation; the audit's answer here is no, and this is where it is recorded.
  • Nothing outside this crate moved. No new dependency, no version bump, no engine change, no editors/ change (smoke.js's capability list already contains semanticTokensProvider, and it passes against the built binary).
  • Results. cargo test --workspace: 1793 passed, 0 failed (1764 before — +29: 18 unit tests in tokens.rs, 9 in server.rs, 1 in main.rs, 1 e2e). cargo clippy --all-targets: silent. cargo fmt --all -- --check: clean. cargo build && node editors/vscode/smoke.js target/debug/lucisv-server: OK. No commits.

QA log

2026-08-26 — QA agent

Gates re-run, from a clean rebuild (touched the three changed source files first so clippy could not reuse a stale cached pass): cargo fmt --all -- --check: clean. cargo clippy --all-targets --workspace -- -D warnings: silent. cargo test --workspace: 1793 passed, 0 failed before QA's own additions, 1802 passed, 0 failed after (9 QA tests added, see below). cargo build && node editors/vscode/smoke.js target/debug/lucisv-server: OK. All match the dev's claims.

1. The delta invariant, independently — verified clean, tests added. Wrote a second applier, independent_apply (tokens.rs, in mod tests), that shares no code with the dev's apply_edits: it walks SemanticTokens rather than the flat u32 array, slices by hand (extend_from_slice) rather than calling Vec::splice, and separately asserts edit.start / edit.delete_count divide evenly by FIELDS — a second, independent check of the ×5 claim. Cross-checked the two appliers directly against each other over 200 random pairs (qa_the_two_independently_written_appliers_never_disagree) — they never disagreed. Ran QA's applier over: both ends changing at once, middle-only, identical, complete replacement, old empty, new empty, and a single-token file, both directions (qa_independent_reconstruction_covers_both_ends_middle_and_the_degenerate_shapes). Ran a second randomized sweep, different generator (xorshift64, not the dev's LCG), different seed (0xDEAD_BEEF_1234_5678 vs 0x5eed), and a different line pool that adds a block comment spanning lines, a continued `define, and a generate/endgenerate block — pieces whose token count is not simply one-line-in-N-tokens-out (qa_a_second_randomized_sweep_with_a_different_seed_generator_and_pool_round_trips). All green. Verdict: verified clean.

2. The overlap cap, re-verified — reproduced, with one correction to the work log's specifics. Reproduced the dev's breakage myself: changed the suffix computation in delta (tokens.rs:304-305 at the time) from counting over old_rest/new_rest to counting over the whole old/new, re-ran cargo test -p lucisv_server, and restored it — the file is back to its pre-experiment text (diffed against git to confirm no leftover debug code). Result: 10 tests failed by attempt to subtract with overflow panic, including the_suffix_is_capped_so_it_cannot_overlap_the_prefix, the dev's own sweep every_pair_of_real_buffers_round_trips_through_its_delta, and — usefully — all of QA's own new round-trip tests from surface 1 above, which is exactly the cross-check CLAUDE.md invariant #4 asks for (an independently-written attack finding the same class of bug). One correction: the work log names repeated_lines_of_verilog_are_the_same_trap_on_real_tokens as one of the three tests that failed in the dev's own experiment. Re-running the same breakage, this specific test passes — traced with a temporary debug print (old.len()=9 new.len()=5 prefix=4 suffix=1 and the mirror), the type/declaration-modifier mismatch a few tokens in breaks the naive whole-list suffix match before it ever grows past old_rest's length, so no overflow occurs for this particular buffer pair under this literal interpretation of "count over the whole lists." This is a documentation accuracy nit, not a safety finding — the class of bug is still real and still demonstrated by the other two named tests plus QA's own — but the dev should either soften the claim (the failure was seen at the time, with whatever the code looked like then, or via a different breakage) or drop that one test's name from the sentence. Then tried to construct a shape that defeats the capped implementation and produces wrong data instead of a panic: with the cap in place, suffix = old_rest.iter().rev().zip(new_rest.iter().rev())… is inherently bounded by min(old_rest.len(), new_rest.len()) because Iterator::zip itself stops at the shorter side — so deleted = old_rest.len() - suffix can never underflow, and the algebra (`old[:prefix]

  • inserted + old_rest[deleted..]reduces to exactlynew) holds unconditionally, not just on the tested shapes. Tried anyway: long shared prefix and long shared suffix overlapping in the middle over periodic data (the [A,A,A,A,A]→[A,A,A]` shape, and variants with the periodic run at different positions) — all round-trip correctly, consistent with the argument above. Verdict: verified clean; the cap is load-bearing (10 failures without it) and, with it, the round-trip property holds by construction, not merely on the cases anyone thought to test.

3. u32 semantics — verified clean. an_edits_indices_count_numbers_and_not_tokens (dev's) and QA's own independent_apply (which asserts % FIELDS == 0 before dividing, on every edit, in every test above, including the 500 combined sweep iterations) agree the ×5 conversion is exact and consistently applied. Wire shape: an unchanged buffer answers edits: [] (present, empty — a_delta_over_an_unchanged_buffer_is_an_empty_edit_list, server.rs:2508) and a stale/unknown/absent-state id answers the Tokens variant with no edits key at all (a_delta_naming_an_id_we_do_not_hold_is_answered_in_full) — both legal per SemanticTokensFullDeltaResult's untagged enum, and both are pinned by existing tests, not left to accident.

4. Range self-containment — verified clean, gaps closed with new tests. The dev covered: full-document range, absolute first-token deltas, overlap kept whole at the start boundary, empty range, whitespace-only lines, range never leaking outside tokens, and a 40-line-window corpus sweep (which QA re-ran directly against the checked-out corpus/ — genuinely exercised, not skipped: windows_checked well over 20). QA added the three shapes the list asked for that were not yet pinned: (a) overlap kept whole at the end boundary, mirroring the dev's start-boundary test (qa_a_range_ending_mid_token_keeps_that_token_whole); (b) a range on a line with tokens, covering only the whitespace (plus an unemitted =) between two of them — not an empty line (qa_a_range_covering_only_mid_line_whitespace_between_two_tokens_is_empty); (c) a reversed range (start > end) — within's guard (range.start >= range.end) is symmetric to this by construction since Position derives Ord over (line, character) lexicographically, so this was already total and already answered empty, but nothing pinned it before now (qa_a_reversed_range_is_total_and_answers_nothing). All pass. Verdict: verified clean.

5. State lifecycle — verified clean, two gaps closed with new tests. The dev covered: didClose+reopen with the old id → full, memory dropped on close (server.rs:784, self.tokens.remove(&uri), confirmed keyed by Uri and removed, not just marked stale), and the unopened-buffer → null convention for all three request kinds (every_token_request_for_a_buffer_that_is_not_open_answers_null, which also asserts the map stays empty). QA added: (a) two buffers open at once, buffer A's id presented to buffer B — answered in full, not edits computed against A's data, and closing A leaves B's own remembered state untouched (qa_two_open_buffers_ids_do_not_cross_contaminate); worth noting as a observation rather than a bug: presenting a foreign id to B does mint a fresh id for B and overwrite B's own remembered answer (every answer does, by design — "Answering the same unchanged buffer twice mints two ids"), so the first version of this test asserted something the design doesn't promise (that id_b keeps working) — fixed once understood, noted here so the next reader doesn't trip on the same assumption. (b) full → delta → full → delta → full stays consistent across three edits (qa_full_delta_full_delta_stays_consistent_across_edits), and separately, a full/delta answer's own resultId chains directly into the next delta without ever going back through full (qa_a_deltas_own_id_chains_directly_into_the_next_delta_without_a_full_in_between) — checked against ground_truth, a helper that reads the document straight through tokens::semantic_tokens and bypasses the request dispatch (and thus the very tokens/token_results bookkeeping under test) entirely, so the check does not depend on the server's own memory being right. All pass. Verdict: verified clean.

6. No behavior change for existing clients — verified clean, two ways. (a) Direct code comparison: classify, modifiers, identifier_type, symbol_type, collect_trivia, split_lines, token_types and token_modifiers are byte-for-byte identical between git show 80b9afd:crates/lucisv_server/src/tokens.rs and the new file; the new flatten+encode pair is the old single encode function split at exactly the line-splitting/sorting boundary, with no logic added or removed. (b) Empirical, at the binary level: built the pre-refactor commit in a separate worktree (git worktree add, removed after), drove both the old and the new lucisv-server binaries over stdio with the same textDocument/semanticTokens/full request against a real corpus file (corpus/picorv32/picorv32.v, 41,325 tokens), and diffed the data arrays: byte-for-byte identical; the only difference in the response is the new resultId field, which the old binary did not send at all. The legend (token_types/token_modifiers) is likewise unchanged (confirmed both by the code diff and by the_semantic_token_capability_asks_for_ranges_and_for_deltas asserting length 14). Verdict: verified clean — this is about as strong as evidence gets for "the refactor changed no behavior."

7. CLAUDE.md compliance — verified clean. grep-checked all non-test code in tokens.rs, server.rs, main.rs for .unwrap(), .expect(, panic!: none. No #[allow] added anywhere in the diff. No unsafe anywhere in the diff. The two new public functions (semantic_tokens_in_range, delta) both carry doc comments explaining what/why. The feature README has each of the six required sections exactly once (plus one extra, non-required "The delta algorithm…" section, which is additive and not a substitute for any required one). TODO.md's item text is unchanged save the checkbox and an appended → summary — the original sentence is intact verbatim.

Fixes made directly (small, per the QA remit): none needed in the dev's own code — every finding above was either "verified clean" or a documentation-accuracy nit (item 2) recorded rather than edited, since CLAUDE.md reserves the Work log for the dev agent's own account of what it did and why, and the specific breakage the dev saw is not reproducible after the fact to know which description would be truer. QA did fix one bug in QA's own first draft of qa_two_open_buffers_ids_do_not_cross_contaminate (a wrong assumption about id_b surviving a cross-request, see item 5) before it ever reached this log.

Tests added this round: 9, all passing, workspace total 1793 → 1802. tokens.rs: qa_the_two_independently_written_appliers_never_disagree, qa_independent_reconstruction_covers_both_ends_middle_and_the_degenerate_shapes, qa_a_second_randomized_sweep_with_a_different_seed_generator_and_pool_round_trips, qa_a_range_ending_mid_token_keeps_that_token_whole, qa_a_range_covering_only_mid_line_whitespace_between_two_tokens_is_empty, qa_a_reversed_range_is_total_and_answers_nothing. server.rs: qa_two_open_buffers_ids_do_not_cross_contaminate, qa_full_delta_full_delta_stays_consistent_across_edits, qa_a_deltas_own_id_chains_directly_into_the_next_delta_without_a_full_in_between.

Overall verdict: committable as-is. No corruption, non-idempotency, dropped-comment, or safety-net-widening risk found — this feature does not touch verify.rs, the formatter, or anything outside crates/lucisv_server, and every claim in the dev's work log checked out except the one test name in item 2, which is cosmetic. All gates green, all new and old tests green, one empirical binary-level spot check green.

Review

2026-08-26 — lead

Reviewed the diff, the work log and the QA log; re-ran all gates myself (1802 workspace tests, 0 failed), clean. The refactor is the right seam: one tokenizer, one pure encoder, and range/full provably cannot drift — QA's byte-for-byte comparison of a 41k-token corpus file against the pre-refactor binary is the strongest possible form of "the factoring changed nothing". The delta design's judgment calls are all correct: range answers carrying no resultId (a delta must never diff against a partial view), a per-answer counter separate from the shared diagnostics generation, and prefix/suffix-with-cap over anything cleverer — with the round-trip property, not minimality, as the contract.

Two QA results deserve the record: the two independently written edit appliers never disagreed across 200 random pairs, and the overlap cap was broken on purpose twice (dev and QA separately) with the suite catching it both times. One cosmetic correction accepted from the QA log: the work log names repeated_lines_of_verilog_are_the_same_trap_on_real_tokens among the tests that fail with the cap reverted; QA's re-run shows that particular pair breaks the match earlier and that test passes — the trap is real but is caught by the other ten failures. The work log stands as the dev's account, with the QA log as the precise version. Accepted as shipped.