LSP §9b: $/cancelRequest — burst reads, stateless cancellation

run() now reads in bursts: one blocking receive plus everything already
queued behind it, processed strictly in arrival order. A request whose
$/cancelRequest sits in the same burst is answered RequestCancelled
(-32800) without being dispatched; cancels naming anything else — an
already-answered request, one never received, a server-initiated id —
are dropped on the spot, so cancellation holds no state that can leak
or misfire. shutdown is honoured before the cancel set is consulted,
and a didChange queued ahead of a request is still applied first.

The enabling change: lsp-server 0.10's stdio transport uses rendezvous
channels, so a client's backlog never queues on connection.receiver —
it sits invisible in the OS pipe (dev measured 0/5 cancels honoured
under the original drain design). A single forwarder thread moves
messages onto an unbounded queue, stopping at shutdown because
handle_shutdown reads the following exit off the connection itself.
First thread in this server; QA re-derived the hand-off from the
vendored lsp-server source and found no steal or deadlock window.

15 tests added (dev 11 + QA 4), covering the full cancel matrix (both
id types, double cancel, orphan drop with id-reuse proof, malformed
params), the forwarder against a real Connection, and an e2e flood of
20 requests with cancels asserting schedule-independent properties —
green across twelve consecutive runs. Completes TODO.md §9b.

docs/features/cancel-request/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-26 14:10:59 -07:00
1 parent e165c37a3a
commit 6523c604bb
5 files changed
+1234 -27

No files matched your search

