Files
lucisv/docs/features/incremental-sync/README.md
T
lucioandClaude Fable 5 c2ea1a11f6 LSP §9b: incremental text sync
textDocument/didChange now applies ranged content changes instead of
requiring the whole buffer per keystroke. New pure sync::apply_changes
applies each change against the document as the previous ones left it
(fresh line table per change), clamping inherited from convert.rs and a
backwards range read as a pure insertion — the one rule that cannot lose
text. One notification stays one reparse / one generation bump / one
publish. Full-sync clients (rangeless changes) keep byte-identical
behavior; save advertises includeText: false and didSave still honours
text when sent.

35 tests added (28 unit incl. a 400-sequence randomized cross-check
against an independent reference model and QA's surrogate/CRLF/final-
newline attacks, 6 server-level, 1 e2e pinning the wire capability
shape). QA's one finding — CRLF split across two same-position inserts
in one batch lands \n\r — is pre-existing convert.rs behavior, pinned
by test, unreachable by real clients; see the feature README.

docs/features/incremental-sync/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-26 11:49:58 -07:00

416 lines
26 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.
# incremental-sync
## Goal
Move the server from `TextDocumentSyncKind::FULL` to
`TextDocumentSyncKind::INCREMENTAL`: a `didChange` now carries the ranges the
user touched rather than the whole buffer, and the server applies them to the
text it already holds. Full-buffer sync re-serializes, re-transfers and
re-allocates the entire file on every keystroke, which is the wrong cost curve
for a server that wants to answer per-keystroke (completion, signature help,
inlay hints) — and for the editor side of a large `.sv` it is the one place
lucisv was measurably ruder than ruff. The price of the move is that the server
becomes the *only* holder of the buffer's text: a wrong offset here silently
rewrites what the user is looking at, with no full-text resend to correct it.
That is why the whole edit application is one pure function
(`sync::apply_changes`), unit-tested against a second implementation, with no
slice that can panic.
## Assumptions
- **Positions are UTF-16, as `capabilities()` says.** Every conversion goes
through `convert::Positions::offset`, the same function every other request
handler uses. There is no second offset arithmetic in this feature — that is
the point.
- **Clamping, exactly.** A client desync (or an editor rounding a position) must
never panic and never corrupt. The rules, all of them inherited from
`Positions::offset` and pinned by tests in `sync.rs`:
- a **line past the end** of the document clamps to the end of the document;
- a **character past the end of a line's content** clamps to that content's
end — before the line's `\n`, and before one `\r` preceding it, so an edit
positioned past the visible end of a CRLF line cannot land between the
`\r` and the `\n`;
- a **character landing inside a surrogate pair** (the low half of an astral
character such as `🎉`) **rounds forward** past the whole character. So a
range boundary can never split a `char`, the output is always valid UTF-8,
and an emoji is either wholly inside the replaced range or wholly outside
it;
- **`start > end` after conversion** clamps `end` up to `start`, which turns
the change into a pure insertion at `start`. There is no resync mechanism
in LSP short of the client closing and reopening the buffer, so the safe
direction is the one that deletes nothing: a user can undo an unexpected
insertion, but cannot recover text the server threw away.
- **Each change is positioned against the document the previous changes in the
same notification left.** This is what the protocol says, and it is why the
line table is rebuilt per change rather than once per notification.
- **A change with no `range` replaces the whole document**, mid-batch included,
and resets the state the ranges after it are positioned against. A batch of
rangeless changes therefore still ends at the last one — the pre-existing
full-sync behavior, kept for a client that ignores the new capability.
- **An empty `contentChanges` array is not a change**: nothing is reparsed and
the generation counter does not move, exactly as before (the old handler's
`next_back()` on an empty list did nothing).
- **A `didChange` for a buffer that was never opened** is out of protocol, but
is still taken rather than dropped: the base text is `""`, so a full-text
change lands exactly as it did before this feature, and a ranged change
clamps to an insertion at the start. No special case, no error path.
- **`O(changes × file)` per notification, honestly.** Every ranged change
builds a fresh `LineIndex` over the current text and allocates a new `String`.
For the batch sizes editors actually send (1–5 ranges) over Verilog files
this is microseconds, and it buys a function with no incremental state that
can fall out of step with the text. A rope or an incrementally-patched line
table is the optimization to reach for if a profile ever asks; TODO.md §6
already defers that whole class of work.
## Handshakes
- **Consumes `convert::Positions::offset`** (`crates/lucisv_server/src/convert.rs`)
for every position→byte conversion, and `vlog_parser::LineIndex` to build it.
Nothing was changed in either — the clamping this feature depends on is the
clamping those already documented and tested.
- **Promises `Server::set_document` is still called exactly once per
`didChange` notification.** `set_document` bumps `self.generation`, which is
the whole `resultId` of `docs/features/pull-diagnostics/README.md`; a bump
per *range* would make one keystroke look like several to a pulling client,
and no bump would let a changed buffer answer "unchanged". One notification =
one reparse = one stamp = one `publish`. Pinned by
`one_notification_is_one_generation_bump_however_many_ranges`.
- **Changes what the client is told at `initialize`.**
`text_document_sync` moves from `Kind(FULL)` to `Options { open_close: true,
change: INCREMENTAL, save: { include_text: false } }`. The `open_close` and
`save` values are not new behavior: they are what a bare `Kind` already
resolved to client-side (`vscode-languageclient` expands a numeric
`textDocumentSync` to exactly `{ openClose: true, change: <kind>, save: {
includeText: false } }`), written out because the options form has no
"unspecified" that means the same thing. `didSave` therefore carries no text,
which is what it carried before — and the `DidSaveTextDocument` handler still
adopts `params.text` if some client sends it anyway, so nothing regresses for
a client that behaves differently.
- **No other crate is touched.** No new dependency; the randomized test's
generator is a five-line LCG rather than `rand`.
## Status / TODO
- [x] Advertise `TextDocumentSyncOptions` with `change: INCREMENTAL`,
preserving the open/close and save semantics a bare `Kind` implied.
- [x] `sync::apply_changes(text, changes) -> String` — pure, total, no
panicking slice.
- [x] All changes applied in order, each against the previous one's result.
- [x] Rangeless change = whole-document replace, mid-batch included.
- [x] Clamping rules (line past EOF, character past line end, surrogate half,
`start > end`) defined above and tested.
- [x] One `set_document` — one reparse, one generation bump, one publish — per
notification.
- [x] Unit tests: insert/delete/replace, dependent batches, multi-byte and
astral characters, CRLF, (0,0), EOF, no trailing newline, rangeless
mixed into a batch, every clamping rule.
- [x] Randomized cross-check against a second implementation built on
`char`s and lines, fixed seed, 400 cases.
- [x] Server-level tests: incremental batch == one full change, generation
bumps once, full-sync batch still ends at the last change, publishes
reflect the composed text.
- [x] e2e test driving the real binary with four ranges over two
notifications.
- [x] `docs/features/lucisv-server/README.md` sync/staleness text updated.
- [x] TODO.md §9b item checked off.
## Work log
**2026-08-26 — dev.** Implemented the whole feature in one round.
- New module `crates/lucisv_server/src/sync.rs` (declared in `main.rs`), one
public function `apply_changes(&str, &[TextDocumentContentChangeEvent]) ->
String`. Chosen over putting it in `convert.rs`: `convert.rs` is the
byte↔position primitive every handler shares, and this is a protocol-level
policy (ordering, rangeless resets, desync clamping) built *on* it. Keeping
them apart means the safety-critical policy has its own test module and its
own reference implementation to be checked against.
- The function is deliberately dumb: `String` in, `String` out, a fresh
`LineIndex` per ranged change. No incremental line table, no rope, no
reusable "document buffer" abstraction for a second user that does not
exist. The cost is written down under Assumptions rather than optimized away.
- **No panicking slice.** `start`/`end` come from `Positions::offset`, which
only ever returns character boundaries, so `text[..start]` would be provably
safe — but "provably" leans on another module's invariant, and the failure
mode is a panic that takes the user's buffer with it. The splice uses
`text.get(..start)` / `text.get(end..)` and skips the change if either is
`None` (unreachable), so the function is total by construction.
- **Clamping decisions.** Line/character clamping is inherited from
`Positions::offset` rather than re-decided here — a second clamping rule
would be a second set of off-by-ones. The one genuinely new decision is
`start > end`: `end` clamps *up* to `start`, making the change an insertion.
Rejected alternatives: dropping the change (leaves the server's text and the
client's silently different, with no way back), and swapping the two (invents
a deletion the client never asked for). Insertion is the only reading that
cannot lose text.
- **Capability.** Moved to the options form. Establishing what a bare `Kind`
meant for save was the fiddly part: the spec leaves it to the client, and
`vscode-languageclient` fills in `{ openClose: true, change, save: {
includeText: false } }`. Writing those two out keeps every client on the
behavior it had, and `includeText: false` is also the right answer on its own
terms now — the server tracks the buffer edit by edit, so a save re-sending
the file would be pure waste. The `didSave` handler was left alone: it still
adopts `params.text` when present, so a client that sends text anyway is
handled exactly as before.
- **Handler.** `DidChangeTextDocument` reads the base text out of the workspace
(`""` if the buffer is unknown), calls `apply_changes` once, and goes through
the existing `set_document` + `publish` path unchanged — so the
pull-diagnostics generation model, the `lucisv.toml` warning re-arm, and the
push/pull gate all behave as they did.
- **Tests: 23 unit (`sync.rs`) + 6 server-level (`server.rs`) + 1 e2e.** The
randomized cross-check (`random_edit_sequences_agree_with_the_reference_model`)
runs 400 sequences of 1–5 changes over random texts drawn from
`{a, b, space, ;, \n, \r\n, é, 🎉}` — every character width, both line
endings, and bare `\r`s — with positions deliberately allowed out of range so
the clamping rules are exercised too. It compares against `reference_apply`,
a flat `Vec<char>` implementation that scans its own line starts and shares
no code with `apply_changes`, and additionally asserts that applying the
batch in one call equals applying the changes one at a time. Seed is fixed
(`0x5EED_1CE5`), no dependency added.
- Deviations from the plan: none. Nothing outside `lucisv_server` was touched
in code. Two documentation files outside this feature were annotated rather
than rewritten, because both stated something this round made false:
`docs/features/lucisv-server/README.md` (the "full-text sync only"
assumption, the recompute table, and one sentence of an old QA log that read
`textDocumentSync: 1` off the capabilities JSON) and one parenthetical in
`docs/features/pull-diagnostics/README.md` that justified the single
generation counter by "full-text sync ignores versions" — the conclusion
still holds, the reason needed rewording. No QA log or Review section was
otherwise touched.
## QA log
**2026-08-26 — QA.** Re-ran every gate, then attacked the six surfaces the
lead flagged plus a few of my own. Verdict: **committable as-is**. No
corruption, no panic, no divergence from a well-behaved client found; one
pre-existing (not introduced by this feature) latent edge case documented
and pinned rather than fixed, since fixing it means changing a shared
primitive (`convert.rs`) outside this feature's scope.
**Gates re-run, all clean:**
- `cargo fmt --all -- --check` — clean.
- `cargo clippy --all-targets` — clean (touched the three changed files and
re-ran to defeat the cache; still clean).
- `cargo test --workspace` — every crate green, 0 failed. `lucisv_server`'s
own run: 628 lib tests (23 in `sync.rs` as claimed, plus 5 I added), 33
e2e, 3 grammar. `cargo test -p vlog_formatter` also re-run per CLAUDE.md's
formatter-change rule (this isn't a formatter change, but confirmed green
anyway): 114 passed.
- `cargo build && node editors/vscode/smoke.js target/debug/lucisv-server` —
`smoke: OK`.
**1. Surrogate rounding — verified clean, direction confirmed by reading
`convert.rs`.** `Positions::offset` (`crates/lucisv_server/src/convert.rs:39`)
walks the line's `char`s accumulating UTF-16 units and only ever returns an
offset it has actually reached by consuming whole `char`s (`offset += ch.
len_utf8()` happens only together with `units += ch.len_utf16()`), so the
returned byte offset is always the smallest character boundary whose
cumulative UTF-16 unit count is `>= pos.character` — i.e. it always rounds
up/forward, unconditionally, for every position (start or end). What
"forward" *means* differs by role: for a start boundary it means the
character is excluded (the insertion/deletion point moves past it, so the
character survives); for an end boundary it means the character is included
(the deletion widens to swallow it). Both are the same mechanical rule.
Added two direct tests pinning the exact resulting string, as asked:
`crates/lucisv_server/src/sync.rs`
`a_deletion_starting_at_the_low_surrogate_index_preserves_the_character`
(`edit((0,4),(0,6),"")` on `"// 🎉 ok\n"` → `"// 🎉ok\n"`, emoji survives) and
`a_deletion_ending_at_the_low_surrogate_index_consumes_the_whole_character`
(`edit((0,3),(0,4),"")` on the same text → `"// ok\n"`, emoji consumed).
Both pass. The dev's own two existing tests in
`an_astral_character_takes_two_units_and_is_never_split` already hit this
exact case (`edit((0,4),(0,6),"X")` and `edit((0,3),(0,4),"X")`) but as
replacements, not pure deletions — the two I added close that gap with an
empty `text`. Cross-checked against the LSP spec: positions are UTF-16
code-unit offsets and a spec-compliant client never legitimately sends a
mid-pair boundary, so any total, non-panicking rule is acceptable — the
README's description ("rounds forward past the whole character") is
accurate to the actual code, not just to the reference model.
**2. Divergence-from-editor risk — one real (low-severity, pre-existing)
finding, everything else clean.**
- **Fresh-`LineIndex`-per-change is not hoisted.** `crates/lucisv_server/src/
sync.rs:35`, `let index = LineIndex::new(&text);`, is inside the `for
change in changes` loop, rebuilt from the current `text` every iteration —
confirmed by reading the code (not just trusting the comment), and then by
actually breaking it: I temporarily hoisted the `LineIndex::new` call above
the loop (reusing one stale index for every change) and reran `cargo test
--bin lucisv-server sync::tests::`. Three tests failed against the stale
index: `a_later_range_positioned_against_the_original_text_would_be_wrong`
(panics — its own doc comment names exactly this regression),
`a_rangeless_change_resets_what_the_next_range_is_against`, and
`random_edit_sequences_agree_with_the_reference_model` (400/400 cases
depend on this). `later_changes_see_what_the_earlier_ones_did` did *not*
fail under hoisting — its three edits happen to stay valid against the
stale index anyway, so it does not by itself pin this — but the three that
did fail are sufficient. Reverted the hoist immediately after (confirmed
back to 28/28 passing); no new test needed, the existing ones already pin
this correctly.
- **A change whose range covers the final newline** — clean. Added
`a_change_covering_the_final_newline_removes_exactly_it`:
`edit((1,1),(2,0),"")` on `"a\nb\n"` → `"a\nb"`. Removes exactly the
trailing `\n`, nothing else.
- **Adjacent zero-width ranges at the same position in one batch** — not a
bug, and pinned as such. Added
`zero_width_inserts_at_the_same_position_compose_in_batch_order`: two
inserts both naming `(0,0)` on `"x"` with texts `"1"` then `"2"` produce
`"21x"`, because each change's position is (correctly, per protocol)
resolved against the text the previous change left — the second insert's
literal position `0` is now *before* the first insert's text. A client
that wants `"12"` must advance the second position past the first's
length, same as it would for a non-zero-width range. This matches "each
change is positioned against the document the previous changes in the
same notification left" exactly.
- **`\r\n` split across two changes in one batch — finding.**
`crlf_split_across_two_changes_in_one_batch_reorders_the_bytes`
(`crates/lucisv_server/src/sync.rs`): `apply_changes("ab", &[edit((0,2),
(0,2), "\r"), edit((0,2),(0,2), "\n")])` produces `"ab\n\r"`, not
`"ab\r\n"`. Root cause: `convert.rs::line_content_end`
(`crates/lucisv_server/src/convert.rs:96`) treats a trailing bare `\r` as
"not content" unconditionally — whether or not a `\n` will ever follow it
— so once change 1 leaves the buffer ending in a lone `\r`, "end of line"
for change 2 clamps to *before* that `\r`, and the `\n` lands ahead of it
instead of after. This is **not introduced by this feature**: the rule
lives in `convert.rs`, which predates incremental sync and is shared by
every position-converting handler. What incremental sync newly does is
give this quirk a path to actually rewrite the *persisted buffer* rather
than just a hover/diagnostic range — before this feature, the server never
computed byte offsets to build a document to save, it just accepted the
client's already-composed text verbatim. In practice this needs a client
to split one `\r\n` insertion into two separate ranged edits inside a
single `didChange` batch, positioned at the exact same coordinates for
both; no known editor's diff algorithm does this (VS Code/Neovim send
`\r\n` as one atomic edit). No panic, no data loss (both bytes survive,
just reordered), so it does not violate the "never corrupt" invariant in
the "produces wrong output" sense used elsewhere in this repo (no crash,
no truncation) but it is a genuine silent-divergence risk if a
pathological client ever does this. Recorded and pinned rather than fixed:
fixing it means deciding whether `line_content_end` should special-case "a
bare trailing `\r` with nothing after it, at the very end of the buffer or
the very end of a change-in-progress" — a `convert.rs` decision that
affects every handler, out of this feature's stated scope
(`sync.rs`/`main.rs`/`server.rs` only). Filed as a follow-up rather than
redesigned here.
- Multi-byte/astral columns (`a_ranged_change_over_multi_byte_text_edits_the_
right_columns`, server.rs) and CRLF-on-one-line edits (`crlf_line_ends_
survive_an_edit_on_the_line`, sync.rs) — re-verified by hand-tracing
`Positions::offset`, both clean, no off-by-one.
**3. Full-sync regression — verified clean.** Diffed the old handler
(`git show aa303ce:crates/lucisv_server/src/server.rs`, the `next_back()`
form) against the new path:
- *Multiple rangeless changes*: old took only the literal last element via
`next_back()` (O(1), never touched the earlier ones); new applies all of
them via `apply_changes`, but each rangeless change fully replaces `text`
and continues, so the net result is identical — last one wins either way.
Confirmed by the dev's `the_last_of_several_rangeless_changes_wins`
(sync.rs) and `a_full_sync_clients_batch_still_lets_the_last_change_win`
(server.rs). The new path is `O(changes)` string clones instead of `O(1)`
for this specific case — a real but tiny and already-documented cost, not
a correctness regression.
- *Empty `contentChanges`*: old — `next_back()` on empty returns `None`, no
`set_document`/no `publish`. New — explicit `if p.content_changes.
is_empty() { return; }` before touching anything. Identical observable
behavior; confirmed by `one_notification_is_one_generation_bump_however_
many_ranges`'s second half (server.rs) which checks the generation counter
does not move.
- *Unknown/never-opened uri*: old — `set_document(uri, change.text)`
unconditionally, no existence check. New — `self.workspace.document(&uri).
map_or("", ...)` then `apply_changes`; for a rangeless change this reduces
to the same `set_document(uri, change.text)`. Confirmed by `a_change_
naming_a_buffer_that_was_never_opened_is_taken_as_written` (server.rs,
rangeless case). I did not find a server-level test of a *ranged* change
against a never-opened buffer, but it is exercised at the unit level
(`an_edit_into_an_empty_document` in sync.rs, since `apply_changes` is
handed `""` either way) and the handler code between the two cases is the
same three lines — low-severity gap, noting rather than adding a
redundant test.
**4. Capability shape — verified clean, confirmed on the actual wire, not
just by reading the struct.** Ran the built binary directly through a
minimal `initialize` and inspected the raw JSON response (not just the
e2e/smoke assertions): `textDocumentSync` serialized as exactly
`{"change":2,"openClose":true,"save":{"includeText":false}}` — no
`willSave`/`willSaveWaitUntil` keys at all (`lsp_types::
TextDocumentSyncOptions` marks both `#[serde(skip_serializing_if = "Option::
is_none")]`, so `None` means genuinely absent from the wire, not `null`).
This is exactly what `vscode-languageclient` and Neovim's builtin client
parse as `{openClose: true, change: Incremental, save: {includeText:
false}}`, with the will-save fields correctly unadvertised for a future
round. `incremental_changes_are_advertised_and_applied_over_the_wire`
(e2e.rs) asserts `sync["change"] == 2`, `sync["openClose"] == true`,
`sync["save"]["includeText"] == false` — confirmed this really does pin the
shape, it isn't a no-op assertion.
**5. Performance honesty — verified clean.** `Server::set_document`
(`crates/lucisv_server/src/state.rs:175`, called from the `DidChangeTextDocument`
arm exactly once per notification per the diff at `server.rs`) is the only
place a `Document::new` (full reparse/tokens/`Semantics`) happens. Inside
`sync::apply_changes`, only a `LineIndex::new` (a single linear scan for
`\n` bytes, not a parse) and a `String` allocation happen per *ranged*
change — that's the honest `O(changes × file)`, not `O(changes × file²)`
and not a hidden per-change reparse. Confirmed by reading `state.rs:175-179`
and by the fact that `self.generation` (bumped only inside `set_document`)
moves exactly once per notification regardless of range count, per
`one_notification_is_one_generation_bump_however_many_ranges`.
**6. CLAUDE.md compliance — clean.** No `unwrap`/`expect`/`panic!` in
library code paths in `sync.rs` or the `server.rs` handler diff (`grep`
confirms the only `expect()`s introduced are inside `#[cfg(test)]` code in
`server.rs`, which CLAUDE.md permits). No new `#[allow]`. `sync.rs` has a
module doc comment and `apply_changes` has a doc comment. Feature README has
all six required sections. `TODO.md`'s §9b item text is unchanged aside from
the checkbox and an appended implementation-summary paragraph (allowed — the
rule is "leave the item text intact", not "add nothing"). The two annotation
edits to `docs/features/lucisv-server/README.md` and `docs/features/
pull-diagnostics/README.md` are both dated 2026-08-26, self-identifying
("*(That last sentence records the state at the time of this QA pass
only...)*", "*(Still true after incremental sync, 2026-08-26: ...)*"), and
factual against the diff — neither rewrites the original text, both append.
One minor nit: the original (pre-existing) `TODO.md` §9b bullet's plan text
says "with a full-text fallback on any malformed change", but the shipped
implementation uses clamping instead of a full-text fallback for a malformed
change — a better and thoroughly-justified design choice (see the README's
Assumptions and Work log), but the Work log's "Deviations from the plan:
none" doesn't call out that the *originally-planned* mechanism changed
between the TODO's wording and the implementation. Cosmetic — the actual
behavior is fully and correctly documented elsewhere in the same README —
not asking for a fix, just noting it for the record.
**Tests added this round** (all in `crates/lucisv_server/src/sync.rs`,
all passing): `a_deletion_starting_at_the_low_surrogate_index_preserves_
the_character`, `a_deletion_ending_at_the_low_surrogate_index_consumes_
the_whole_character`, `crlf_split_across_two_changes_in_one_batch_
reorders_the_bytes`, `a_change_covering_the_final_newline_removes_exactly_
it`, `zero_width_inserts_at_the_same_position_compose_in_batch_order`.
**Verdict: committable as-is.** No dev follow-up required to ship; the
`\r\n`-split-across-changes behavior is worth a future look if `convert.rs`
is ever revisited, but it is pre-existing, unreachable by any known real
client, and now pinned by a test rather than silently latent.
## Review
### 2026-08-26 — lead
Reviewed the diff, the work log and the QA log; re-ran fmt/clippy/the full
workspace suite/smoke.js myself, all clean. `apply_changes` is the right
shape: pure, total, no panicking slice, and the fresh-line-table-per-change
decision buys correctness with microseconds — the honest O(changes × file)
note is exactly how this repo trades. Inheriting the clamping rules from
`Positions::offset` instead of inventing a second set was the correct call,
and the `start > end` → pure-insertion rule is the only reading that cannot
lose the user's text.
On QA's finding (a `\r` + `\n` split across two same-position inserts in
one batch lands as `\n\r`): accepted as pinned, not fixed. The root cause
is `convert.rs`'s pre-existing treatment of a trailing bare `\r`, which is
shared by every handler and out of this feature's scope; no real client
splits a CRLF across two changes of one batch, and the behavior is now
documented by a test rather than latent. If a cross-file `convert.rs`
round ever opens, this goes with it. The randomized cross-check (400
sequences against an independent model), the deliberate-breakage check
that the line table really is rebuilt per change, and the wire-level
capability assertion give this the confidence a sync rewrite needs.
Accepted as shipped.