Files
lucisv/crates/lucisv_server/src/server/batch.rs
T
Guoliang ChenandClaude Mythos 5.2 934d472af2
ci / checks (push) Successful in 54s
ci / corpus (push) Successful in 15s
release / build-and-publish (push) Successful in 5m28s
Release 0.65.8: Find References next to a name, edits kept in order, a startup that could take minutes
TODO §71.7. Three server bugs, all older than this series.

- A caret just past an identifier's last letter resolved the NEXT character
  (spans are end-exclusive): references, definition, hover and highlight came
  back empty where VS Code considers the caret on the word — the owner's
  'not found, then works after clicking back'. lucisv_server/src/caret.rs;
  nine position-to-symbol requests use it through Server::symbol_offset; the
  References view opens a row with the caret at the name's start.
- process_batch held requests during a scan but applied notifications at
  once, so a didChange could overtake an older one still queued; with
  incremental sync that corrupted the server's copy of the buffer until the
  file was reopened. Rule now: no notification overtakes an older unapplied
  notification (Server::must_hold, the 'behind' count for the burst a scan
  is nested in). Cancels wait whenever anything is held; responses never.
- answer_what_is_waiting acted on a didOpen it had queued but not applied,
  re-holding the same batch at every file of the startup scan (~300-400 s on
  OpenTitan). Scan state now changes only where a message is applied; a held
  batch is handed back at most once per applied didOpen.

An attempt to also drop excluded buffers from the index on close cost 190 ms
per open of an outside file and was reverted after QA measured it.

Dev (two rounds), QA (two rounds, own ordering driver: 9 118 bursts, no
wrong text) and lead review: docs/features/scan-ordering/README.md. TODO.md
files what stays open.

Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots); notes in CHANGELOG.md (## 0.65.8) and
editors/vscode/CHANGELOG.md.

Gates: tools/gates.sh PASS on this tree including cross;
lucisv_server 2030/0.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-19 11:47:14 -08:00

176 lines
8.4 KiB
Rust

//! Reading a burst of messages before any of it is served.
//!
//! `lsp-server` hands messages over a rendezvous channel, one at a time; the
//! forwarder here moves them onto a queue of our own so that "everything the
//! client has already sent" is a question with an answer. The rest of the
//! file reads a burst without handling anything in it: which requests it
//! cancels and — for a `didOpen` — whether the index scope grew, stayed, or
//! has to be rebuilt. (Which files a burst *opens* is not read here any more:
//! a `didOpen` changes a scan's order when it is applied, never because a
//! batch carries it — `docs/features/scan-ordering/README.md`.) The loop in `mod.rs` and the
//! mid-scan drain in `index.rs` both read bursts through here, which is why
//! this is its own file rather than part of either.
use std::collections::HashSet;
use lsp_server::{Connection, Message, RequestId, Response};
use lsp_types::notification::{Cancel, Notification as _};
use lsp_types::request::{Request as _, Shutdown};
use lsp_types::{CancelParams, NumberOrString};
/// 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.
pub(super) fn is_shutdown(message: &Message) -> bool {
matches!(message, Message::Request(request) if request.method == Shutdown::METHOD)
}
/// 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
/// [`burst`] — and of the drain a scan does between two of its files.
///
/// 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 — and it never parses, which is why it is the one
/// thread the server spawns without `vlog_parser::PARSE_STACK_SIZE`
/// (`docs/features/recursion-limit`).
pub(super) fn forward(
connection: &Connection,
) -> (std::sync::mpsc::Sender<Message>, std::sync::mpsc::Receiver<Message>) {
let (sender, receiver) = std::sync::mpsc::channel();
let source = connection.receiver.clone();
let ours = sender.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;
}
}
});
(ours, receiver)
}
/// `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.
pub(super) 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.
pub(super) 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.
pub(super) 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.
pub(super) fn cancelled_response(id: RequestId) -> Response {
Response::new_err(
id,
lsp_server::ErrorCode::RequestCanceled as i32,
"lucisv: request cancelled by the client".to_string(),
)
}
/// What a `didOpen` did to the index scope, and therefore which of the three
/// answers it is owed.
#[derive(Debug, PartialEq, Eq)]
pub(super) enum Widen {
/// The scope did not move: the file is in a folder already covered, or the
/// rung in force is one an open buffer cannot widen (a filelist, or the
/// whole-workspace walk). Publish and index nothing.
Nothing,
/// Folders were added and nothing else changed — the cheap path, indexing
/// only what the added folders bring in
/// ([`Server::reindex_widened`](super::Server::reindex_widened)).
Added(Vec<std::path::PathBuf>),
/// Anything else. The whole rescan, which is always a correct answer.
Whole,
}
/// Which of the three [`Widen`] answers a move from `before` to `after` is.
///
/// **The chooser, and it is deliberately narrow**: only a scope that grew and
/// lost nothing takes the incremental path, because that is the only shape
/// whose result is the whole rescan's by construction — a directory that left
/// the scope can take files out of the index, and working out *which* files is
/// the walk the widen exists not to do. Nothing in the server takes a directory
/// out of the folder scope today (`opened_dirs` only grows, and a `didClose`
/// costs no rescan at all), so the third arm is a rule kept rather than a case
/// reached; a future shrink gets a correct answer instead of a subtle one.
///
/// **A directory that subsumes one already in scope is an add** (2026-08-29,
/// `docs/features/index-scope/README.md`). At `scopeDepth: 2` the second file a
/// user opens routinely raises to a *parent* of the directory the first one
/// raised to — opentitan's `hw/ip/aes` then `hw/ip`. That is still a pure add
/// here, because every opened directory is raised on its own and the list keeps
/// them all: the contained directory is in `after` beside the containing one,
/// and nothing was lost. The overlap is not re-read either, because
/// `Workspace::begin_widen`'s work list is diffed **by file against what the
/// index holds** rather than by folder against the old walk.
///
/// Both lists come from `Workspace::scope_dirs`, which sorts and dedups, so
/// equality is set equality and `contains` is over a handful of directories.
pub(super) fn widen_of(before: &[std::path::PathBuf], after: &[std::path::PathBuf]) -> Widen {
if before == after {
return Widen::Nothing;
}
if before.iter().any(|dir| !after.contains(dir)) {
return Widen::Whole;
}
Widen::Added(after.iter().filter(|dir| !before.contains(dir)).cloned().collect())
}
/// Whether a message changes what the server holds — any notification but a
/// `$/cancelRequest`. These are the messages whose order is the order the
/// client sent them in (`Server::must_hold`).
pub(super) fn changes_state(message: &Message) -> bool {
matches!(message, Message::Notification(n) if n.method != Cancel::METHOD)
}