# Server Ordering, Versioned Edits, and Startup Race Fixes (Round 1) ## Goal Close four ordering and protocol-soundness bugs identified in `docs/topo.md` (`#53`, `#52`, `#61`, `#62`): 1. **Topo #53 (Startup scan race for workspace-wide mutating requests)**: Hold `textDocument/rename`, `codeAction/resolve`, `workspace/executeCommand`, and `workspace/willRenameFiles` until an active background scan (`self.scanning == true`) finishes completely rather than letting them run mid-scan once `head_owed` clears, while preserving read-only `same_file` fast-action early answers and avoiding O(N) re-drain spinning across scan publishes. 2. **Topo #52 (Versioned `DocumentChanges` edits)**: Track client-announced `i32` buffer versions across `didOpen`, `didChange`, dirty flushes, `didSave`, `didClose`, and large-file reclassification; detect `workspace.workspaceEdit.documentChanges` in `ClientAbilities`; and emit deterministic, sorted `DocumentChanges::Edits` (`OptionalVersionedTextDocumentIdentifier { uri, version }`) in `rename.rs` and `ports.rs`, falling back to `WorkspaceEdit { changes: Some(...), .. }` when unsupported or when no edited buffer carries a version. 3. **Topo #61 (Stale `didChangeConfiguration` replay during staging)**: When `take_the_answer_out_of_held` plucks a pulled `Pending::Configuration` response during startup staging, drop any older `workspace/didChangeConfiguration` notifications sitting earlier in `self.held` so they cannot replay after staging ends and overwrite newer pulled settings, while retaining any pushes that arrived after the pull response. 4. **Topo #62 (Exact state-index oracle in `fast_actions_bursts`)**: Record the server's exact `applied_changes` counter whenever `answered_ahead` emits an early response and assert in `fast_actions_bursts.rs` both `applied >= required` (no skipped affecting state change) and `e == reference_at[applied]` against the single-message reference stream. ## Assumptions - Read-only requests exempted via `same_file` / `viewport` (`answer_from_the_buffer`) remain eligible mid-scan whenever their own preconditions hold; only whole-workspace mutating requests (`textDocument/rename`, `codeAction/resolve`, `workspace/executeCommand`, `workspace/willRenameFiles`) must wait for `self.scanning == false`. - Unopened on-disk files touched alongside an open versioned buffer in `DocumentChanges::Edits` carry `OptionalVersionedTextDocumentIdentifier { uri, version: None }`, matching LSP 3.16+ semantics (and existing `extract.rs` conventions). When no edited file has an attached version (for instance, direct workspace unit tests or closed-file commands) or when `document_changes` capability is false, `WorkspaceEdit::new(changes)` is used. ## Handshakes - **`crates/lucisv_server/src/server/index.rs` (`waiting_for_this_scan`)**: Untouched per lane file ownership. Whole-scan mutators arriving during `self.scanning == true` are staged into `Server::after_scan` in `server/mod.rs` (checked alongside `held` in `must_wait`, `must_hold`, `ahead.rs::nothing_unapplied_for`, `ahead.rs::answer_ahead_mid_widen`, `Server::run`, and `server/tests/scan_ordering.rs::settle`) so `waiting_for_this_scan` does not re-drain and re-hold them on each intermediate scan file. A follow-up lane can fold `after_scan` into `index.rs` if desired. - **`crates/lucisv_server/src/server/probe.rs` (`went_ahead`)**: Untouched per lane file ownership. Exact `applied_changes` recording at `answered_ahead` lives in `#[cfg(test)]` `server/ahead.rs::AHEAD_APPLIED` (`take_ahead_applied()`) paired with `#[cfg(test)] Server::applied_changes` incremented in `server/mod.rs`, `server/startup.rs`, and `server/notification.rs`. A follow-up lane can fold `AHEAD_APPLIED` into `probe::Probe`. - **`crates/lucisv_server/src/state/buffers.rs` / `server/diagnostics.rs` / `server/large_file.rs`**: Untouched per lane file ownership. Because `Workspace::set_document` rebuilds `Document` without a version parameter, `Server::versions: HashMap` and `Server::sync_document_versions()` re-attach versions after dirty flushes, `didSave(text)`, `apply_settings`, and `take_the_answer_out_of_held`. - **Remaining `WorkspaceEdit` producers (`imports.rs`, `instantiate.rs`, `extract.rs`, `inline_module.rs`, `code_action.rs`, `file_ops.rs`)**: Untouched beyond lane ownership. `rename.rs` and `ports.rs` now share `ports::encode_edit` and honor `ClientAbilities::document_changes`; follow-up lanes can pass `self.abilities.document_changes` and document versions to `imports`, `instantiate`, `extract`, `inline_module`, `code_action`, and `file_ops::will_rename`. - **Cross-lane handshake F2b (`crates/lucisv_server/src/same_file.rs` + `server/tests/fast_actions_differential.rs`)**: Lane 1A fixed `#53` in `vlog_refactor::prepare_rename_here` to check `index.units(enclosing_unit)` for symbols inside a file-scope unit (`Module`/`Interface`/`Package`/`Typedef`/`Class`), not only `scope == file_scope`. Updated `same_file::renamed_here` to walk `Semantics` parent scopes up to `file_scope` and defer (`false`) whenever the symbol sits inside a file-scope unit, updated `same_file/tests.rs`, and added `"dup_b.sv"` to `fast_actions_differential::early_answers_equal_settled_over_the_locality_shapes` (passes both before and after Lane 1A merges). ## Status / TODO - [x] Topo #53: Hold workspace-wide mutating requests across `self.scanning` via `after_scan` + `waits_for_whole_scan`. - [x] Topo #52: Track `Document::version` atomically, parse `workspace.workspaceEdit.documentChanges`, and emit `DocumentChanges::Edits` in `rename.rs` and `ports.rs` via shared `ports::encode_edit` (including non-canonical client URIs and immediate version sync after `flush_dirty` / `flush_buffer`). - [x] Topo #61: Drain superseded `workspace/didChangeConfiguration` notifications preceding plucked `Pending::Configuration` answers in `take_the_answer_out_of_held`. - [x] Topo #62: Record exact `applied_changes` on early answers and tighten `fast_actions_bursts.rs` oracle to exact state equality (`e == reference_at[applied]` and `applied >= required`). - [x] Cross-lane F2b: Align `same_file::renamed_here` with `vlog_refactor::prepare_rename_here` for symbols enclosed by file-scope units and cover `"dup_b.sv"` in `fast_actions_differential.rs`. - [x] Add regression suite `crates/lucisv_server/src/server/tests/ordering_r1.rs` plus unit tests in `main.rs`, `rename.rs`, and `ports.rs`. ## Work log - Added `AtomicI64` buffer `version` storage (`version()`, `set_version()`) on `Document` in `crates/lucisv_server/src/state/document.rs` without changing `Document: Sync` or existing constructors. - Added `document_changes_support` in `crates/lucisv_server/src/main.rs` and `ClientAbilities::document_changes` in `crates/lucisv_server/src/server/mod.rs`. - Added `Server::after_scan`, `Server::versions`, `must_wait_for`, `waits_for_whole_scan`, and `sync_document_versions` in `crates/lucisv_server/src/server/mod.rs`, updating `Server::run`, `process_batch`, `hold`, and `must_hold`. - Updated `crates/lucisv_server/src/server/startup.rs` (`take_the_answer_out_of_held`) to drain older `DidChangeConfiguration` notifications prior to the last plucked `Pending::Configuration` response while keeping newer pushes intact; updated `crates/lucisv_server/src/server/tests/fast_actions_precondition.rs::what_staging_held_behind_a_push_is_not_released_ahead_of_it` so its test `push(1000)` arrives after `settings_answer(0)` rather than relying on the pre-#61 stale-replay bug. - Updated `crates/lucisv_server/src/server/notification.rs` and `crates/lucisv_server/src/server/dispatch.rs` to record/sync document versions and dispatch `document_changes` capability to `rename::rename_traced_for` and `ports::{code_actions_for, resolve_for, execute_for}`. - Extracted shared `ports::encode_edit` helper used by both `ports.rs` and `rename.rs`. - Tightened `crates/lucisv_server/src/server/tests/fast_actions_bursts.rs` with `ahead::take_ahead_applied()` and `applied >= required` + exact state equality, and added regression tests in `crates/lucisv_server/src/server/tests/ordering_r1.rs`, `rename.rs`, `ports.rs`, and `main.rs`. ### 2026-11-26 — QA fix pass + F2b handshake - **QA F1 (`crates/lucisv_server/src/ports.rs::encode_edit`)**: Matched open documents via `ws.open_documents()` (`doc.path.as_deref() == Some(path)`) instead of canonical `path_to_uri(path)` + `ws.document(&target)`, preserving the client's open URI (`file://localhost/...`, lowercase percent-encoding, etc.) and `doc.version()` across both `DocumentChanges::Edits` and unversioned `changes` maps. Added unit and integration tests in `ports.rs` and `ordering_r1.rs`. - **QA F2 (`crates/lucisv_server/src/server/{notification,ahead}.rs`)**: Added `self.sync_document_versions()` immediately after `self.flush_dirty()` in `notification.rs` and `self.flush_buffer(&uri)` in `ahead.rs` so `Document::version()` remains `Some(v)` immediately after `didSave(text: None)`, `didClose(other)`, `didChangeWatchedFiles`, or mid-scan buffer flushes. Added regression test `qa_f2_document_version_survives_flush_dirty_and_flush_buffer_immediately` in `ordering_r1.rs`. - **Cross-lane F2b (`crates/lucisv_server/src/same_file.rs`, `same_file/tests.rs`, `server/tests/fast_actions_differential.rs`)**: Updated `same_file::renamed_here` with `enclosed_by_unit` so `textDocument/prepareRename` defers (`false`) for symbols inside file-scope units (`Module`, `Interface`, `Package`, `Typedef`, `Class`), updated `same_file/tests.rs`, and added `"dup_b.sv"` to `early_answers_equal_settled_over_the_locality_shapes` in `fast_actions_differential.rs`. ## QA log ### 2026-11-26 — QA agent (Round 1, Lane 1B) **Verdict: FAIL** (two concrete Topo #52 bugs found; Topo #53, Topo #61, and Topo #62 passed all adversarial checks and live OpenTitan probing). #### Ownership, hygiene, and size checks - **File ownership (`git status` / `git diff --stat`)**: All DEV changes are inside the lane's allowed files (`main.rs`, `ports.rs`, `rename.rs`, `server/{mod,startup,dispatch,notification,ahead}.rs`, `state/document.rs`, `server/tests/{mod,fast_actions_bursts,fast_actions_precondition,scan_ordering,ordering_r1}.rs`, `docs/features/server-ordering-r1/README.md`). QA added 5 passing adversarial regression tests in `crates/lucisv_server/src/server/tests/ordering_r1.rs` (`qa_topo_53_*`, `qa_topo_52_full_version_lifecycle_*`, `qa_topo_61_attack_burst_*`). - **Production line counts (non-blank, non-comment lines before `mod tests {`)**: All modified production files are `<= 600` lines (`dispatch.rs`: 522, `main.rs`: 400, `ports.rs`: 367, `server/mod.rs`: 311, `notification.rs`: 261, `ahead.rs`: 250, `startup.rs`: 192, `state/document.rs`: 135, `rename.rs`: 88). - **Safety / author stamps**: `0` occurrences of `unwrap(`, `expect(`, `panic!`, or `unsafe` in modified production code. `python3 tools/stamp_author.py --check` exits `0`. #### Verification & adversarial attacks 1. **Topo #53 (`after_scan` & `waits_for_whole_scan`) — PASS**: - Inspected `Server::hold`, `must_wait`, `must_wait_for`, `must_hold`, `after_scan` drain in `Server::run`, `waiting_for_this_scan`, `nothing_unapplied_for`, and `answer_ahead_mid_widen`. `held` and `after_scan` remain mutually exclusive across `hold`, `answer_ahead_mid_widen`, and `run`, preserving arrival order on nested `process_batch` scans and avoiding O(N) re-drain spinning (`handed_back <= 1`). - Added and passed QA tests in `ordering_r1.rs` covering: `$/cancelRequest` arriving in a later burst while `rename` sits in `after_scan`; `$/cancelRequest` in the same burst as `rename` while `head_owed == true` (transitioning `held -> after_scan`); incremental `didChange` behind `rename` in `after_scan` followed by a second incremental `didChange` and mid-scan `didSave` (`rescan_wanted = true`, two scan `end`s before `after_scan` drains). - **Live OpenTitan 10-spawn probe** (`./tools/guard.sh -m 6 -t 600 -- cargo build --release -p lucisv_server` -> `target/release/lucisv-server --verbose` against `/Users/lucio/repo/opentitan`, `hw/top_englishbreakfast/ip/ast/rtl/adc.sv` line 81 col 42 `rst_adc_ni`, workspace scope with `persist: false` and scratch `/tmp` storage dirs): 5 startup-burst spawns + 5 mid-scan `$/progress` `report` spawns (`4044 files`) all logged `textDocument/rename HELD behind a rescan`, answered strictly after `$/progress` `end`, exited `0`, and returned **10/10 identical** deterministic refusal (`code: -32803`, ``"lucisv: `rst_adc_ni` is declared in more than one indexed file; lucisv will not guess which declaration this rename means."``). `git -C /Users/lucio/repo/opentitan status --porcelain` remained empty. 2. **Topo #52 (versioned `documentChanges`) — FAIL (2 findings)**: - Passing lifecycle checks (`qa_topo_52_full_version_lifecycle_open_change_save_empty_change_rename_and_overlay` + `topo_52_session_tracks_versions_and_emits_versioned_document_changes`): `didOpen(v=1)` -> `didChange(v=2)` -> `didSave(None)` -> `didChange(v=3, contentChanges=[])` -> `watched` (`Document::refresh_overlay`) -> `rename` (mixed `Some(3)` and `None`, `changes` fallback when `document_changes=false`), eager `codeAction`, `codeAction/resolve`, `executeCommand` (`workspace/applyEdit`), `largeFile.threshold` reclassification, and `didClose` resetting version to `None` all pass for canonical `file:///` URIs. - **Finding 1 (Medium/High — wire bug): `crates/lucisv_server/src/ports.rs:555-571` (`encode_edit`) drops document versions and emits unversioned `changes` (or `version: None`) for valid non-canonical `file:` URIs.** - At `ports.rs:555`, `ws.text_of(path)` resolves open buffers via `d.path.as_deref() == Some(path)` (`state/buffers.rs:103`), whereas `ports.rs:570` computes `target = path_to_uri(path)` and looks up `ws.document(&target).and_then(Document::version)`. - Whenever the client opened the file with a valid `file:` URI whose serialization differs from `path_to_uri(path)` — e.g. `file://localhost/...` (explicitly supported by `uri.rs:38`), lowercase percent-encoding such as `caf%c3%a9.sv` vs `path_to_uri`'s `%C3%A9`, or Windows VS Code's `file:///c%3A/...` vs `file:///C:/...` — `ws.document(&target)` returns `None`, silently losing the buffer's version (`Some(v)` -> `None`) and falling back to unversioned `changes` (and `target` also fails to echo the client's open URI). - **Reproduction**: Open `caf%c3%a9.sv` (or `file://localhost//sub.sv`) at `version: 12` with `ClientAbilities { document_changes: true, ..Default::default() }`, then issue `textDocument/rename` on it (or cross-file from `top.sv`). `rename` returns `{"changes": ...}` (or `version: null` for `sub.sv` in cross-file `documentChanges`) instead of `documentChanges` with `version: 12`. - **Finding 2 (Low/Medium — state invariant leak): `crates/lucisv_server/src/server/notification.rs:71` (`handle_notification` `flush_dirty`) and `crates/lucisv_server/src/server/ahead.rs:195` (`flush_buffer`) rebuild `Document` without re-attaching `self.versions`.** - `notification.rs:71` runs `self.flush_dirty()` on non-`didChange` notifications such as `didSave` with `text: None` (the default because `main.rs:221` advertises `include_text: Some(false)`), `didClose` of another file, or `didChangeWatchedFiles`. `flush_dirty()` calls `set_document`, replacing the `Document` with `version = NO_VERSION` (`None`). Only `didSave(Some(text))` (`notification.rs:167`) and `apply_settings` (`notification.rs:366`) call `self.sync_document_versions()`. Similarly `ahead.rs:195` (`flush_buffer`) does not sync versions. - Currently masked on LSP wire requests because `dispatch.rs:172` (`answer_request`) calls `self.sync_document_versions()` before `answer_flushed`, but `Document::version()` on `Workspace` is `None` immediately after `didSave(None)` until the next request or debounce timeout. - **Reproduction**: `didOpen(uri, v=1)` -> `didChange(uri, v=2, text)` -> `didSave(uri)` (no `text` field). Immediately inspecting `session.server.workspace.document(&uri).unwrap().version()` returns `None` instead of `Some(2)`. 3. **Topo #61 (`take_the_answer_out_of_held`) — PASS**: - Tested attack burst `[didOpen, (optional lens), push(A: threshold=0), hover, settings_answer(B: threshold=100), push(C: threshold=4MiB)]` in `qa_topo_61_attack_burst_didopen_push_a_hover_answer_b_push_c`: `B` beats `A` (`hover` sees threshold=100 -> `Null`), `hover` is not dropped, `C` beats `B` once `held` drains (`threshold=4MiB`), and `applied_changes` matches exact applied state transitions (`2`/`3` at staging end, `+1` after `push(C)`). 4. **Topo #62 (`fast_actions_bursts`) — PASS**: - Inspected `fast_actions_bursts.rs:403-511`: `ahead_applied` records `self.applied_changes` at `answered_ahead` (`ahead.rs:237`) and asserts both `applied >= required` (prior reaching `can_reach` or config changes) and `e == reference_at[applied]`. - Ran `fast_actions_bursts` (`1448 requests, 384 answered ahead (0 from a later state), 1280 settled comparisons`), 300-round `answers_given_ahead_equal_a_one_message_at_a_time_server_long_run` (`seed 7: 1313 requests, 400 answered ahead (0 from a later state), 1200 settled comparisons, 0 differ`), and `ordering_random` (`12 seeds × 10 rounds`, pass). - Verified oracle sensitivity via temporary mutations (reverted immediately): subtracting 1 from `applied` failed immediately at `seed 1, round 0` (`6 answered at applied=1 ahead of reaching change 2`), and skipping `self.flush_buffer(&uri)` in `ahead.rs:195` failed at `seed 2, round 5` (`28 went ahead at applied=4 (required >= 4) with wrong state`). #### Full crate gates (worktree, after final edits) - `python3 tools/stamp_author.py --check` -> exit 0 - `cargo fmt -p lucisv_server -- --check` -> exit 0 - `./tools/guard.sh -m 6 -t 600 -- cargo clippy -p lucisv_server --all-targets -- -D warnings` -> exit 0 - `./tools/guard.sh -m 6 -t 600 -- cargo test -p lucisv_server --all-targets` -> `2,043` passed (`47` ignored) unit + `106` passed (`3` ignored) e2e + `3` grammar + `1` ifdef_folding + `0` passed (`2` ignored) opentitan_references; `0` failed ### 2026-11-26 — QA re-check (Round 1, Lane 1B) **Verdict: PASS** (F1, F2, and cross-lane F2b all verified fixed; full crate gates green). #### Ownership, hygiene, and size checks - **File ownership (`git status` / `git diff --stat`)**: Only owned `crates/lucisv_server/` files (`main.rs`, `ports.rs`, `rename.rs`, `same_file.rs`, `same_file/tests.rs`, `server/{mod,startup,dispatch,notification,ahead}.rs`, `state/document.rs`, `server/tests/{mod,fast_actions_bursts,fast_actions_differential,fast_actions_precondition,ordering_r1,scan_ordering}.rs`) and `docs/features/server-ordering-r1/README.md` are modified or untracked. QA added 2 passing re-check regression tests (`qa_r2_f1_*`, `qa_r2_f2_*`) in `crates/lucisv_server/src/server/tests/ordering_r1.rs`. - **Production line counts (non-blank, non-comment before inline `mod tests {`)**: All modified production files remain `<= 600` lines (`dispatch.rs`: 522, `main.rs`: 400, `ports.rs`: 374, `server/mod.rs`: 311, `notification.rs`: 262, `ahead.rs`: 251, `startup.rs`: 192, `state/document.rs`: 134, `same_file.rs`: 126, `rename.rs`: 88). - **Safety / author stamps**: `0` occurrences of `unwrap(`, `expect(`, `panic!`, or `unsafe` in modified production code. `python3 tools/stamp_author.py --check` exits `0`. #### Re-verification & adversarial attack results 1. **Attack F1 (`ports.rs::encode_edit`) — PASS**: - Verified `ws.open_documents().find(|(_, doc)| doc.path.as_deref() == Some(path))` preserves client non-canonical URIs (`file://localhost/...` and lowercase percent-encoded `caf%c3%a9.sv`) and `doc.version()`, while closed files fall back to canonical `path_to_uri(path)` with `version: None`. - Verified `qa_f1_non_canonical_client_uris_preserve_uri_and_version_in_edits` and QA-added `qa_r2_f1_multifile_rename_open_noncanonical_and_closed_doc_with_and_without_document_changes` pass: multi-file `textDocument/rename` touching one open non-canonical URI (`file://localhost/...` or `caf%c3%a9.sv`) plus one closed file (`version: null`) emits `documentChanges` when enabled and uses the client's open URI as the `changes` map key when `documentChanges` is disabled. 2. **Attack F2 (`notification.rs` / `ahead.rs` version sync) — PASS**: - Verified `qa_f2_document_version_survives_flush_dirty_and_flush_buffer_immediately` passes. - Audited all `Document` reconstruction call sites across `server/` and `state/`: every `Server::set_document`, `flush_dirty`, `flush_buffer`, and `reclassify_large_buffers` caller (`notification.rs`, `ahead.rs`, `dispatch.rs`, `server/mod.rs`, `startup.rs`) immediately runs `record_document_version` or `sync_document_versions()`. - Verified QA-added `qa_r2_f2_document_version_survives_reclassify_incremental_apply_changes_and_didsave_with_text` passes across incremental `apply_changes_at` + flush, `didSave(text: Some(...))`, and `reclassify_large_buffers` (`normal -> large -> normal`). 3. **Attack F2b (`same_file.rs::renamed_here` + `fast_actions_differential.rs`) — PASS**: - Verified `enclosed_by_unit` matches `vlog_semantic`'s 5 unit kinds (`Module`, `Interface`, `Package`, `Typedef`, `Class`) at `file_scope` and walks parent scopes so declarations/uses inside file-scope units wait for the index. - Confirmed `"dup_b.sv"` runs in `fast_actions_differential::early_answers_equal_settled_over_the_locality_shapes` (`early=3378 waited=614 differed=0`), `same_file::tests::prepare_rename_waits_at_file_scope_inside_units_and_on_an_unresolved_use` passes, and `fast_actions_bursts::answers_given_ahead_equal_a_one_message_at_a_time_server` passes (`1448 requests, 284 answered ahead (0 from a later state), 1280 settled comparisons`). #### Full crate gates (worktree, after final edits) - `python3 tools/stamp_author.py --check` -> exit 0 - `cargo fmt -p lucisv_server -- --check` -> exit 0 - `./tools/guard.sh -m 6 -t 600 -- cargo clippy -p lucisv_server --all-targets -- -D warnings` -> exit 0 - `./tools/guard.sh -m 6 -t 600 -- cargo test -p lucisv_server --all-targets` -> `2,048` passed (`47` ignored) unit + `106` passed (`3` ignored) e2e + `3` grammar + `1` ifdef_folding + `0` passed (`2` ignored) opentitan_references; `0` failed ## Review ### 2026-11-26 — Lead review: PASS (merged with Lane 1A in Round 1) - Inspected combined diff across `lucisv_server` and verified `after_scan` exclusivity, non-canonical URI/version tracking in `ports::encode_edit`, immediate `sync_document_versions` after `flush_dirty`/`flush_buffer`, staging push draining (`#61`), exact `applied_changes` oracle (`#62`), and `same_file::renamed_here` parity (`F2b`) with Lane 1A's duplicate-unit check. - Live 10-spawn OpenTitan `adc.sv:81` probe confirmed 10/10 deterministic refusal with `/Users/lucio/repo/opentitan` untouched. - Handshakes closed in `docs/topo.md`: `#52`, `#53` (server half), `#61`, `#62`. Full `tools/gates.sh` verified green on merged `master`.