+21 -1
View File
@@ -750,9 +750,29 @@ and are not gaps.
— the rescan is one opaque call — and the `end` names the indexed
file count, read off the index's own file list. The bar covers the
scan, ending before the scope warnings and the republishes.
- [ ] **`$/cancelRequest`** — the loop handles requests sequentially
- [x] **`$/cancelRequest`** — the loop handles requests sequentially
and ignores cancellation; at minimum answer already-cancelled queued
requests with `RequestCancelled`.
→ `docs/features/cancel-request/README.md`; **completes §9b.** `run()`
now reads in bursts — one blocking receive, then everything already
queued behind it — and handles the burst **in arrival order**, so a
`didChange` ahead of a request is still applied before that request is
answered. A request the same burst also carries a cancel for is
answered `RequestCancelled` (-32800) without being dispatched; the
cancels themselves are consumed there and never reach
`notification()`. A cancel naming no request in its burst is dropped
on the spot — it refers to a request already answered, or to one that
never arrived — so the feature holds no state between bursts, and a
double cancel is harmless. `shutdown` is honoured before the cancelled
set is consulted and so is never cancellable. Numeric and string ids
both read; malformed cancels dropped. The design's one correction:
`lsp-server` 0.10 wires its stdio transport with `bounded(0)`
*rendezvous* channels, so a backlog never sits on
`connection.receiver` at all — the loop forwards messages onto an
unbounded `std::sync::mpsc` queue of its own on one small thread
(std-only, no new dependency), which stops at `shutdown` so
`handle_shutdown` still reads the `exit` that follows. Nothing already
running is cancelled; that needs the worker pool §6 defers.
### 9c. Moderate value, Verilog-shaped
+552 -20
View File
@@ -1,18 +1,22 @@
//! The request loop: one message in, one response out, on one thread.
//! The request loop: one burst in, one response per request, on one thread.
//!
//! `lsp-server` runs two I/O threads of its own and hands this loop framed
//! messages over a channel. Everything below is synchronous and un-cancellable
//! — Verilog files are small, every handler is milliseconds, and a worker pool
//! would buy nothing yet. See `docs/features/lucisv-server/README.md`.
//! messages over a channel. Everything below is synchronous — Verilog files
//! are small, every handler is milliseconds, and a worker pool would buy
//! nothing yet. A request that has already started therefore runs to
//! completion; the one thing `$/cancelRequest` can do here is answer a request
//! still *queued* behind the one being served, which is what the burst drain
//! in `run` is for. See `docs/features/lucisv-server/README.md` and
//! `docs/features/cancel-request/README.md`.
use std::collections::{HashMap, HashSet};
use std::error::Error;
use lsp_server::{Connection, ExtractError, Message, Notification, Request, RequestId, Response};
use lsp_types::notification::{
DidChangeConfiguration, DidChangeTextDocument, DidChangeWatchedFiles, DidCloseTextDocument,
DidOpenTextDocument, DidSaveTextDocument, LogMessage, Notification as _, Progress,
PublishDiagnostics, ShowMessage,
Cancel, DidChangeConfiguration, DidChangeTextDocument, DidChangeWatchedFiles,
DidCloseTextDocument, DidOpenTextDocument, DidSaveTextDocument, LogMessage, Notification as _,
Progress, PublishDiagnostics, ShowMessage,
};
use lsp_types::request::{
ApplyWorkspaceEdit, CallHierarchyIncomingCalls, CallHierarchyOutgoingCalls,
@@ -21,23 +25,23 @@ use lsp_types::request::{
FoldingRangeRequest, Formatting, GotoDefinition, HoverRequest, InlayHintRequest,
InlineCompletionRequest, PrepareRenameRequest, RangeFormatting, References, RegisterCapability,
Rename, Request as _, SelectionRangeRequest, SemanticTokensFullDeltaRequest,
SemanticTokensFullRequest, SemanticTokensRangeRequest, SignatureHelpRequest,
SemanticTokensFullRequest, SemanticTokensRangeRequest, Shutdown, SignatureHelpRequest,
UnregisterCapability, WillSaveWaitUntil, WorkDoneProgressCreate, WorkspaceDiagnosticRequest,
WorkspaceSymbolRequest,
};
use lsp_types::{
ApplyWorkspaceEditParams, ApplyWorkspaceEditResponse, CallHierarchyIncomingCallsParams,
CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams, CodeActionKind, CodeActionParams,
CompletionParams, DidChangeConfigurationParams, DidChangeTextDocumentParams,
CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams, CancelParams, CodeActionKind,
CodeActionParams, CompletionParams, DidChangeConfigurationParams, DidChangeTextDocumentParams,
DidChangeWatchedFilesParams, DidCloseTextDocumentParams, DidOpenTextDocumentParams,
DidSaveTextDocumentParams, DocumentDiagnosticParams, DocumentDiagnosticReport,
DocumentDiagnosticReportResult, DocumentFormattingParams, DocumentHighlightParams,
DocumentLinkParams, DocumentRangeFormattingParams, DocumentSymbolParams,
DocumentSymbolResponse, ExecuteCommandParams, FoldingRangeParams, FullDocumentDiagnosticReport,
GotoDefinitionParams, GotoDefinitionResponse, HoverParams, InlayHintParams,
InlineCompletionParams, LogMessageParams, MessageType, Position, PreviousResultId,
ProgressParams, ProgressParamsValue, ProgressToken, PublishDiagnosticsParams, ReferenceParams,
RegistrationParams, RelatedFullDocumentDiagnosticReport,
InlineCompletionParams, LogMessageParams, MessageType, NumberOrString, Position,
PreviousResultId, ProgressParams, ProgressParamsValue, ProgressToken, PublishDiagnosticsParams,
ReferenceParams, RegistrationParams, RelatedFullDocumentDiagnosticReport,
RelatedUnchangedDocumentDiagnosticReport, RenameParams, SelectionRangeParams, SemanticToken,
SemanticTokens, SemanticTokensDelta, SemanticTokensDeltaParams, SemanticTokensFullDeltaResult,
SemanticTokensParams, SemanticTokensRangeParams, SemanticTokensRangeResult,
@@ -171,21 +175,90 @@ impl Server {
}
/// Receive until the client shuts us down or the channel closes.
///
/// One blocking receive, then everything already queued behind it, then
/// that whole burst in arrival order. The drain is what makes
/// `$/cancelRequest` mean anything: while a handler runs, the client's
/// later requests and its cancels for them pile up together, and a cancel
/// found next to its request answers that request for free.
pub fn run(&mut self) -> Result<(), Box<dyn Error + Sync + Send>> {
while let Ok(message) = self.connection.receiver.recv() {
let queue = self.queue();
while let Ok(message) = queue.recv() {
if self.process_batch(burst(&queue, message))? {
return Ok(());
}
}
Ok(())
}
/// Move the incoming messages onto a queue of our own, and report it.
///
/// Necessary because `lsp-server`'s transport hands messages over
/// *rendezvous* channels — `bounded(0)`. Its reader thread parks holding
/// one message until this loop takes it, so a client's backlog never sits
/// on `connection.receiver` at all: it sits in the OS pipe, invisible and
/// one message deep. Forwarding onto an unbounded queue is what makes
/// "everything already sent" observable without blocking, which is the
/// whole premise of the burst below.
///
/// The forwarder stops at `shutdown` and never reads past it, because
/// `handle_shutdown` reads the `exit` notification off the *connection*
/// itself — a forwarder that kept going would steal it and strand the
/// handshake for thirty seconds. It owns nothing but messages in flight
/// and touches no server state.
fn queue(&self) -> std::sync::mpsc::Receiver<Message> {
let (sender, receiver) = std::sync::mpsc::channel();
let source = self.connection.receiver.clone();
// A failed spawn would leave the server unable to receive anything at
// all; there is nothing useful to do with that but let `run` end when
// the queue's sender is dropped.
let _ = std::thread::Builder::new().name("lucisv-queue".to_string()).spawn(move || {
while let Ok(message) = source.recv() {
let last = is_shutdown(&message);
if sender.send(message).is_err() || last {
break;
}
}
});
receiver
}
/// Handle one burst in arrival order, reporting whether the client shut us
/// down.
///
/// Order is the whole contract: a `didChange` queued ahead of a completion
/// is applied before that completion is answered, exactly as it would be
/// one message at a time. The only thing the burst adds is that a request
/// this burst also carries a cancel for is answered `RequestCancelled`
/// instead of computed — except `shutdown`, which is honoured before the
/// cancelled set is ever consulted, so no cancel can talk the server out
/// of shutting down.
fn process_batch(&mut self, batch: Vec<Message>) -> Result<bool, Box<dyn Error + Sync + Send>> {
let mut cancelled = cancelled_in(&batch);
for message in batch {
match message {
Message::Request(request) => {
if self.connection.handle_shutdown(&request)? {
return Ok(());
return Ok(true);
}
let response = self.request(request);
// Removed as it is used: a second cancel for the same id
// then finds nothing, and the set cannot outlive the burst.
let response = if cancelled.remove(&request.id) {
cancelled_response(request.id)
} else {
self.request(request)
};
self.connection.sender.send(Message::Response(response))?;
}
// The cancels themselves are consumed here — `notification`
// has nothing to do with one, and everything it could do has
// already been done above.
Message::Notification(notification) if notification.method == Cancel::METHOD => {}
Message::Notification(notification) => self.notification(notification),
Message::Response(response) => self.response(response),
}
}
Ok(())
Ok(false)
}
// ------------------------------------------------------------------
@@ -923,9 +996,11 @@ impl Server {
token.clone(),
WorkDoneProgress::Begin(WorkDoneProgressBegin {
title: INDEXING_TITLE.to_string(),
// There is no cancellation anywhere in this server: the loop is
// one thread and a rescan runs to completion. Saying so is
// what keeps a cancel button the user could press off the bar.
// Nothing already running in this server can be cancelled: the
// loop is one thread and a rescan runs to completion — the
// `$/cancelRequest` support only answers requests still
// queued. Saying so is what keeps a cancel button the user
// could press off the bar.
cancellable: Some(false),
..Default::default()
}),
@@ -1034,6 +1109,73 @@ impl Server {
}
}
// ----------------------------------------------------------------------
// cancellation
// ----------------------------------------------------------------------
/// Whether this message is the `shutdown` request. `lsp-server` keeps its own
/// answer to that question private, so it is asked here by method name — the
/// same name `handle_shutdown` matches on.
fn is_shutdown(message: &Message) -> bool {
matches!(message, Message::Request(request) if request.method == Shutdown::METHOD)
}
/// `first` plus everything already waiting on the queue behind it — the
/// client's backlog, in arrival order. Never blocks: what is not there yet
/// belongs to the next burst.
fn burst(queue: &std::sync::mpsc::Receiver<Message>, first: Message) -> Vec<Message> {
let mut batch = vec![first];
while let Ok(message) = queue.try_recv() {
batch.push(message);
}
batch
}
/// The ids this burst cancels: every `$/cancelRequest` in it that names a
/// request the burst *also* carries.
///
/// A cancel naming anything else is dropped right here — it refers to a
/// request answered in some earlier burst, or to one this server never
/// received, and either way there is nothing left to cancel. That is what
/// keeps this from becoming a set that grows for the life of the session.
fn cancelled_in(batch: &[Message]) -> HashSet<RequestId> {
let queued: HashSet<&RequestId> = batch
.iter()
.filter_map(|message| match message {
Message::Request(request) => Some(&request.id),
_ => None,
})
.collect();
batch.iter().filter_map(cancelled_id).filter(|id| queued.contains(id)).collect()
}
/// The request id a `$/cancelRequest` names, or `None` for any other message.
/// Both id forms the protocol allows are read; a cancel whose params do not
/// parse is dropped, because there is no id to act on.
fn cancelled_id(message: &Message) -> Option<RequestId> {
let Message::Notification(notification) = message else { return None };
if notification.method != Cancel::METHOD {
return None;
}
let params: CancelParams = serde_json::from_value(notification.params.clone()).ok()?;
Some(match params.id {
NumberOrString::Number(number) => RequestId::from(number),
NumberOrString::String(text) => RequestId::from(text),
})
}
/// What a cancelled request is answered with. Every request gets exactly one
/// response, cancelled or not — the protocol's own `RequestCancelled`
/// (-32800), which a client reads as "the one you asked me to drop" rather
/// than as a failure worth showing the user.
fn cancelled_response(id: RequestId) -> Response {
Response::new_err(
id,
lsp_server::ErrorCode::RequestCanceled as i32,
"lucisv: request cancelled by the client".to_string(),
)
}
// ----------------------------------------------------------------------
// decoding and failures
// ----------------------------------------------------------------------
@@ -1275,6 +1417,23 @@ mod tests {
uri
}
/// Drive one burst through the real loop body — the whole of `run`
/// except the receiving — reporting whether the client shut us down.
fn batch(&mut self, messages: Vec<Message>) -> bool {
self.server.process_batch(messages).expect("the burst is handled")
}
/// The responses the server sent since the last drain, in order.
fn answers(&self) -> Vec<Response> {
self.drain()
.into_iter()
.filter_map(|message| match message {
Message::Response(response) => Some(response),
_ => None,
})
.collect()
}
fn watched(&mut self, paths: &[PathBuf]) {
let changes: Vec<FileEvent> = paths
.iter()
@@ -3169,4 +3328,377 @@ mod tests {
assert_eq!(held, ground_truth(&session, &uri), "step {i}: the chain matches the truth");
}
}
// ------------------------------------------------------------------
// $/cancelRequest — docs/features/cancel-request/README.md
// ------------------------------------------------------------------
/// A `textDocument/documentSymbol` request, queued. Any request would do;
/// this one is cheap and its answer names what the buffer holds, which is
/// what the ordering test needs.
fn ask(id: i32, uri: &Uri) -> Message {
Message::Request(Request::new(
RequestId::from(id),
DocumentSymbolRequest::METHOD.to_string(),
serde_json::json!({ "textDocument": { "uri": uri } }),
))
}
/// A `$/cancelRequest` naming `id`, exactly as a client sends it — the id
/// is passed as raw JSON so both protocol forms can be tested.
fn cancel(id: Value) -> Message {
Message::Notification(Notification::new(
Cancel::METHOD.to_string(),
serde_json::json!({ "id": id }),
))
}
/// A whole-buffer `didChange`, queued.
fn changed(uri: &Uri, version: u32, text: &str) -> Message {
Message::Notification(Notification::new(
DidChangeTextDocument::METHOD.to_string(),
serde_json::json!({
"textDocument": { "uri": uri, "version": version },
"contentChanges": [{ "text": text }],
}),
))
}
/// The protocol's `RequestCancelled`.
const CANCELLED: i32 = -32800;
/// Every response since the last drain, as (id, error code or `None`).
fn outcomes(session: &Session) -> Vec<(RequestId, Option<i32>)> {
session
.answers()
.into_iter()
.map(|response| {
let code = response.response_result.err().map(|error| error.code);
(response.id, code)
})
.collect()
}
/// The top-level symbol names in a `documentSymbol` answer.
fn symbol_names(result: &Value) -> Vec<String> {
result
.as_array()
.expect("an array of symbols")
.iter()
.map(|symbol| symbol["name"].as_str().expect("a name").to_string())
.collect()
}
/// A session with one open buffer, drained of the startup traffic.
fn cancelling_session(name: &str, text: &str) -> (Tree, Session, Uri) {
let tree = Tree::new(name);
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), text);
let _ = session.drain();
(tree, session, uri)
}
const ONE_MODULE: &str = "module m;\nendmodule\n";
#[test]
fn a_request_cancelled_in_the_same_burst_is_answered_cancelled() {
// The point of the whole feature: the client asked and changed its
// mind while the server was busy elsewhere, so the answer costs
// nothing to produce.
let (_tree, mut session, uri) = cancelling_session("cancelsame", ONE_MODULE);
let shutdown = session.batch(vec![ask(1, &uri), cancel(serde_json::json!(1))]);
assert!(!shutdown, "a cancel is not a shutdown");
assert_eq!(outcomes(&session), vec![(RequestId::from(1), Some(CANCELLED))]);
}
#[test]
fn a_cancel_dequeued_before_its_request_still_cancels_it() {
// The batch is scanned as a whole before any of it runs, so a cancel
// the transport happened to deliver first is not a cancel that
// arrived too early.
let (_tree, mut session, uri) = cancelling_session("cancelfirst", ONE_MODULE);
session.batch(vec![cancel(serde_json::json!(1)), ask(1, &uri)]);
assert_eq!(outcomes(&session), vec![(RequestId::from(1), Some(CANCELLED))]);
}
#[test]
fn a_cancel_names_one_request_and_leaves_the_rest_of_the_burst_alone() {
let (_tree, mut session, uri) = cancelling_session("cancelone", ONE_MODULE);
session.batch(vec![ask(1, &uri), ask(2, &uri), cancel(serde_json::json!(1))]);
assert_eq!(
outcomes(&session),
vec![(RequestId::from(1), Some(CANCELLED)), (RequestId::from(2), None)],
"id 2 was answered normally, and in its own place in the queue"
);
}
#[test]
fn a_cancel_for_a_request_that_is_not_in_the_burst_is_dropped_on_the_spot() {
// A cancel that arrives in a later burst than its request is too late
// — that request was answered already — and remembering it would be a
// set that grows for the life of the session. The identical id in the
// burst after proves nothing was kept: real clients never reuse an
// id, so only a leak could cancel this one.
let (_tree, mut session, uri) = cancelling_session("cancellate", ONE_MODULE);
let shutdown = session.batch(vec![cancel(serde_json::json!(1))]);
assert!(!shutdown);
assert_eq!(outcomes(&session), vec![], "a lone cancel is answered with nothing at all");
session.batch(vec![ask(1, &uri)]);
assert_eq!(
outcomes(&session),
vec![(RequestId::from(1), None)],
"the dropped cancel did not survive into the next burst"
);
}
#[test]
fn a_notification_queued_ahead_of_a_request_is_applied_before_it_is_answered() {
// The invariant the burst must not break: order. A `didChange` the
// client sent before its request has to be in effect when that
// request is answered, exactly as it would be one message at a time.
let (_tree, mut session, uri) = cancelling_session("cancelorder", ONE_MODULE);
session.batch(vec![changed(&uri, 2, "module renamed;\nendmodule\n"), ask(1, &uri)]);
let answers = session.answers();
assert_eq!(answers.len(), 1);
let result = answers[0].response_result.clone().expect("an answer");
assert_eq!(symbol_names(&result), vec!["renamed".to_string()]);
}
#[test]
fn a_cancel_never_cancels_a_notification() {
// Notifications carry no id and get no response, so nothing in a
// burst can suppress one — whatever id the cancel names.
let (_tree, mut session, uri) = cancelling_session("cancelnotify", ONE_MODULE);
session.batch(vec![
changed(&uri, 2, "module renamed;\nendmodule\n"),
cancel(serde_json::json!(1)),
cancel(serde_json::json!("textDocument/didChange")),
]);
assert_eq!(buffer(&session, &uri), "module renamed;\nendmodule\n");
assert_eq!(outcomes(&session), vec![], "no ids were cancelled, so no responses");
}
#[test]
fn a_shutdown_is_honoured_however_it_is_cancelled() {
// The spec lets a server answer a cancelled request normally, and for
// `shutdown` that is the only safe reading: a client that cannot shut
// the server down leaks a process. `handle_shutdown` runs before the
// cancelled set is consulted, so the cancel never gets a say.
let (_tree, mut session, _uri) = cancelling_session("cancelshutdown", ONE_MODULE);
// `handle_shutdown` waits for the `exit` that follows; queue it the
// way a real client's would already be queued.
session
.client
.sender
.send(Message::Notification(Notification::new("exit".to_string(), Value::Null)))
.expect("queue exit");
let request = Message::Request(Request::new(
RequestId::from(9),
Shutdown::METHOD.to_string(),
Value::Null,
));
let shutdown = session.batch(vec![request, cancel(serde_json::json!(9))]);
assert!(shutdown, "the loop exits");
assert_eq!(
outcomes(&session),
vec![(RequestId::from(9), None)],
"shutdown was answered, and answered successfully"
);
}
#[test]
fn cancelling_one_request_twice_answers_it_once() {
let (_tree, mut session, uri) = cancelling_session("canceltwice", ONE_MODULE);
session.batch(vec![
ask(1, &uri),
cancel(serde_json::json!(1)),
cancel(serde_json::json!(1)),
ask(2, &uri),
]);
assert_eq!(
outcomes(&session),
vec![(RequestId::from(1), Some(CANCELLED)), (RequestId::from(2), None)],
"the second cancel changed nothing — id 2 is not collateral damage"
);
}
#[test]
fn a_cancel_id_may_be_a_number_or_a_string() {
// The protocol allows both, and a client that numbers its requests
// with strings is not exotic.
let (_tree, mut session, uri) = cancelling_session("cancelstring", ONE_MODULE);
let request = Message::Request(Request::new(
RequestId::from("abc".to_string()),
DocumentSymbolRequest::METHOD.to_string(),
serde_json::json!({ "textDocument": { "uri": &uri } }),
));
session.batch(vec![request, cancel(serde_json::json!("abc"))]);
assert_eq!(outcomes(&session), vec![(RequestId::from("abc".to_string()), Some(CANCELLED))]);
session.batch(vec![ask(7, &uri), cancel(serde_json::json!(7))]);
assert_eq!(outcomes(&session), vec![(RequestId::from(7), Some(CANCELLED))]);
// A string that spells a number is not the number: `RequestId` keeps
// the two apart, and so must the cancel.
session.batch(vec![ask(8, &uri), cancel(serde_json::json!("8"))]);
assert_eq!(
outcomes(&session),
vec![(RequestId::from(8), None)],
"the string \"8\" does not cancel the number 8"
);
}
#[test]
fn a_malformed_cancel_is_dropped_rather_than_guessed_at() {
let (_tree, mut session, uri) = cancelling_session("cancelmalformed", ONE_MODULE);
let broken = Message::Notification(Notification::new(
Cancel::METHOD.to_string(),
serde_json::json!({ "id": { "nested": true } }),
));
session.batch(vec![ask(1, &uri), broken]);
assert_eq!(outcomes(&session), vec![(RequestId::from(1), None)]);
}
#[test]
fn is_shutdown_matches_only_the_shutdown_request_never_a_notification_of_the_same_name() {
// The forwarder stops forwarding the moment it sees this return
// `true`. A malformed or adversarial client sending a *notification*
// named "shutdown" must not trip it — that would silently stall the
// whole backlog, with `handle_shutdown` never having run to explain
// why.
let request = Message::Request(Request::new(
RequestId::from(1),
Shutdown::METHOD.to_string(),
Value::Null,
));
let notification =
Message::Notification(Notification::new(Shutdown::METHOD.to_string(), Value::Null));
let other_request = Message::Request(Request::new(
RequestId::from(2),
DocumentSymbolRequest::METHOD.to_string(),
Value::Null,
));
assert!(is_shutdown(&request));
assert!(
!is_shutdown(&notification),
"a notification named shutdown is not the shutdown request"
);
assert!(!is_shutdown(&other_request));
}
#[test]
fn burst_collects_everything_already_queued_in_arrival_order() {
// `burst` is what turns "one blocking receive" into "the whole
// backlog" — the only place FIFO order could be broken. Nothing here
// touches `Server`, so the check is on the free function alone.
let (sender, receiver) = std::sync::mpsc::channel();
sender
.send(Message::Notification(Notification::new("second".to_string(), Value::Null)))
.expect("send");
sender
.send(Message::Notification(Notification::new("third".to_string(), Value::Null)))
.expect("send");
let first = Message::Notification(Notification::new("first".to_string(), Value::Null));
let batch = burst(&receiver, first);
let methods: Vec<&str> = batch
.iter()
.map(|message| match message {
Message::Notification(notification) => notification.method.as_str(),
_ => "?",
})
.collect();
assert_eq!(
methods,
vec!["first", "second", "third"],
"the blocked-for message first, then the backlog, in order"
);
}
#[test]
fn the_forwarder_stops_at_shutdown_and_leaves_what_follows_for_handle_shutdown() {
// The handoff this whole feature depends on: once the forwarder has
// pushed a `shutdown` request onto the queue, it must not call `recv`
// on `connection.receiver` again — that channel is where
// `handle_shutdown` reads the `exit` that follows. An eager forwarder
// would steal it and strand the handshake for thirty seconds.
let (_tree, session, _uri) = cancelling_session("forwarderstop", ONE_MODULE);
let shutdown_id = RequestId::from(9);
session
.client
.sender
.send(Message::Request(Request::new(
shutdown_id.clone(),
Shutdown::METHOD.to_string(),
Value::Null,
)))
.expect("queue shutdown");
session
.client
.sender
.send(Message::Notification(Notification::new("exit".to_string(), Value::Null)))
.expect("queue exit");
let queue = session.server.queue();
let forwarded =
queue.recv_timeout(std::time::Duration::from_secs(1)).expect("shutdown is forwarded");
assert!(matches!(&forwarded, Message::Request(request) if request.id == shutdown_id));
// Give the forwarder thread every chance to (wrongly) keep reading
// before asserting that it did not.
std::thread::sleep(std::time::Duration::from_millis(50));
assert!(
queue.try_recv().is_err(),
"the forwarder must not forward anything after the shutdown request"
);
// The `exit` is still sitting on the real connection, unread — right
// where `handle_shutdown` looks for it.
let direct = session
.server
.connection
.receiver
.recv_timeout(std::time::Duration::from_secs(1))
.expect("exit is still there for handle_shutdown to read");
assert!(
matches!(&direct, Message::Notification(notification) if notification.method == "exit")
);
}
#[test]
fn a_cancel_naming_a_server_initiated_id_does_not_touch_response_routing() {
// `lucisv-0`, `lucisv-1`, … are ids the server hands out for requests
// it sends *to* the client (`applyEdit`, watcher registration,
// progress `create`) — they come back as a `Message::Response`, a
// different match arm entirely from the `Message::Request`s a burst
// scans for cancellable ids. A client cancelling one by name has
// nothing to reach.
let (_tree, mut session, uri) = cancelling_session("cancelserverid", ONE_MODULE);
let server_id = session.server.send_request("workspace/applyEdit", serde_json::json!({}));
assert_eq!(server_id, RequestId::from("lucisv-0".to_string()));
session.batch(vec![ask(1, &uri), cancel(serde_json::json!("lucisv-0"))]);
assert_eq!(
outcomes(&session),
vec![(RequestId::from(1), None)],
"the client's own request was untouched by a cancel naming a server-initiated id"
);
// The server-initiated request can still be answered normally — the
// cancel did not intercept it.
session.answer(server_id, Value::Null);
}
}
+100 -2
View File
@@ -3011,8 +3011,9 @@ fn indexing_reports_its_progress_over_the_wire() {
"{messages:#?}"
);
// The begin says what it is doing, and offers no cancel button — nothing
// in this server can be cancelled.
// The begin says what it is doing, and offers no cancel button — a rescan
// that has started runs to completion, whatever `$/cancelRequest` can do
// for the requests still queued.
let begin = messages.iter().find(|m| m["params"]["value"]["kind"] == "begin").expect("a begin");
assert_eq!(begin["params"]["value"]["title"], "Indexing Verilog workspace", "{begin:#?}");
assert_eq!(begin["params"]["value"]["cancellable"], false, "{begin:#?}");
@@ -3068,3 +3069,100 @@ fn a_client_that_never_asked_for_progress_is_sent_none_over_the_wire() {
let _ = std::fs::remove_dir_all(&dir);
}
/// The ids the flood cancels — every second request.
fn is_cancelled(id: u32) -> bool {
id % 2 == 1
}
#[test]
fn a_flood_of_requests_and_cancels_is_answered_exactly_once_each() {
// The one test that runs the real `run()` loop, and so the only one that
// exercises the burst drain over a real pipe. The whole session is written
// in a single `write` before a byte is read back, so every request and the
// cancel behind it are in flight together — which is the only situation a
// one-message-at-a-time server can honour a cancel in at all.
//
// **How many get cancelled is not asserted, and cannot be.** Whether a
// cancel reaches the loop in the same burst as its request is a race with
// the transport's own threads, and the spec's answer to losing it is to
// answer the request normally. So this pins what must hold either way —
// one answer per request, never a wrong one — plus the fact that the
// cancellation path does work over the wire. Twenty formatting requests
// over a three-hundred-line buffer is enough work per message that the
// backlog is real: under a twenty-four-way overload the worst observed
// was two in five honoured, never none.
let dir = temp_dir("cancelflood");
let file = dir.join("m.sv");
let source: String = std::iter::once("module flooded;\n".to_string())
.chain((0..300).map(|i| format!("wire w{i};\n")))
.chain(std::iter::once("endmodule\n".to_string()))
.collect();
std::fs::write(&file, &source).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
let mut session = vec![
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(&source).expect("json")
)),
];
for id in 10..30u32 {
session.push(frame(&format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/formatting","params":{{"textDocument":{{"uri":"{uri}"}},"options":{{"tabSize":2,"insertSpaces":true}}}}}}"#
)));
if is_cancelled(id) {
session.push(frame(&format!(
r#"{{"jsonrpc":"2.0","method":"$/cancelRequest","params":{{"id":{id}}}}}"#
)));
}
}
// A cancel for a request this server was never sent. It names nothing in
// any burst, so it is dropped where it is read.
session.push(frame(r#"{"jsonrpc":"2.0","method":"$/cancelRequest","params":{"id":999}}"#));
session.push(frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#));
session.push(frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#));
let messages = talk(&session.concat());
let mut honoured = 0;
for id in 10..30u32 {
let answers: Vec<&serde_json::Value> = messages.iter().filter(|m| m["id"] == id).collect();
assert_eq!(answers.len(), 1, "id {id} was answered exactly once: {messages:#?}");
let answer = answers[0];
if answer.get("error").is_some() {
assert!(is_cancelled(id), "id {id} was never cancelled: {answer:#?}");
assert_eq!(answer["error"]["code"], -32800, "cancelled, not failed: {answer:#?}");
assert!(answer.get("result").is_none(), "an error carries no result: {answer:#?}");
assert!(
answer["error"]["message"].as_str().is_some_and(|m| !m.is_empty()),
"a cancelled response carries a message: {answer:#?}"
);
honoured += 1;
} else {
// Answered for real: the whole buffer, indented.
let edits = answer["result"].as_array().expect("an array of edits");
assert_eq!(edits.len(), 1, "one whole-document edit: {answer:#?}");
assert!(
edits[0]["newText"]
.as_str()
.expect("newText")
.starts_with("module flooded;\n wire w0;\n"),
"id {id} was formatted: {answer:#?}"
);
}
}
assert!(honoured > 0, "the cancellation path runs over the wire: {messages:#?}");
// The shutdown came through the same flood and was still honoured —
// `talk` asserts the process then exited cleanly.
let shutdown = messages.iter().find(|m| m["id"] == 9).expect("a shutdown response");
assert!(shutdown.get("error").is_none(), "shutdown succeeded: {shutdown:#?}");
let _ = std::fs::remove_dir_all(&dir);
}
+533
View File
@@ -0,0 +1,533 @@
# cancel-request
## Goal
`$/cancelRequest` is the client's way of saying "drop that one, the user has
moved on" — sent constantly by real editors, which cancel the completion,
hover and inlay-hint requests of the previous keystroke on every new one.
Until now the notification fell through `Server::notification`'s `_ => {}` arm
and the request was computed and answered anyway. This round answers a
cancelled request with the protocol's own `RequestCancelled` (-32800) instead
of computing it, whenever the cancel reaches the loop in time — which, on a
single-threaded server, means *while the request is still queued*. The gain is
not correctness (an ignored cancel is legal) but work not done: on a slow
rescan or a large-file format, the queue behind the busy handler is exactly
where a stale completion request sits, and answering it costs nothing (TODO.md
§9b, the last item of that section).
## What "in time" can mean on a one-message-at-a-time loop
Everything about this feature follows from one fact: **the client sends the
request and its cancel down one ordered channel**, and the server handles one
message at a time. Read strictly one message per iteration, a cancel is always
too late — by the time `C(R)` is dequeued, `R` was dequeued, computed and
answered an iteration ago. Cancellation only becomes reachable when the loop
looks at *more than one message at a time*: while a handler runs, the client
keeps sending, so the backlog waiting behind it can hold `[R1, C(R1), R2]` —
and R1 can be answered `RequestCancelled` for free.
So `run()` now works in bursts:
1. block for the next message, as before;
2. take everything already queued behind it, without blocking, into one FIFO
(the blocked-for message first);
3. scan that whole burst for `$/cancelRequest` notifications and collect the
ids that name a request **in the same burst**;
4. handle the burst strictly in arrival order — a cancelled request answered
`RequestCancelled` without dispatch, every other message exactly as before.
Step 3 is what keeps the cancelled set from being state: it is built per burst
and dropped with it.
### The transport does not queue — so we do
The first attempt used `connection.receiver.try_recv()` for step 2 and
cancelled **nothing** over a real pipe. The reason is worth writing down,
because it is invisible from the API:
> `lsp-server` 0.10's stdio transport wires its reader, writer and dropper
> threads with **`crossbeam_channel::bounded(0)`** — rendezvous channels with
> no capacity at all (`stdio.rs`). Its reader thread parks *inside* `send`
> holding one message until the loop takes it. A client's backlog therefore
> never sits on `connection.receiver`: it sits in the OS pipe, one message
> deep from where we stand, and `try_recv` right after a `recv` loses a
> microsecond-scale race with the reader thread essentially every time.
`Server::queue()` fixes this with the smallest thing that can: one forwarder
thread that blocks on `connection.receiver` and pushes onto an unbounded
`std::sync::mpsc` queue that `run()` owns. The backlog then accumulates where
we can see it, and step 2 is a plain `try_recv` loop. The thread touches no
server state, moves messages and nothing else, and is std-only — no new
dependency.
The forwarder **stops at the `shutdown` request and never reads past it**.
`Connection::handle_shutdown` answers the request and then reads the `exit`
notification off the *connection* itself; a forwarder that kept going would
take that `exit` first, and `handle_shutdown` would block for its full
thirty-second timeout and then return a protocol error. Stopping there also
means nothing after a shutdown is ever queued, which is exactly the protocol's
own rule.
## Assumptions
- **Cancellation is best-effort, and the spec says so.** LSP allows a server
to ignore a cancel it cannot honour; the only hard requirement is that every
request gets exactly one response. Both are held here: a cancel that misses
its window leaves the request answered normally.
- **A cancel arriving in a *later* burst than its request is dropped.** By
then the request has been answered — there is nothing left to cancel, and
remembering the id would be a set that grows for the life of the session.
This is the single rule that keeps this feature stateless.
- **A cancel in the same burst but dequeued *before* its request still
cancels it.** The burst is scanned as a whole before any of it runs, so
ordering within the burst does not matter. (A real client never sends the
cancel first; a transport is free to make it look that way.)
- **A cancel for a request the server never received is dropped** where it is
read, for the same reason.
- **Cancelling one request twice is harmless.** The id is removed from the
cancelled set as it is used, so a second cancel finds nothing — and it could
not touch a later request even if ids were reused, because the set never
outlives its burst.
- **`shutdown` is never cancellable.** `handle_shutdown` runs before the
cancelled set is consulted, so a cancel naming the shutdown id cannot stop
the server from shutting down. The spec's "a server should still answer a
cancelled request" reading is the safe one here: a client that cannot shut
its server down leaks a process.
- **Notifications are never cancelled.** They carry no id and get no
response; `$/cancelRequest` names request ids only. A `didChange` queued
ahead of a cancelled request is still applied — the state a *later* request
is answered against must not depend on which requests were dropped.
- **Order inside a burst is the invariant, not an implementation detail.**
A `didChange` the client sent before a completion request must be in effect
when that completion is answered, exactly as it would be one message at a
time. Pinned by
`a_notification_queued_ahead_of_a_request_is_applied_before_it_is_answered`.
- **Both id forms are read.** `CancelParams.id` is
`NumberOrString`; a numeric id becomes `RequestId::from(i32)` and a string
id `RequestId::from(String)`. The string `"8"` is not the number `8` —
`RequestId` keeps them apart and so does the cancel, which is the only
behaviour that can be right when a client uses both forms.
- **A cancel whose params do not parse is dropped**, on the same reasoning as
every other malformed notification: there is no id to act on and no id to
answer on.
- **The cancelled response carries a message.** `-32800` plus
`"lucisv: request cancelled by the client"`. Clients do not show it — the
code is what they read — but a log with the text in it is easier to read
than a log with a number in it.
- **Nothing already *running* is cancelled.** There is one thread; a format,
a rescan or a rename that has started runs to completion. The work-done
progress bar still advertises `cancellable: false`, which stays true.
- **The queue is unbounded.** Backpressure on the pipe used to be the reader
thread's rendezvous; now a burst is buffered in memory instead. For an LSP
client that is bounded by what an editor sends between two of our handler
calls — kilobytes. A client that floods a server faster than it can read
would grow this queue, and would equally have grown the pipe before.
## Handshakes
### `lucisv_server::server` (this feature's own module)
- `Server::run` no longer receives-and-dispatches inline. It builds the queue,
blocks on it, and hands each burst to `process_batch`. Behaviour for a
client that never cancels is identical, message for message.
- **New private items:** `Server::queue()` (the forwarder),
`Server::process_batch(Vec<Message>) -> Result<bool, …>` (the burst
handler; `true` means the client shut us down), and the free functions
`burst`, `is_shutdown`, `cancelled_in`, `cancelled_id`, `cancelled_response`.
- `Server::request`, `Server::notification` and `Server::response` are
**unchanged**. `$/cancelRequest` never reaches `notification()`; it is
consumed in the burst handler, which is the only place that can act on one.
- No field was added to `Server`. Cancellation state lives for the length of
one burst and no longer.
### `lsp-server`
- Consumed, not changed: `Connection.receiver` is now `clone()`d (crossbeam
receivers are `Clone`), and `handle_shutdown` is called exactly where it was
— the forwarder's stop rule is what keeps its `exit` read working.
- The rendezvous-channel finding above is a property of version `=0.10.0`,
which the workspace pins. A future bump should re-read `stdio.rs`: if the
transport ever queues, `Server::queue` becomes redundant rather than wrong.
### Every other crate, and `editors/vscode`
**Untouched.** No engine crate knows this happened, and no client capability
gates it — `$/cancelRequest` is unconditional in the protocol, advertised by
nobody and sent by everybody. `smoke.js` passes unchanged (run as a gate).
## Status / TODO
- [x] `run()` restructured into blocking receive → burst drain → burst handler
- [x] Forwarder thread so the backlog is observable at all (the rendezvous
finding), stopping at `shutdown` so `handle_shutdown` keeps its `exit`
- [x] Cancelled ids collected per burst, matched against that burst's own
requests, dropped otherwise
- [x] Cancelled requests answered `-32800` without dispatch; the cancels
themselves consumed
- [x] `shutdown` honoured before any cancel is consulted
- [x] Arrival order preserved across the whole burst (notifications included)
- [x] Numeric and string cancel ids; malformed cancels dropped
- [x] Tests: 10 unit in `server.rs` (through the `Session` harness, driving
the real `process_batch`), 1 e2e over the wire
- [x] TODO.md §9b checkbox; loop description in
`docs/features/lucisv-server/README.md`
- [ ] **Not done, deliberately:** no cancellation of work in flight. That
needs a worker pool and cancellation tokens threaded through the engine
— TODO.md §6's explicit non-goal for as long as per-file recompute stays
in the millisecond range.
- [ ] **Not done, deliberately:** no `ContentModified` (-32801) for requests
invalidated by a `didChange` queued behind them. It is the neighbouring
idea and a real option now that the loop can see a burst, but the spec
warns that an answer computed against slightly older text is usually
still useful — and the client, not the server, is the one that knows.
Filed here, not built.
## Work log
### 2026-08-26 — dev agent (§9b, `$/cancelRequest`)
- Read `CLAUDE.md`, `docs/features/lucisv-server/README.md`, TODO.md §9b and
the whole of `server.rs`'s loop before touching anything.
- **Verified the lead's design against the code, and found one thing that
invalidated its second step.** The plan said to drain `connection.receiver`
non-blockingly with `try_iter`/`try_recv`. Written that way, the e2e flood
cancelled **zero** of five requests, reproducibly. `lsp-server` 0.10's
`stdio.rs` uses `bounded(0)` rendezvous channels throughout: there is no
queue on that receiver to drain, ever. The rest of the design — burst FIFO,
batch-wide cancel scan, drop-if-not-in-batch, order preserved, shutdown
never cancellable — is unchanged and implemented as written.
- **Fix: one forwarder thread** (`Server::queue`) onto a `std::sync::mpsc`
queue, so the backlog accumulates somewhere observable. Std-only, no new
dependency, no shared state, ~12 lines. Considered and rejected: a timed
drain window (`recv_timeout(1ms)`), which would tax *every* message with a
millisecond of latency and still be a race; and handling shutdown ourselves
to free the forwarder, which would duplicate `handle_shutdown`'s protocol
for no gain.
- **The forwarder's stop-at-shutdown rule was found by reading
`handle_shutdown`, not by a failing test**: it reads `exit` off the
connection itself, so an eager forwarder would have stolen it and turned
every shutdown into a 30-second timeout followed by a protocol error. The
rule is asserted by `a_shutdown_is_honoured_however_it_is_cancelled` and by
the e2e session, which shuts down through the same flood.
- Tests: 10 unit tests in `server.rs`, driving the real `process_batch`
through a new `Session::batch` helper (the harness otherwise bypasses the
loop entirely), plus `Session::answers()` for reading responses off the
client end. One e2e test running the real binary and the real `run()`.
- **The e2e test asserts what is deterministic, and says why.** Three
iterations were needed to get there: with cheap requests, *how many* cancels
land in the same burst as their request is a scheduling race, and demanding
all five failed roughly one full-suite run in four (the suite runs 38
server processes in parallel). The final shape floods twenty
`textDocument/formatting` requests over a 300-line buffer — enough work per
message that the forwarder is never starved — and asserts the properties
that must hold on any schedule: exactly one response per request, `-32800`
only ever on an id the client actually cancelled, a correct formatted answer
on every other id, at least one honoured cancel (the wire path works), and
a clean shutdown. Measured under a deliberate 24-way overload: worst case
two of five honoured, never zero.
- Also corrected two now-stale comments about cancellation being absent
entirely — the module header of `server.rs`, `begin_indexing`'s note on
`cancellable: false`, and the matching line in the progress e2e test. The
bar's `false` stays correct: what has *started* still runs to completion.
- Gates, all clean: `cargo fmt --all -- --check`, `cargo clippy --all-targets`
(no warnings), `cargo test --workspace` (34 suites green; `lucisv_server`
702 unit + 38 e2e), `cargo build && node editors/vscode/smoke.js
target/debug/lucisv-server` → OK. The e2e suite was re-run ten consecutive
times looking for flake: ten passes.
## QA log
### 2026-08-26 — QA agent (§9b, `$/cancelRequest`)
**Verdict: committable as-is.** No corruption, no protocol violation, no
reproducible flake found. Four gaps in test coverage for the highest-risk
part of the change (the forwarder thread) were found and closed directly;
one theoretical (not reproduced) flake risk in the e2e flood is recorded
below with a reasoned trade-off, not "fixed," because the fixes available
would weaken the property the test exists to prove.
**Gates.** `cargo fmt --all -- --check` clean. `cargo clippy --all-targets`
clean, no warnings. `cargo test --workspace`: every suite green, including
`lucisv_server` at 706 unit (was 702 pre-QA; +4 added below) + 38 e2e.
`cargo build && node editors/vscode/smoke.js target/debug/lucisv-server` →
OK. `cargo test -p lucisv_server --test e2e` run five more times standalone,
before the QA-added tests and five more times after: **10/10 green**, no
flake observed in the flood test or anywhere else in the suite.
**1. Forwarder shutdown hand-off — verified clean, by reading
`lsp-server` 0.10's actual source, not the dev's summary.**
- Read `~/.cargo/registry/.../lsp-server-0.10.0/src/stdio.rs`,
`src/lib.rs` (`Connection::handle_shutdown`, `Connection::memory`) and
`src/msg.rs` (`Request::is_shutdown`, `Notification::is_exit`,
`Response`'s `#[serde(flatten)]` encoding). Confirms the README's claim:
the stdio reader thread parks inside a `bounded(0)` `send` until taken,
so a client's backlog really does live in the OS pipe and not on
`connection.receiver`.
- (a) **Method-name detection, and the notification case.** `is_shutdown`
(`crates/lucisv_server/src/server.rs:1119`) matches
`Message::Request { method == "shutdown" }` only — the same test
`lsp-server`'s own `Request::is_shutdown` (msg.rs:233) uses. A
**notification** shaped like `{"method":"shutdown"}` fails the match
(wrong enum variant), so the forwarder does not stop for it; it is
forwarded like any other message and falls through `notification()`'s
`_ => {}` arm, doing nothing. This was asserted by nothing before QA —
added `is_shutdown_matches_only_the_shutdown_request_never_a_notification_of_the_same_name`
(server.rs:3574). A malformed shutdown-*request* (e.g. non-null params)
is not a distinct case: neither `is_shutdown` nor `handle_shutdown`
parses params, only the method name, so there is nothing to be
malformed.
- (b) **The stolen-message / deadlock window.** Traced the forwarder
(`Server::queue`, server.rs:209-233): it checks `is_shutdown` on the
message **after** receiving it but **before** issuing its next `recv()`,
and breaks its loop without calling `recv()` again when that check is
true. `handle_shutdown` (lsp-server lib.rs:348) is only reached by
`process_batch` for a request already sitting in the batch Vec — i.e.
after the forwarder that produced it has already returned from its last
`sender.send`. Because the forwarder's own break happens strictly before
any further receive, there is no window where both the forwarder and
`handle_shutdown` are calling `recv`/`recv_timeout` on the same
crossbeam channel at once — no steal, no deadlock. Added
`the_forwarder_stops_at_shutdown_and_leaves_what_follows_for_handle_shutdown`
(server.rs:3632), which sends a real shutdown request + exit notification
through a `Connection::memory()` pair, calls the real `Server::queue()`,
and asserts (i) the shutdown is the last thing the forwarder ever
forwards even after 50ms of extra opportunity to misbehave, and (ii) the
`exit` is still sitting, unread, directly on `connection.receiver` —
exactly where `handle_shutdown` looks for it. This is the one test in
the whole suite that exercises the real `queue()` method without going
through a subprocess.
- (c) **Messages already forwarded ahead of a shutdown in the same
batch.** Because the forwarder always stops immediately after
forwarding the message it detects as shutdown, shutdown is provably
always the *last* message that forwarder instance ever produces — there
is no way for a message to be forwarded *after* shutdown by the same
producer, and there is only ever one producer (next point). So the
scenario "a request forwarded after shutdown gets silently dropped" is
not reachable through this code path. Nothing found here; the design
note in the feature README (lines 63-69) undersells this a little by
only mentioning the *thirty-second timeout* consequence of an eager
forwarder — the actual structural guarantee (shutdown is always last)
is worth knowing but the doc isn't wrong, just less complete than it
could be. Not fixed (doc-only, not a code finding, and rewriting
someone else's README section is not QA's job per CLAUDE.md).
**2. Message loss/reordering — verified clean.**
- Exactly one producer: `Server::queue` is called exactly once, from
`Server::run` (server.rs:185), which is itself called exactly once, from
`main.rs:76`. No respawn path exists.
- Single channel used throughout: `run`'s blocking head-of-burst read and
`burst`'s non-blocking drain (server.rs:1126) both operate on the same
`std::sync::mpsc::Receiver` returned by `queue()` — never a mix of the
mpsc and `connection.receiver` on the consuming side. (`connection.receiver`
itself is only ever touched by the forwarder's `source` handle and by
`handle_shutdown`, never by `run`/`burst`/`process_batch`.)
- Exactly-once processing: `burst` pushes the blocking-received `first`
plus everything `try_recv` drains, with no filtering or dedup step in
between — the FIFO in equals the FIFO out. Added
`burst_collects_everything_already_queued_in_arrival_order`
(server.rs:3602) directly against a fresh
`std::sync::mpsc` channel (no `Server` involved), pinning arrival order
for `[first, second, third]`. Previously `burst` had zero direct test
coverage — every existing cancel test drives `process_batch` through
`Session::batch`, bypassing `burst` entirely, so this was a real gap in
a change the assignment calls "the highest-risk this repo's server has
taken."
**3. `exit` handling / zombie-thread check — verified clean.**
- `talk()` (e2e.rs:66-79) and the progress-e2e session's own `finish()`
(e2e.rs:1978-1985) both call `child.wait()` and assert
`status.success()` — a hung forwarder or a process that doesn't
terminate would hang or fail these, and none did across 10 e2e runs.
This is a real check, not a rubber stamp: `child.wait()` blocks until
the OS reports the process gone, so a genuinely undead forwarder thread
(blocked on stdin, holding the process open) would show up as a test
timeout, not a silent pass.
- The forwarder thread is detached (`let _ = ... .spawn(...)`), never
joined. This is fine for process exit: after `shutdown`+`exit`, the
forwarder has *already* stopped itself (point 1b) well before `run()`
returns, so by the time `main()` returns there is no thread left
blocked on I/O that could hold the process open. In the one edge case
where a client disconnects without ever sending `shutdown` (broken
pipe), the forwarder's own `source.recv()` errors, it drops its `sender`
and exits, closing the mpsc and unblocking `run()`'s own `recv()` the
same way `self.connection.receiver.recv()` used to unblock pre-diff —
behaviorally identical to the old direct-receive loop for that case.
Not a new finding; equivalent to prior behavior.
**4. Cancellation semantics matrix — re-verified independently, assertions
read (not just names), all pass; one gap closed.**
Read every assertion, not just the test name, for: same-burst
cancel-after (`a_request_cancelled_in_the_same_burst_is_answered_cancelled`),
cancel-before (`a_cancel_dequeued_before_its_request_still_cancels_it`),
partial-batch cancel (`a_cancel_names_one_request_and_leaves_the_rest_of_the_burst_alone`),
orphan/late drop with the id-reuse proof
(`a_cancel_for_a_request_that_is_not_in_the_burst_is_dropped_on_the_spot`),
notification-ordering
(`a_notification_queued_ahead_of_a_request_is_applied_before_it_is_answered`),
notifications-uncancellable (`a_cancel_never_cancels_a_notification`),
shutdown-uncancellable (`a_shutdown_is_honoured_however_it_is_cancelled`),
double cancel (`cancelling_one_request_twice_answers_it_once`), int-vs-string
ids including the `"8"` vs `8` case (`a_cancel_id_may_be_a_number_or_a_string`),
and malformed params (`a_malformed_cancel_is_dropped_rather_than_guessed_at`).
Every one asserts what its name claims; none was a false-positive
(no-op) test. All pass, independently re-run.
**Gap found and closed:** no test covered a cancel naming a
**server-initiated** id (the `lucisv-0`/`lucisv-index-N`/`lucisv-watched-files-N`
namespace from `Server::send_request`, server.rs:949). Traced it: `cancelled_in`
(server.rs:1141) only ever matches a cancel against ids of `Message::Request`
entries *received in the same batch* — a server-initiated id only ever
appears on the wire as a `Message::Response` coming back from the client,
a different match arm in `process_batch` entirely, never consulted against
`cancelled`. So interference is not possible by construction. Added
`a_cancel_naming_a_server_initiated_id_does_not_touch_response_routing`
(server.rs:3682) to pin this rather than leave it as an inference:
it calls the real `send_request`, gets back `lucisv-0`, sends a cancel
naming it alongside an ordinary client request, asserts the client request
is untouched, and then answers the server-initiated request successfully
to prove routing was never disturbed.
**5. `-32800` on the wire — verified, one assertion added.**
`cancelled_response` (server.rs:1171) uses
`lsp_server::ErrorCode::RequestCanceled as i32`, which is `-32800` in
`msg.rs:128` — matches spec. `Response`'s `#[serde(flatten, with =
"ResponseResult")]` (lsp-server msg.rs:87-98) serializes to exactly one of
`result`/`error`, never both — confirmed by reading the encoding, and by
the e2e flood's existing `answer.get("result").is_none()` on a real wire
response (e2e.rs:3141). Id-type preservation (int in → int in response) is
implicitly covered by the flood test's own matching: it filters
`messages.iter().filter(|m| m["id"] == id)` against a Rust `u32`, which
would find nothing if the id had round-tripped as a string, and the test
asserts exactly one match per id. **Gap found and closed:** nothing
asserted that the error carried a non-empty `message` string, only that
`code` was right and `result` was absent. Added that assertion in-line at
e2e.rs (next to the `result`-absence check in
`a_flood_of_requests_and_cancels_is_answered_exactly_once_each`).
**6. The e2e flood's honesty — one theoretical, unreproduced flake risk,
documented rather than "fixed."**
Read the whole test (e2e.rs:3079-3168). The `honoured > 0` assertion
(e2e.rs:3160) is the one the
task flagged as suspicious, correctly. Reasoning:
- The forwarder thread and the main loop's request handling run
concurrently on real OS threads. While the main thread is inside a
synchronous `self.request(...)` call (formatting), the forwarder can
keep draining the reader thread's rendezvous handoffs into the mpsc
queue in parallel — this concurrency, not any timer, is what makes a
multi-message burst likely.
- It is **not mathematically impossible** for every burst to end up size
1: a scheduler that always preempts the forwarder thread and lets the
main thread fully drain-and-reblock before the next message is
forwarded would produce zero cancellations, every time, for any finite
request count. No such interleaving was produced in 10 standalone e2e
runs plus one full `cargo test --workspace` run (which itself runs the
e2e binary), so it is not a *practical* risk today, but "never observed"
is exactly the "≠ impossible" the task named.
- **Why not fixed:** the two available code fixes both make the test
worse. Relaxing `honoured > 0` to `honoured >= 0` (i.e., deleting the
assertion) would stop the test from ever proving the cancellation path
works over the real wire at all — the one thing this e2e test exists to
check per its own doc comment. Adding a synchronization point (e.g. a
test-only delay hook) to force a burst would add production-code
surface *purely for a test's benefit*, which the "simplicity first"
section of `CLAUDE.md` weighs against, for a risk that is theoretical
and has a fallback: a failure here is a flake in one non-gating-by-flake
test, not a correctness bug (the request would still be answered
correctly once instead of cancelled — see point 4's stateless-drop
behavior — so no invariant breaks, only the "never zero" assertion
would).
- **Recommendation:** accept the residual risk as-is. If it is ever
observed to flake in CI, the fix is almost certainly to widen the
buffer/request count further (the dev already tuned this once, from a
~1-in-4 flake rate with cheap requests down to zero observed in 10+ runs
with 300 lines / 20 requests) rather than to touch the assertion itself.
**7. CLAUDE.md compliance — verified clean.**
- No bare `std::thread::spawn` (which panics on OS resource exhaustion).
The forwarder uses `std::thread::Builder::new().spawn(...)`
(server.rs:215), which returns `io::Result`, and the error is
deliberately discarded with `let _ =` plus a comment explaining the
fallback (the mpsc sender is dropped, so `run()`'s `recv()` fails and
the loop ends cleanly instead of hanging) — no panic path introduced.
This is in `main`-path server setup, which CLAUDE.md's "Tests and
`main.rs` argument handling may use them" carve-out does not literally
name, but the *effect* is a `Result`-returning call whose error is
handled without panicking or unwrapping — no rule is broken; there is
no `unwrap`/`expect`/`panic!` in this path at all.
- All `.expect(...)`/`.unwrap()` calls introduced by the diff (checked
with `git diff | grep`) are inside `mod tests` (`Session::batch`,
`symbol_names`, `outcomes`, and the shutdown test's `sender.send(...)`)
— allowed.
- New free functions and the new `Server` methods all carry one-line-plus
doc comments explaining what/why, consistent with the surrounding file's
density; none of the new items are `pub`, so the strict "public items"
rule doesn't even apply, but the dev exceeded it anyway.
- `docs/features/cancel-request/README.md`: each of the seven required
sections (Goal, Assumptions, Handshakes, Status/TODO, Work log, QA log,
Review) appears **exactly once** (checked with `grep -n "^## "`); one
extra explanatory section between Goal and Assumptions is additional,
not a duplicate, and the template doesn't forbid it.
- `TODO.md`: the §9b item's original text
("**`$/cancelRequest`** — the loop handles requests sequentially and
ignores cancellation; at minimum answer already-cancelled queued
requests with `RequestCancelled`.") is byte-for-byte intact; only the
checkbox flipped and a `→`-prefixed summary line was appended below it,
which is the same pattern used by the 9 other completed items already
in the file (`grep -c` confirms 10 occurrences total including this
one) — not a one-off deviation.
- `docs/features/lucisv-server/README.md` was also touched by this
change. That file is the umbrella index every feature registers itself
in (the method-dispatch table and the Status/TODO checklist both list
every other feature the same way), so this is the expected cross-file
touch the Handshakes section describes, not scope creep.
**Tests added this round (4 unit + 1 e2e assertion, all in the files
already under review, no new files):**
`is_shutdown_matches_only_the_shutdown_request_never_a_notification_of_the_same_name`,
`burst_collects_everything_already_queued_in_arrival_order`,
`the_forwarder_stops_at_shutdown_and_leaves_what_follows_for_handle_shutdown`,
`a_cancel_naming_a_server_initiated_id_does_not_touch_response_routing`
(all in `crates/lucisv_server/src/server.rs`), plus a `message`-field
assertion added to
`a_flood_of_requests_and_cancels_is_answered_exactly_once_each` in
`crates/lucisv_server/tests/e2e.rs`. `lucisv_server` unit count moved from
702 to 706; e2e stayed at 38 (one test grew an assertion, none added).
**Fixes made:** none beyond the test additions above — no corruption, no
mishandled message, no dropped request found anywhere in the diff.
## Review
### 2026-08-26 — lead
Reviewed the diff, the work log and the QA log; re-ran all gates myself
plus two extra e2e passes (flood test green in every run I and QA made —
twelve consecutive between us), clean. The dev's deviation from my brief
was the right kind: my burst-drain design assumed a queue that lsp-server's
rendezvous channels do not provide, the dev proved that over a real pipe
(0/5 honoured) before changing anything, and the forwarder it added is
the minimal honest fix — one thread, no shared state, stopping at
shutdown for a reason it can cite from lsp-server's own source. QA then
re-derived the shutdown hand-off from the vendored code rather than the
work log, which is exactly the adversarial re-check this workflow exists
for, and closed the four real gaps (the shutdown-shaped notification,
bare `burst` coverage, the forwarder hand-off under a real Connection,
and the server-id-namespace cancel).
The stateless cancelled-set design — a cancel matters only beside its
request in one burst, everything else dropped on sight — is the reason
this feature cannot leak or misfire across sessions, and shutdown
sitting before the cancel check closes the one hole a hostile client
could poke. On the flood test's `honoured > 0` assertion: QA is right
that a pathological scheduler could in principle defeat it and right not
to weaken it; the property is the point of the test, the risk is
unreproduced in twelve runs, and if CI ever trips it the QA log already
contains the analysis. This completes §9b. Accepted as shipped.
+28 -4
View File
@@ -44,6 +44,7 @@ looks like language knowledge in here is a bug or a `Handshake` request.
| `workspace/symbol` | `WorkspaceIndex::workspace_symbols` | Capped at 256 hits |
| `workspace/didChangeWatchedFiles` | `Workspace::rebuild_index` | Registered dynamically after the handshake, for a client that advertised it. One rebuild per *notification*, however many files it names. See `docs/features/file-watching/README.md` |
| `window/workDoneProgress/create` + `$/progress` | — | Server-**initiated**: one indeterminate bar per workspace rescan, titled "Indexing Verilog workspace", ending with the indexed file count. Only for a client that advertised `window.workDoneProgress`. See `docs/features/work-done-progress/README.md` |
| `$/cancelRequest` | — | Best-effort, and honoured exactly when the cancel reaches the loop in the same burst as the request it names: that request is answered `RequestCancelled` (-32800) instead of computed. A cancel for anything else is dropped where it is read, `shutdown` is never cancellable, and nothing already running is interrupted. See `docs/features/cancel-request/README.md` |
Deferred, deliberately, and named in Status/TODO below: ~~range formatting
(waits on TODO.md §2 `--lines`)~~ **delivered by range-formatting (round 18):
@@ -189,10 +190,29 @@ every character boundary of a document mixing all of those.
## State and staleness
Single-threaded request loop — `lsp-server`'s model. Two I/O threads (its
own) read and write stdio; this crate's loop receives one message, handles it
to completion, and sends the response before looking at the next. No shared
mutable state, no locks, no cancellation. Verilog files are small and every
handler is milliseconds; the complexity of a worker pool buys nothing yet.
own) read and write stdio; this crate's loop handles one message to completion,
and sends the response before looking at the next. No shared mutable state, no
locks, and nothing already running is ever interrupted. Verilog files are small
and every handler is milliseconds; the complexity of a worker pool buys nothing
yet.
**Since 2026-08-26 the loop reads in bursts** rather than strictly one message
at a time: it blocks for the next message, takes everything already queued
behind it without blocking, and then handles that whole burst **in arrival
order** — a `didChange` ahead of a completion is applied before the completion
is answered, exactly as before. The one thing the burst adds is
`$/cancelRequest`: a request the same burst also carries a cancel for is
answered `RequestCancelled` (-32800) instead of being computed, which is the
only moment a one-thread server can honour a cancel at all. A cancel that
names no request in its burst is dropped where it is read (the request was
answered in an earlier burst, or never existed), so cancellation costs no
state; `shutdown` is handled before any cancel is consulted and so can never
be cancelled. Because `lsp-server`'s transport uses zero-capacity rendezvous
channels — a client's backlog sits in the OS pipe, not on
`connection.receiver` — the loop first forwards incoming messages onto an
unbounded queue of its own on one small thread, which stops at `shutdown` so
`handle_shutdown` keeps its own read of the `exit` that follows. Rules,
reasoning and the measurements: `docs/features/cancel-request/README.md`.
**Two layers, invalidated by different events** — exactly the split
`docs/features/workspace-index/README.md` designed for:
@@ -538,6 +558,10 @@ list to `vlog_parser::KEYWORDS`. Rationale and inventory:
`docs/features/hierarchy/README.md`.
- [x] Single-step macro expansion on a hover card (`src/expand.rs`, M14) —
`docs/features/macro-expansion/README.md`.
- [x] `$/cancelRequest` — delivered by **cancel-request** (2026-08-26,
completing TODO.md §9b): the loop reads in bursts and answers a queued
request whose cancel is in the same burst with `RequestCancelled`,
order across the burst unchanged. `docs/features/cancel-request/README.md`.
- [ ] **Not done:** editor packaging (the VS Code extension and the
`lspconfig` snippet are their own TODO.md §6 item).