Review round §61.4 (R4): a fixed-arrival probe showed a publish costs the size of the index (a whole-index merge per burst); a scan now publishes at most once per 512 files with the waiting drain exempt — publication −78 to −88 %, loaded scans −48 to −65 %, median wait 112 → 2 ms warm at the same offered load; an empty navigation answer mid-scan is deferred to the next publish or scan end (unsettled answers 0 everywhere); a cancel naming a deferred request answers it cancelled (lead fix for QA's finding); HEAD_WALK_MAX pinned
ci / checks (push) Successful in 1m17s
ci / corpus (push) Successful in 36s

This commit is contained in:
lucio committed 2026-09-08 22:38:56 -05:00
1 parent eb54042032
commit 07ef771a35
20 files changed
+1900 -48

No files matched your search

+71 -8
View File
@@ -6436,19 +6436,82 @@ scan_order.rs,server/startup.rs,server/index.rs,index_cache.rs}`, tests.
Review §4. Files: `tools/perf/` (a fixed-arrival-rate probe), then
`lucisv_server/src/{server/index.rs,state/,candidates.rs,includes.rs}`.
- [ ] the probe: a definition every N ms of wall clock (not after the
- [x] the probe: a definition every N ms of wall clock (not after the
previous response), recording queue latency, publications, per-
publication cost (index absorb / candidates / includes / overlays)
and scan completion under the same offered load, 1 / 10 / many
buffers
- [ ] then reduce duplicate publication work (incremental candidates and
buffers — **`tools/perf/phases_r4.py`: `scanload` (warm),
`scanloadcold`, `scanloadcross`, plus a quiet control in the same
series. A fixed request *count* over a fixed window, because the
first draft stopped sending when the server went quiet, which made
the offered load a function of the server — `scanserve`'s own
confound in a new place. The split at `eb54042`, warm, one open
buffer, a definition every 100 ms: 34 publishes, `absorb` 2 433 ms
(78 %), `candidates` 623 (20 %), `includes` 47, `overlay` 2.4
(0.08 %) — 3 105 ms of publication in a 4 206 ms scan whose quiet
form takes 1 005. Cold: 88 publishes, 7 973 of 10 675 against a
2 766 ms quiet scan. `absorb` is the cost because it ends in a
whole-index merge; the overlay refresh, which this item expected to
matter, is 0.08 % at one buffer and 9.6 % at 101**
- [x] then reduce duplicate publication work (incremental candidates and
includes tables, or a bounded publish cadence) preserving the
coherent-prefix contract; quiet-scan decode/merge only after an
allocation profile shows duplication
- [ ] measured: same offered load, better queue latency AND completion;
never fewer served requests reported as a speedup; R4 cells
- [ ] QA: coherence under load; the probe's arrival discipline verified;
numbers re-taken
allocation profile shows duplication — **the cadence
(`Scan::publish_is_due`, `PUBLISH_EVERY` 512): one merge per 512
staged records instead of one per burst of requests, with the drain
that has something *waiting* — the session's first useful answer —
exempt. A quiet scan still publishes nothing. The candidates
rebuild and the overlay refresh were **measured and not rebuilt**:
the cadence takes both down with it, and the overlay is noise at
every buffer count an editor has. `WorkspaceIndex::absorb`'s
whole-index merge is named as a finding for a later lane —
`update_facts` has a targeted merge beside it and `absorb` does
not, but that is a `vlog_semantic` change this lane may not make**
- [x] measured: same offered load, better queue latency AND completion;
never fewer served requests reported as a speedup; R4 cells —
**same offered load, requests answered equal in every cell:
publication −78 to −88 %, the traced scan −48 to −65 %, the median
request wait −98 to −99.5 % (warm 112.3 → 1.9 ms at one buffer,
1 960 → 10.4 at 101; cold 137.7 → 1.5, and 4 706 → 2.1 at two).
Across the sixteen loaded cells the tail improved in ten, was level
in two and rose in four — three of them single-open-buffer cells,
worst warm 168 → 422 ms, against cold 9 308 → 1 583 at 101 buffers.
Quiet warm scan 1 005 → 985 ms (≤ 1 s kept), quiet cold 2 724 →
2 694, first useful answer 78.2 → 80.8 cold / 115.1 → 115.8 warm,
idle RSS −0.2 %, store size identical, 24 of 24 scope cells equal,
`scanserve` cold median 122.2 → 45.6 with the same 13 requests
served. `mismatched_answers` 0 and `unsettled_answers` 0
everywhere — and on a new cross-folder cursor the reference is
unsettled 12 of 270 with one buffer and 270 of 270 with eleven
where the candidate is 0. Feature README
`docs/features/perf5r-publication/`; 4 360 → 4 365 tests**
- [x] the lead's §61.3 rulings, both on this drain path: **an empty
navigation answer computed mid-startup-scan is not answered — the
request is asked again at the next publish and at the latest when
the scan ends, where `[]` is honest. Three methods
(definition / typeDefinition / references), a hover untouched and
pinned. The `HEAD_WALK_MAX` fixture QA asked for is in
`server/tests/startup.rs` and was sabotage-checked**
- [x] QA: coherence under load; the probe's arrival discipline verified;
numbers re-taken — **PASS. Coherence sabotage-tested (a direct
index/candidates-agreement test, failed when `publish_scan`'s
candidates absorb is disabled). The "never re-ask" sabotage produces
the lost-request failure this task guards against; the shipped rule
does not. `HEAD_WALK_MAX` sabotage reproduces "515 files (the folder
first)". `scanload`/`scanloadcross` re-run independently on the dev's
own binaries: `mismatched_answers` 0 and `unsettled_answers` 0 for the
candidate in every cell, matching the archived record. Quiet
scan/RSS controls re-run within ±10% (widest +6.9%). Tail
characterized: the CAND max attributed to cadence spacing, not
deferral; a T=100 ms secondary bound estimated to give back most of
this cell's publication win since the reference's own pre-cadence
publish spacing (~123 ms) is already close to 100 ms. One
non-blocking gap found and pinned by a new test: a `$/cancelRequest`
against a request sitting in `Server::deferred`, arriving outside a
batch that reunites it with a publish, is silently ineffective
(exactly-one-response held; `cancel-request`'s README needs a dated
amendment, filed as a handshake). QA log in
`docs/features/perf5r-publication/README.md`**
### 61.5 R3b + R3c — rename scope reuse (conditional)
+1 -1
View File
@@ -94,7 +94,7 @@ pub(super) fn cancelled_in(batch: &[Message]) -> HashSet<RequestId> {
/// 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> {
pub(super) fn cancelled_id(message: &Message) -> Option<RequestId> {
let Message::Notification(notification) = message else { return None };
if notification.method != Cancel::METHOD {
return None;
@@ -49,6 +49,25 @@ use crate::{
pairs, ports, rename, selection, signature, symbols, tokens, type_def, type_hierarchy,
};
/// The requests whose empty answer may mean "this scan has not reached the
/// file yet" rather than "there is nowhere to go".
///
/// All three answer with a **list of places** and with an empty list when they
/// find none, so `[]` is exactly the shape that carries no information. Every
/// other request is left alone: a hover's `null`, a completion's empty list and
/// a code-action menu with no offers all mean what they say whatever the scan
/// has reached, and deferring one would be withholding an answer rather than
/// waiting for a better one. `textDocument/implementation` would belong here;
/// this server does not answer it, so it is not written down as if it did.
const NAVIGATION: [&str; 3] =
[GotoDefinition::METHOD, GotoTypeDefinition::METHOD, References::METHOD];
/// Whether a response says **nowhere**: an answer, not a failure, and an empty
/// list of places. See [`NAVIGATION`].
pub(super) fn names_nowhere(response: &Response) -> bool {
matches!(&response.response_result, Ok(Value::Array(found)) if found.is_empty())
}
impl Server {
/// Answer one request, timing it when `--verbose` asked.
///
@@ -80,6 +99,46 @@ impl Server {
response
}
/// A copy of `request` to ask again at the scan's next publish, when an
/// empty answer to it right now would mean "not scanned yet" rather than
/// "nowhere".
///
/// **The lead's ruling from §61.3, as a rule in the drain.** A held
/// startup request is answered the moment the user's own folder is
/// published, and a definition whose target lives in another folder was
/// answered `[]` there — coherent, and wrong by the time the scan ended.
/// Rather than teach the drain to work out whether the published prefix
/// resolves *this* request's target, the answer is computed through the
/// ordinary handler and, when it names nowhere and the index is still
/// growing, put back ([`Server::deferred`]).
///
/// **Only while a scan is running**, so a settled server answers empty
/// exactly as it always did — including the last try, after the scan ends.
/// **Only the three navigation methods that answer with a list of places**
/// ([`NAVIGATION`]): a hover, a completion, a code action or a rename is
/// unaffected, and so is every request whose empty answer means something
/// else. `textDocument/implementation` is not on the list because this
/// server does not answer it.
pub(super) fn ask_again_if_empty(&self, request: &Request) -> Option<Request> {
if !self.scanning || !NAVIGATION.contains(&request.method.as_str()) {
return None;
}
Some(Request::new(request.id.clone(), request.method.clone(), request.params.clone()))
}
/// `--verbose`: that a navigation answer was set aside for the next
/// publish rather than sent, and how many are waiting with it.
pub(super) fn say_deferred(&self, request: &Request) {
if !self.verbose {
return;
}
self.timing(format!(
"{} DEFERRED to the next publish (empty mid-scan, already deferred={})",
request.method,
self.deferred.len()
));
}
/// [`Server::flush_dirty`], with the dirty-buffer stage measured apart
/// from the handler that follows it.
///
+47 -4
View File
@@ -221,9 +221,29 @@ impl Server {
self.scanning = false;
// A neighbourhood can only be owed by a scan, and there is none now.
self.head_owed = false;
self.answer_what_was_deferred();
warnings
}
/// Answer whatever the empty-answer rule set aside, now that the index has
/// stopped growing.
///
/// **The other half of that rule, and the reason it can never strand a
/// request.** A navigation answer was deferred because `[]` might have
/// meant "not scanned yet"; here it cannot mean that any more, so an empty
/// answer is the honest one and goes out. The scan is over, so
/// [`Server::ask_again_if_empty`] defers nothing this time round — and a
/// request the order contract still holds, one behind something already
/// `held`, is put back by `process_batch`'s own rule exactly as any other
/// message would be.
pub(super) fn answer_what_was_deferred(&mut self) {
let deferred = std::mem::take(&mut self.deferred);
if deferred.is_empty() || self.stopped {
return;
}
self.stopped = !matches!(self.process_batch(deferred), Ok(false));
}
/// One whole scan: the bar up, every file indexed with the client's
/// messages answered between two of them, the bar down.
///
@@ -334,13 +354,22 @@ impl Server {
/// **This is the round's whole point, and its whole cost.** Polling costs
/// one `try_recv` per file and finds nothing in a scan nobody is waiting
/// on, so a quiet scan pays nothing at all; a scan somebody *is* waiting
/// on pays one merge per burst to make the records it has taken since the
/// last one answerable ([`Workspace::publish_scan`]). The messages then go
/// on pays a merge to make the records it has taken since the last one
/// answerable ([`Workspace::publish_scan`]). The messages then go
/// through the same `process_batch` the loop uses, so a `didChange` queued
/// ahead of a hover is applied before that hover is answered and a cancel
/// beside its request still answers it `RequestCancelled` — the order
/// contract is the loop's, unchanged, because it is the loop's code.
///
/// **A merge per burst was the cost; a merge per 512 files is what it is
/// now.** [`Scan::publish_is_due`] is the cadence, and the one drain
/// exempt from it is the one with something *waiting* — the startup's held
/// requests, drained the moment the neighbourhood is in, which is the
/// session's first useful answer and must not be a file later than it was
/// (`docs/features/perf5r-first-answer/README.md`). Everything else reads
/// a coherent prefix that is at most a cadence older, which is the trade
/// `docs/features/perf5r-publication/README.md` measures.
///
/// An error here is a client that has gone: there is nobody to report it
/// to and no reason to go on scanning, so it stops the scan the same way a
/// `shutdown` does.
@@ -350,9 +379,24 @@ impl Server {
// would be `[]` (`docs/features/perf5-p4/README.md` §P4b3).
self.head_owed = !scan.neighbourhood_indexed();
let mut batch = self.waiting_for_this_scan();
let owed = !batch.is_empty();
let mut arrived = Vec::new();
while let Ok(message) = self.queue.try_recv() {
batch.push(message);
arrived.push(message);
}
// A quiet scan pays nothing at all, and that is a promise: the cadence
// is asked only when there is something for a publish to be *for*.
if !owed && arrived.is_empty() && self.deferred.is_empty() {
return false;
}
if owed || scan.publish_is_due() {
self.workspace.publish_scan(scan);
// A navigation answer this scan could not give yet is asked again
// off the prefix that has just grown — behind whatever was already
// waiting, ahead of everything newer ([`Server::deferred`]).
batch.append(&mut self.deferred);
}
batch.append(&mut arrived);
if batch.is_empty() {
return false;
}
@@ -364,7 +408,6 @@ impl Server {
// recomputed below once the new head segment is known.
let opened = !opened_in(&batch).is_empty();
self.head_owed |= opened;
self.workspace.publish_scan(scan);
self.stopped = !matches!(self.process_batch(batch), Ok(false));
// The files the user has just opened, and the folders around them, are
// what they are looking at, so they are indexed next rather than when
+57 -3
View File
@@ -46,7 +46,8 @@ use lsp_types::{SemanticToken, Uri};
use crate::state::Workspace;
use batch::{burst, cancelled_in, cancelled_response};
use batch::{burst, cancelled_id, cancelled_in, cancelled_response};
use dispatch::names_nowhere;
mod batch;
mod client;
@@ -227,6 +228,23 @@ pub struct Server {
/// [`Server::must_wait`] — this is the order contract, not a queue of its
/// own.
held: Vec<Message>,
/// Navigation requests a scan answered **empty** while it was still
/// growing the index, to be asked again at its next publish.
///
/// **Not a second `held`, and deliberately not part of
/// [`Server::must_wait`].** A held request is one the order contract says
/// nothing newer may overtake; this is one whose answer was computed,
/// found to name nowhere, and set aside because the reason it named
/// nowhere may be that the file it wants has not been scanned yet
/// (`docs/features/perf5r-publication/README.md`). Nothing else is owed
/// anything by it — a hover, a completion or a code action behind one is
/// answered exactly as before — and it is asked again at most once per
/// publish, so the re-computation is bounded by the cadence and not by the
/// scan's file count. A scan ending runs whatever is left through the
/// dispatch one last time, with itself already over — so nothing is
/// deferred that time round and an empty answer, which is now the honest
/// one, goes out ([`Server::answer_what_was_deferred`]).
deferred: Vec<Message>,
/// `--verbose`: whether every operation says how long it took, in the
/// client's log channel. Off is the shipped state and the whole of what it
/// costs is the branch that reads this field — see
@@ -393,7 +411,20 @@ impl Server {
let response = if cancelled.remove(&request.id) {
cancelled_response(request.id)
} else {
self.request(request)
// A navigation request whose answer would be `[]` only
// because the scan has not reached its target yet is
// asked again at the next publish rather than answered
// with nowhere ([`Server::deferred`]).
let again = self.ask_again_if_empty(&request);
let response = self.request(request);
match again.filter(|_| names_nowhere(&response)) {
Some(request) => {
self.say_deferred(&request);
self.deferred.push(Message::Request(request));
continue;
}
None => response,
}
};
self.connection.sender.send(Message::Response(response))?;
}
@@ -402,7 +433,14 @@ impl Server {
// already been done above. Kept only so that a request behind
// one that has to wait takes its cancel with it.
Message::Notification(notification) if notification.method == Cancel::METHOD => {
consumed_cancels.push(Message::Notification(notification));
let cancel = Message::Notification(notification);
// A request the empty-answer rule set aside is not in this
// burst, so `cancelled_in` cannot see it — but it is still
// a request the client is waiting on, and a cancel for it
// is honoured where it lands: answered `RequestCancelled`
// now, and never asked again (QA, perf5r-publication).
self.cancel_deferred(&cancel)?;
consumed_cancels.push(cancel);
}
Message::Notification(notification) => self.notification(notification),
Message::Response(response) => self.response(response),
@@ -411,6 +449,22 @@ impl Server {
Ok(false)
}
/// Honour a `$/cancelRequest` naming a request in [`Server::deferred`]:
/// take it out and answer it cancelled. A cancel naming anything else is
/// left to the batch's own rule.
fn cancel_deferred(&mut self, cancel: &Message) -> Result<(), Box<dyn Error + Sync + Send>> {
let Some(id) = cancelled_id(cancel) else { return Ok(()) };
let found = self
.deferred
.iter()
.position(|message| matches!(message, Message::Request(request) if request.id == id));
if let Some(at) = found {
self.deferred.remove(at);
self.connection.sender.send(Message::Response(cancelled_response(id)))?;
}
Ok(())
}
/// Whether a request reaching the dispatch right now must wait instead of
/// being answered.
///
@@ -167,6 +167,7 @@ impl Server {
answering_a_rescan: false,
stopped: false,
held: Vec::new(),
deferred: Vec::new(),
verbose,
born: Instant::now(),
}
@@ -386,3 +386,35 @@ fn a_cancel_naming_a_server_initiated_id_does_not_touch_response_routing() {
// cancel did not intercept it.
session.answer(server_id, Value::Null);
}
/// A request the empty-answer rule set aside (`Server::deferred`,
/// perf5r-publication) is not in any burst, so the burst's own cancel rule
/// cannot see it. A cancel for it must still be honoured where it lands:
/// answered `RequestCancelled` at once, taken out of the deferred set, and
/// never asked again when the scan ends. Found by QA on §61.4; the request is
/// planted directly because a real deferral lives only inside a running scan.
#[test]
fn a_cancel_for_a_deferred_request_answers_it_cancelled_and_forgets_it() {
let (_tree, mut session, uri) = cancelling_session("cancel-deferred", ONE_MODULE);
let parked = Request::new(
RequestId::from(41),
GotoDefinition::METHOD.to_string(),
serde_json::json!({
"textDocument": { "uri": uri },
"position": { "line": 0, "character": 7 }
}),
);
session.server.deferred.push(Message::Request(parked));
session.server.process_batch(vec![cancel(serde_json::json!(41))]).expect("a burst");
assert_eq!(outcomes(&session), vec![(RequestId::from(41), Some(CANCELLED))]);
assert!(session.server.deferred.is_empty(), "the cancelled request is not asked again");
// And the scan's end finds nothing left to answer: exactly one response.
session.server.answer_what_was_deferred();
assert!(outcomes(&session).is_empty(), "a cancelled request is answered once");
// A cancel naming a request that is *not* deferred changes nothing.
session.server.process_batch(vec![cancel(serde_json::json!(42))]).expect("a burst");
assert!(outcomes(&session).is_empty());
}
+195 -28
View File
@@ -21,6 +21,7 @@ use super::scan::{positions, symbol_request};
use super::scan_trace::{field, is_trace_line, line_of, trace_tree};
use super::*;
use crate::server::startup::OPENING_FILE_WAIT;
use crate::state::discover::HEAD_WALK_MAX;
/// A client that answers `workspace/configuration` and is told what a scan
/// spent its time on.
@@ -691,10 +692,19 @@ fn a_buffer_opened_from_the_workspace_root_is_no_neighbourhood_to_lead_with() {
!started.contains("the folder first"),
"the root is not a folder to lead with: {started}"
);
// No deadlock: the request is still answered, and inside the scan.
let (ended, answered) = positions(&said, 7);
let answered = answered.expect("the definition is answered at all");
assert!(answered < ended.expect("the bar comes down"), "inside the scan: {said:#?}");
// No deadlock: the request is still answered, and with the right place.
// **It used to be answered `[]` inside the scan** — the drain reached it
// before the alphabet reached `ip/aes/rtl`, and `[]` was what the prefix
// said. Since §61.4 an empty *navigation* answer computed while the index
// is still growing is not an answer at all: the request is asked again at
// the scan's next publish and, in a workspace this small, at the scan's
// end — which is later, and right (`perf5r-publication`).
let found = result_of(&said, 7).expect("the definition is answered at all");
assert_eq!(
found[0]["uri"],
serde_json::json!(path_to_uri(&tree.path.join("ip/aes/rtl/aes.sv")).expect("uri")),
"the module the buffer instantiates, not the empty prefix: {found}"
);
assert_eq!(session.server.workspace.index().files().len(), INTERLEAVE_ABOVE + 9);
}
@@ -769,26 +779,72 @@ fn an_unsaved_buffer_leads_with_its_own_text_and_not_the_disk_copy() {
);
}
#[test]
fn a_target_outside_the_head_is_answered_when_the_head_is_published_and_is_empty() {
// **The honest limit, pinned.** A held request is drained the moment the
// user's own folder is published, and a definition whose target lives in
// *another* folder is answered `[]` there — the same answer a request
// arriving mid-scan has always had for a file the scan has not reached
// (`docs/features/scan-interleave/README.md`). The split does not
// introduce it and does not widen it: the reference answers the same
// request the same way, one interleave point earlier.
//
// Making it wait instead needs the drain to know whether the index
// already resolves the request's own target, which is a `server/dispatch`
// decision and a handshake this lane filed rather than made.
let tree = a_block_and_a_crowd("splitcrossfolder", INTERLEAVE_ABOVE + 6);
/// The cross-folder fixture: the buffer's folder is `ip/aes`, and what it
/// instantiates lives in `ip/kmac` — so the head the split publishes first
/// cannot answer the definition in it.
fn a_block_that_instantiates_the_block_next_door(tag: &str) -> Tree {
let tree = a_block_and_a_crowd(tag, INTERLEAVE_ABOVE + 6);
tree.write("ip/kmac/rtl/kmac.sv", "module kmac;\nendmodule\n");
// The buffer's folder is `ip/aes`; what it instantiates is in `ip/kmac`.
tree.write("ip/aes/dv/tb/tb.sv", "module tb;\n kmac dut ();\nendmodule\n");
tree
}
#[test]
fn a_target_outside_the_head_is_asked_again_rather_than_answered_nowhere() {
// **§61.3's honest limit, closed by §61.4's rule.** A held request is
// drained the moment the user's own folder is published, and a definition
// whose target lives in *another* folder used to be answered `[]` there —
// coherent, and wrong by the time the scan ended. The rule now says an
// empty **navigation** answer computed while the index is still growing is
// not an answer: the request is put back and asked again at the scan's
// next publish, and at the latest when the scan ends
// (`docs/features/perf5r-publication/README.md`).
//
// This fixture stages under `PUBLISH_EVERY` files, so there is exactly one
// publish — the head's — and the request is answered where the second half
// of the rule catches it: at the end of the scan, with the right location.
let tree = a_block_that_instantiates_the_block_next_door("splitcrossfolder");
let opened = tree.path.join("ip/aes/dv/tb/tb.sv");
let text = std::fs::read_to_string(&opened).expect("read");
let mut session = Session::staged(
let session = Session::staged(
vec![tree.path.clone()],
pulling_with_a_bar(),
true,
CONFIGURATION_WAIT,
vec![
configuration_answer(the_whole_workspace()),
did_open(&opened, &text),
definition_at(7, &opened, 1, 3),
],
);
let said = session.drain();
let found = result_of(&said, 7).expect("a result, not a failure");
assert_eq!(
found[0]["uri"],
serde_json::json!(path_to_uri(&tree.path.join("ip/kmac/rtl/kmac.sv")).expect("uri")),
"the block next door, which is the settled answer: {found}"
);
// Once, not twice: the deferral puts the request back, it does not answer
// it and then answer it again.
let answers = said
.iter()
.filter(|message| matches!(message, Message::Response(r) if r.id == RequestId::from(7)))
.count();
assert_eq!(answers, 1, "one response for one request: {said:#?}");
}
#[test]
fn a_navigation_answer_that_is_genuinely_empty_is_answered_when_the_scan_ends() {
// **The rule defers; it never withholds.** A cursor on a name nothing in
// the workspace declares is empty at every publish and empty at settle,
// and the request is answered all the same — with `[]`, once the scan has
// stopped being a reason to doubt it.
let tree = a_block_and_a_crowd("crossfoldergenuinelyempty", INTERLEAVE_ABOVE + 6);
tree.write("ip/aes/dv/tb/tb.sv", "module tb;\n nowhere dut ();\nendmodule\n");
let opened = tree.path.join("ip/aes/dv/tb/tb.sv");
let text = std::fs::read_to_string(&opened).expect("read");
let session = Session::staged(
vec![tree.path.clone()],
pulling_with_a_bar(),
true,
@@ -804,17 +860,128 @@ fn a_target_outside_the_head_is_answered_when_the_head_is_published_and_is_empty
assert_eq!(
found.as_array().map(Vec::len),
Some(0),
"answered off the head, which does not hold the other block: {found}"
"nothing declares `nowhere`, and the answer says so: {found}"
);
}
#[test]
fn a_type_definition_outside_the_head_is_asked_again_too() {
// The rule is three methods wide and the definition test only walks one of
// them. A `typeDefinition` on the instance name answers with the module it
// instantiates, which lives in the block next door: empty off the head,
// right once the scan has been all the way round.
let tree = a_block_that_instantiates_the_block_next_door("splitcrossfoldertype");
let opened = tree.path.join("ip/aes/dv/tb/tb.sv");
let text = std::fs::read_to_string(&opened).expect("read");
let ask = Message::Request(Request::new(
RequestId::from(7),
GotoTypeDefinition::METHOD.to_string(),
serde_json::json!({
"textDocument": { "uri": path_to_uri(&opened).expect("uri") },
"position": { "line": 1, "character": 7 },
}),
));
let session = Session::staged(
vec![tree.path.clone()],
pulling_with_a_bar(),
true,
CONFIGURATION_WAIT,
vec![configuration_answer(the_whole_workspace()), did_open(&opened, &text), ask],
);
let found = result_of(&session.drain(), 7).expect("a result, not a failure");
assert_eq!(
found[0]["uri"],
serde_json::json!(path_to_uri(&tree.path.join("ip/kmac/rtl/kmac.sv")).expect("uri")),
"the instance's module, from the block next door: {found}"
);
}
#[test]
fn a_hover_is_never_deferred_however_empty_it_is() {
// **The rule is three methods wide, and this is the wall.** A hover
// answers `null` for a name the index has not reached, and `null` is what
// a hover means by "nothing to say" whatever the scan has done — so it is
// answered where every mid-scan request is answered, inside the scan and
// before the bar comes down. Deferring it would be withholding an answer
// rather than waiting for a better one.
let tree = a_block_that_instantiates_the_block_next_door("crossfolderhover");
let opened = tree.path.join("ip/aes/dv/tb/tb.sv");
let text = std::fs::read_to_string(&opened).expect("read");
let hover = Message::Request(Request::new(
RequestId::from(7),
HoverRequest::METHOD.to_string(),
serde_json::json!({
"textDocument": { "uri": path_to_uri(&opened).expect("uri") },
"position": { "line": 1, "character": 3 },
}),
));
let session = Session::staged(
vec![tree.path.clone()],
pulling_with_a_bar(),
true,
CONFIGURATION_WAIT,
vec![configuration_answer(the_whole_workspace()), did_open(&opened, &text), hover],
);
let said = session.drain();
let (ended, answered) = positions(&said, 7);
let answered = answered.expect("the hover is answered at all");
assert!(
answered < ended.expect("the bar comes down"),
"inside the scan, at the head publish, like every other mid-scan request: {said:#?}"
);
}
#[test]
fn a_folder_bigger_than_the_head_bound_is_scanned_exactly_as_it_always_was() {
// **`HEAD_WALK_MAX`, pinned** — the bound QA found untested in §61.3. Past
// 512 files the neighbourhood is not provably a minority of anything, so
// the split is refused: the walk is finished there and then, the two lists
// are merged in path order, and the scan is the one every scan before the
// split was. The proof is in three parts — the scan does not say "the
// folder first", every file is indexed once, and the index it lands is the
// one a session with nothing open lands.
let tree = a_block_and_a_crowd("headwalkmax", 4);
for n in 0..=HEAD_WALK_MAX {
tree.package(&format!("ip/aes/rtl/big{n:04}.sv"), &format!("big{n:04}"));
}
let opened = tree.path.join("ip/aes/dv/tb/tb.sv");
let text = std::fs::read_to_string(&opened).expect("read");
let session = Session::staged(
vec![tree.path.clone()],
pulling(),
true,
CONFIGURATION_WAIT,
vec![configuration_answer(the_whole_workspace()), did_open(&opened, &text)],
);
let started = scan_started(&session.drain());
assert!(
!started.contains("the folder first"),
"a neighbourhood over the bound is walked with everything else: {started}"
);
// And once the scan has settled the very same request is right — the
// index is complete, and nothing about the split changed what it holds.
session.batch(vec![definition_at(8, &opened, 1, 3)]);
let settled = result_of(&session.drain(), 8).expect("a result");
// Every file once: the whole tree is `crowd/` (4) + `ip/aes/rtl` (1 + the
// padding) + `ip/aes/dv/tb` (1) + `ip/kmac` (none here).
let files = session.server.workspace.index().files();
let expected = 4 + 1 + (HEAD_WALK_MAX + 1) + 1;
assert_eq!(files.len(), expected, "every file, and none of them twice");
let mut sorted = files.to_vec();
sorted.sort();
sorted.dedup();
assert_eq!(sorted.len(), files.len(), "no path is in the index twice");
// And the index is the one the bound's other side would have built.
let quiet = Session::staged(
vec![tree.path.clone()],
pulling(),
true,
CONFIGURATION_WAIT,
vec![configuration_answer(the_whole_workspace())],
);
let _ = quiet.drain();
assert_eq!(
settled[0]["uri"],
serde_json::json!(path_to_uri(&tree.path.join("ip/kmac/rtl/kmac.sv")).expect("uri")),
"the settled answer is the one the gate compares against: {settled}"
session.server.workspace.index().fingerprint(),
quiet.server.workspace.index().fingerprint(),
"the open buffer bought the order, never a different index"
);
}
+1 -1
View File
@@ -372,7 +372,7 @@ impl Workspace {
/// 0.2 ms a file (124 files in 25 ms, `docs/features/perf5-p4/README.md`
/// §P4b3), so a head of this size is ~100 ms of stepping and the whole first
/// answer still fits inside the round's 200 ms gate.
pub(super) const HEAD_WALK_MAX: usize = 512;
pub(crate) const HEAD_WALK_MAX: usize = 512;
impl Workspace {
/// Whether this scan may walk the user's own folders first and the rest of
+36 -1
View File
@@ -28,7 +28,7 @@ use crate::module_select::{self, Reach};
use crate::rename_trace::{self, Rung, SelectionTrace, Wanted};
use crate::scan_order::{self, WorkList};
mod discover;
pub(crate) mod discover;
mod scan;
use crate::scan_trace::{CacheWork, ScanTrace};
@@ -2488,6 +2488,41 @@ mod tests {
ws.finish_scan(scan)
}
#[test]
fn the_publication_cadence_holds_a_publish_until_enough_has_been_staged() {
// **The whole of the cadence, at its exact boundary.** A publish is a
// pass over the whole index, and before §61.4 the drain paid one per
// burst of requests — 13 to 18 in one warm opentitan scan, 46 % of it
// (`docs/features/perf5r-publication/README.md`). `publish_is_due`
// spaces them by work done rather than by how often a client asks: no
// publish is due until `PUBLISH_EVERY` records are staged, one is due
// the moment the 512th lands, and publishing clears the debt.
let tree = Tree::new("publishcadence");
for n in 0..scan::PUBLISH_EVERY + 2 {
tree.package(&format!("p{n:04}.sv"), &format!("p{n:04}"));
}
let mut ws = Workspace::default();
ws.client.index_scope = IndexScope::Workspace;
ws.adopt_roots(vec![tree.path.clone()]);
let mut scan = ws.begin_scan(&mut |_| {}, false);
for taken in 1..scan::PUBLISH_EVERY {
assert!(ws.scan_step(&mut scan, &mut |_| {}), "premise: file {taken} exists");
assert!(!scan.publish_is_due(), "{taken} staged is not yet a publish");
}
assert!(ws.scan_step(&mut scan, &mut |_| {}), "premise: the 512th file exists");
assert!(scan.publish_is_due(), "{} staged is", scan::PUBLISH_EVERY);
ws.publish_scan(&mut scan);
assert!(!scan.publish_is_due(), "and publishing clears the debt");
// The cadence is a latency decision and nothing else: what this scan
// lands is what a one-shot scan over the same tree lands.
while ws.scan_step(&mut scan, &mut |_| {}) {}
ws.finish_scan(scan);
let mut one_shot = Workspace::default();
one_shot.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(everything(&one_shot), everything(&ws));
}
/// A tree of three files that declare each other's names and include each
/// other, so a half-published index has something to get wrong.
fn tangled(tag: &str) -> Tree {
+40
View File
@@ -170,6 +170,18 @@ pub(super) struct PendingDiscovery {
pub(super) seen: HashSet<PathBuf>,
}
/// How many records may be staged before another mid-scan publish is worth the
/// whole-index merge it costs — see [`Scan::publish_is_due`].
///
/// **512 is a work bound, and it is deliberately the same number
/// `HEAD_WALK_MAX` is.** Both answer "how much of this workspace may a user
/// wait for before an answer stops being worth waiting for": 512 warm steps is
/// ~100 ms of scanning on the corpus the round measured
/// (`docs/features/perf5r-first-answer/README.md`), so a request landing
/// between two publishes reads an index at most that far behind and the whole
/// scan pays at most one merge per 512 files instead of one per burst.
pub(crate) const PUBLISH_EVERY: usize = 512;
/// Which of the two shapes a [`Scan`] is.
///
/// One enum rather than two `finish` methods so a caller cannot pair the wrong
@@ -221,6 +233,34 @@ impl Scan {
self.at >= self.head
}
/// Whether enough has been staged since the last publish for another one
/// to be worth the merge it costs — the **publication cadence**.
///
/// **A publish is a pass over the whole index, and it used to be one per
/// burst of requests.** `answer_what_is_waiting` published whenever
/// anything at all was waiting, so a client asking ten times a second
/// bought ten merges a second over a table that grows all the way to the
/// end of the scan. Measured on opentitan under a definition every 100 ms
/// (`docs/features/perf5r-publication/README.md`): 13 to 18 publishes in
/// one warm scan, and `absorb` + `candidates` alone were 46 % of it.
///
/// The rule this asks is **how much new the next answer would see**, not
/// how long ago the last publish was: a merge's cost is the index's size
/// and its value is the records it makes answerable, so files staged is
/// the currency both are in — and it is a count, so what a scan does is
/// the same on a fast machine and a slow one, and a test may assert it.
///
/// It bounds staleness, never correctness: a request answered between two
/// publishes reads a prefix at most [`PUBLISH_EVERY`] files older than the
/// one it could have had, and every table in it still agrees with every
/// other ([`Workspace::publish_scan`](super::Workspace::publish_scan)).
/// The **first** publish of a scan is never deferred by it — that one is
/// the session's first useful answer, and `server/index.rs` asks for it by
/// a different door.
pub fn publish_is_due(&self) -> bool {
self.staged.len() >= PUBLISH_EVERY
}
/// Whether this scan still owes itself the rest of its own scope — see
/// [`PendingDiscovery`].
///
+11
View File
@@ -531,3 +531,14 @@ 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.
### 2026-09-08 — the deferred set (perf5r-publication, lead)
A navigation request whose answer was empty while the startup scan was
still growing is put in `Server::deferred` and asked again at the next
publish (`docs/features/perf5r-publication/README.md`). Such a request is
in no burst, so the burst's own cancel rule (`cancelled_in`) cannot see
it; `Server::cancel_deferred` honours a `$/cancelRequest` naming it where
the cancel lands — answered `RequestCancelled` at once, removed, never
asked again. Every request still gets exactly one response. Found by QA;
pinned by `a_cancel_for_a_deferred_request_answers_it_cancelled_and_forgets_it`.
+879
View File
@@ -0,0 +1,879 @@
# perf5r-publication — what a startup scan costs while requests keep arriving
Review round §R4 (TODO §61.4). `docs/performance_take5_review.md` §4 and its
"Startup throughput and responsiveness must be judged separately".
## Goal
A scan that answers messages between its files pays a **publication** for each
burst: the staged records merged into the index, the completion tables
re-derived, the include graph folded in, every open buffer's overlay refreshed
(`Workspace::publish_scan`). The review could not say what that costs, because
the only probe it had (`scanserve`) sends the next request 200 ms *after the
previous response* — so a more responsive server is asked more often and its
session-completion time is not comparable with anything. This lane builds the
controlled probe the review asked for — a **fixed arrival rate**, the same
offered load whatever the server does with it — reads the publication cost off
the server's own trace beside the request latencies, and then reduces what the
probe names without touching the coherent-prefix contract. It also carries two
items the lead assigned here because they live on the same drain path: the
empty-answer rule §61.3 filed, and the `HEAD_WALK_MAX` test §61.3's QA found
missing.
## Assumptions
- **The three tables are published together or not at all.** Nothing here
changes that; the cadence changes *how often* a publish happens, never what
one contains (`docs/features/scan-interleave/README.md`).
- **A prefix is allowed to be old, never inconsistent.** A request answered
between two publishes reads an index that is at most `PUBLISH_EVERY` files
behind the one it could have had. That was always true between two interleave
points; the cadence widens the gap and does not change its nature.
- **`[]` from a navigation request is not information while the index is
growing.** The empty-answer rule rests on this: a definition, a
typeDefinition and a references answer with a *list of places* and with an
empty list when they find none, so `[]` cannot be told apart from "not
scanned yet". A hover's `null`, a completion's empty list and an empty
code-action menu mean what they say, and are untouched.
- **`textDocument/implementation` is not answered by this server**, so it is
not on the navigation list even though it would belong there.
- The corpus is opentitan `0098135264` with its three known modifications, read
only. Every number is from `tools/perf/bench.py` under
`tools/guard.sh -m 8 -t 1800`.
## Handshakes
### `lucisv_server::state` — the publication cadence
```rust
pub(crate) const PUBLISH_EVERY: usize = 512; // state/scan.rs
impl Scan {
/// Whether enough has been staged since the last publish for another one
/// to be worth the merge it costs.
pub fn publish_is_due(&self) -> bool;
}
```
Additive. `publish_scan` is unchanged — same signature, same contract, same
three tables — and so is every other entry on `Scan`. The only caller of
`publish_is_due` is `server/index.rs::answer_what_is_waiting`, which is the one
place a mid-scan publish is decided.
`state::discover` and `HEAD_WALK_MAX` went from `pub(super)` to `pub(crate)`, so
`server/tests/startup.rs` can write a fixture *against the bound* rather than
against the number 512 written out again. No line was added to `state/mod.rs`
for it.
### `lucisv_server::server` — a request may be asked again
```rust
struct Server {
/// Navigation requests a scan answered empty while it was still growing
/// the index, to be asked again at its next publish.
deferred: Vec<Message>,
}
impl Server {
pub(super) fn ask_again_if_empty(&self, request: &Request) -> Option<Request>;
pub(super) fn say_deferred(&self, request: &Request);
}
pub(super) fn names_nowhere(response: &Response) -> bool;
```
**`deferred` is deliberately not part of `must_wait`.** `held` is the order
contract — nothing newer may overtake what is waiting there. `deferred` is not
a queue at all: the answer was computed, found to name nowhere, and set aside
because the reason may be that the file has not been scanned. Nothing is owed
anything by it, so a hover, a completion or a code action behind one is answered
exactly as before. That is the difference the two names are for.
### `docs/features/scan-interleave/README.md`
A dated entry records both, with the rules they amend stated in that README's
own terms. Neither is a contract change: the coherence contract, the order
contract and `INTERLEAVE_ABOVE` are all untouched.
### `docs/features/perf5r-first-answer/README.md`
That lane's cross-folder `[]` — pinned openly and filed as request 5 — is
answered here. Its test moved with it; the "honest limit" it pinned is now the
rule's own regression test.
### Requests for the lead (`docs/topo.md` is not edited by this lane)
1. `lucisv_server ──▶ vlog_semantic`: nothing new. `WorkspaceIndex::absorb` is
called with the same arguments, fewer times.
2. A new edge inside `lucisv_server`: `server::index ──▶ state::scan`
(`publish_is_due`) and `server::mod ──▶ server::dispatch` (`names_nowhere`,
`ask_again_if_empty`).
3. `state::discover` is now `pub(crate)` — a visibility widening for a test,
not an interface.
4. **A finding for a future lane, not a request:** `WorkspaceIndex::absorb`
ends in `merge(None)`, a pass over every record the index holds, while
`update_facts` has a targeted `merge(Some(&affected))` beside it. Under load
that whole-index merge is the single largest publication cost. An additive
`absorb` that takes an `Affected` would be a `vlog_semantic` change, which
this lane's file list excludes; the cadence reduces how often it is paid
rather than what it costs. Numbers below.
## How it works
### The probe: `scanload`
`tools/perf/phases_r4.py`, schema 2, registered in `bench.py` like every other
phase.
- **The clock, not the answers.** A `textDocument/definition` goes out every
`rate` ms of wall time counted from the session's own start, whether or not
the previous one has been answered. Requests pipeline; a server that stalls
accumulates them, which is the queue latency the probe exists to see.
- **A fixed count, so the load is the same for both binaries.** The first draft
stopped sending when the server stopped saying things, and that reintroduced
`scanserve`'s confound in a new place: a mid-scan lull in the progress
chatter stopped the probe at 14 requests where the session ran for 20 ticks.
The window is now fixed per cache state (`WINDOW_MS`: cold 9 000 ms, warm
3 500 ms — long enough to cover the reference's whole loaded session), so both
binaries are asked exactly the same number of times and a binary that finishes
sooner shows it as requests answered **after** settle, never as requests never
sent.
- **Every request's own wait.** `Session.poll_answers` (new, additive, in
`lspclient.py`) takes every response that has arrived without blocking on the
oldest, and the arrival instant is stamped in the reader thread, so a request
answered while the probe is busy sending the next one is not charged for the
probe's poll interval.
- **The publication split beside the latencies.** The session runs `--verbose`,
so `publishes`, `published` and the four `publish_*` stages come off the very
session whose requests are in the row.
- **A quiet control in the same series**: the same cells with no requests at
all, so a settle time that moved can be told apart from one that moved
*because requests arrived*.
- **Cells:** rate ∈ {100, 250} ms × cache ∈ {cold, warm} × extra open buffers
∈ {0, 1, 10, 100}, three fresh sessions each, plus the quiet control per
(cache, buffers). Buffer counts are *extra*: the cursor's own file is always
open, so "0" is one buffer and "100" is 101 — `scanprofile`'s convention.
- **Recorded per cell:** every request's wall latency (median and max, and the
same two over the mid-scan subset), how many were answered before settle,
`mismatched_answers` and `unsettled_answers` against the settled answer,
settle time, the publish counts and stage split, `tick_jitter_ms` (the largest
slip between a tick's due instant and its write — how a reader checks the
arrival discipline the row claims), and requests offered vs answered.
### The cadence
`answer_what_is_waiting` published whenever anything at all was waiting — one
whole-index merge per burst of requests. It now publishes when
* something was **waiting** — the startup's held requests, drained the moment
the neighbourhood is in. That publish is the session's first useful answer
and is never deferred (`perf5r-first-answer`); or
* `Scan::publish_is_due()` — `PUBLISH_EVERY` (512) records staged since the
last publish.
A count rather than a clock, for three reasons: a merge's cost is the index's
size and its value is the records it makes answerable, so files staged is the
currency both are in; what a scan does is then the same on a fast machine and a
slow one; and a test can assert it. 512 is deliberately `HEAD_WALK_MAX`'s
number — both answer "how much of this workspace may a user wait for", and 512
warm steps is ~100 ms of scanning on this corpus.
**A quiet scan still pays nothing at all.** The cadence is asked only when there
is something for a publish to be *for*: the drain returns before it, as it
always did, when nothing is held, nothing has arrived and nothing is deferred.
### The empty-answer rule
Inside `process_batch`, at the one place a request's response is sent:
1. `ask_again_if_empty` takes a copy of the request when a scan is running and
the method is one of the three in `NAVIGATION`;
2. the answer is computed through the **ordinary handler**, exactly as before;
3. if it `names_nowhere` — an `Ok` result that is an empty array — the copy goes
on `deferred` and nothing is sent;
4. the next publish puts `deferred` at the front of that drain's batch, behind
whatever was already `held` and ahead of everything newer, and they are asked
again;
5. `scan_until_settled` ends with `answer_what_was_deferred`, which runs
whatever is left through `process_batch` with `scanning` already false — so
the rule defers nothing that time round and an empty answer goes out.
The re-computation is bounded **by publishes, not by steps**: a deferred request
is asked again once per publish, so at most a handful of times in a whole scan,
and a request that keeps coming back empty costs one evaluation per publish and
is answered when the scan ends.
## Measured
Machine and method are `docs/perf/README.md`'s: Apple M1 Max, macOS 27.0,
release binaries built with `cargo build --release --locked`, opentitan
`0098135264` with its three known modifications, everything under
`tools/guard.sh -m 8 -t 1800`, three fresh sessions a cell, no cargo command
during a timed run. Reference `REF` = trunk `eb54042`; candidate `CAND` = that
tree plus this lane's diff. `~/.cache/lucisv-perf/take5r-4/`.
### What a publish costs, and how it scales — the R4 baseline
The reference under a definition every 100 ms of wall clock, warm, one open
buffer: **34 publishes in one scan**, and
| stage | ms | share of publication |
|---|---:|---:|
| `publish_absorb` | 2 433 | **78 %** |
| `publish_candidates` | 623 | 20 % |
| `publish_includes` | 47 | 1.5 % |
| `publish_overlay` | 2.4 | 0.08 % |
| **total** | **3 105** | of a **4 206 ms** scan — **74 %** |
The same scan with no requests at all takes **1 005 ms**. So under this load the
scan is four times longer, and essentially all of the difference is
publication. Cold is the same shape and worse: 88 publishes, **7 973 ms** of
publication in a **10 675 ms** scan, against a **2 766 ms** quiet cold scan.
Three things the split says, and only one of them is what the brief guessed:
1. **`index.absorb` is the cost.** It is 78 % of publication because it ends in
`merge(None)`, a pass over every record the index holds — so a publish costs
the size of the *index*, not the size of the batch, and the index grows all
the way to the end of the scan. `vlog_semantic`'s own doc comment says a
per-file merge would be quadratic; under load the drain was doing one per
burst of requests, which is the same shape at a coarser grain.
2. **The candidates rebuild is real but second.** `Candidates::absorb` ends in
`take_index_tables`, which re-derives the unit, module and macro tables from
the whole index every publish — 20 % of publication, ~18 ms a publish on
this corpus.
3. **The overlay refresh is not a lever.** It is **0.08 %** at one open buffer
and **9.6 %** at 101 (291 ms of 3 037), i.e. about 0.09 ms per buffer per
publish. At the buffer counts an editor actually has it is noise. This is
the item the work order expected to matter; the measurement says it does
not, and the reduction it asked for — deciding per buffer whether the
absorbed records could have moved its external resolutions — would cost a
name-set intersection per buffer per publish to save a tenth of a
millisecond. **Not done, and the numbers are why.**
Scaling: publication is flat in the number of open buffers except for the
overlay term (2.4 ms at 1 buffer → 291 ms at 101), and roughly linear in the
number of publishes, which is set by how often requests arrive. That is the
whole finding: *the client's request rate, not the workspace, decides what a
scan spends on publication.*
### The cadence, under the same offered load
Warm, every cell three fresh sessions, the same fixed number of requests
offered to both binaries (`requests answered` is equal in every row, so nothing
here is a speedup bought by serving less).
| cell (warm) | | latency p50 | latency max | publishes | publication ms | scan ms |
|---|---|---:|---:|---:|---:|---:|
| 100 ms, 1 buffer | REF | 112.3 | 168.0 | 34.3 | 3 105 | 4 206 |
| | **CAND** | **1.9** | 421.9 | **4.7** | **588** | **2 188** |
| 250 ms, 1 buffer | REF | 243.4 | 256.5 | 14.0 | 2 824 | 3 852 |
| | **CAND** | **1.9** | **203.5** | **3.0** | **378** | **1 417** |
| 100 ms, 2 buffers | REF | 308.9 | 2 109.5 | 33.0 | 3 082 | 4 117 |
| | **CAND** | **2.4** | **680.7** | **4.0** | **688** | **1 725** |
| 100 ms, 11 buffers | REF | 175.6 | 1 912.6 | 33.3 | 3 101 | 4 142 |
| | **CAND** | **2.3** | **708.6** | **3.7** | **580** | **1 654** |
| 100 ms, 101 buffers | REF | 1 960.1 | 3 672.0 | 33.0 | 3 037 | 4 254 |
| | **CAND** | **10.4** | **823.1** | **4.0** | **669** | **1 873** |
**Publication down 78–87 %, the scan down 48–63 %, the median request wait down
98–99.5 %, and the same number of requests answered.**
The **tail** is the one place this is not a clean sweep, and the count across
all sixteen loaded cells (warm and cold, both rates, four buffer counts) is:
**improved in ten, level in two, higher in four.** Three of the four are
single-open-buffer cells — the case where the reference is at its best, because
publishing after every burst keeps the index so fresh that no request waits
long for one, and the worst of them is warm 100 ms, **168 → 422 ms**. The
fourth is warm 250 ms at 11 buffers, 760 → 777 ms, which is 2 %. Against that:
3 672 → 823 ms at 101 buffers warm and 9 308 → 1 583 ms cold, and a median that
went from 112 ms to 1.9. The trade is legible — four merges instead of
thirty-four means a request that lands inside one waits for it — and it is
one request in thirty-five.
Cold is the same shape and larger, because a cold scan is longer and every
publish merges a bigger index by the time it happens:
| cell (cold) | | latency p50 | latency max | publishes | publication ms | scan ms |
|---|---|---:|---:|---:|---:|---:|
| 100 ms, 1 buffer | REF | 137.7 | 210.6 | 87.7 | 7 973 | 10 675 |
| | **CAND** | **1.5** | 395.5 | **7.0** | **922** | **3 686** |
| 250 ms, 1 buffer | REF | 225.3 | 255.0 | 36.7 | 6 816 | 9 569 |
| | **CAND** | **1.3** | 313.1 | **5.0** | **552** | **3 301** |
| 100 ms, 2 buffers | REF | 4 705.9 | 9 160.5 | 89.7 | 7 979 | 10 778 |
| | **CAND** | **2.1** | **1 440.0** | **7.0** | **922** | **3 602** |
| 100 ms, 11 buffers | REF | 4 724.7 | 9 194.9 | 89.7 | 7 980 | 10 801 |
| | **CAND** | **1.9** | **1 412.2** | **6.0** | **880** | **3 626** |
| 100 ms, 101 buffers | REF | 4 832.2 | 9 308.4 | 89.3 | 7 959 | 10 947 |
| | **CAND** | **2.2** | **1 583.3** | **6.0** | **932** | **3 829** |
**Publication −88 %, the traced scan −65 %, and at two or more open buffers the
tail improves by six times.** The overlay term at 101 buffers goes 812 → 56 ms
with it. Note the reference's cold median at two or more open buffers: **4.7
seconds**. That is not publication — it is `must_wait`'s `held` clause, and it
is the finding the probe made before a line of this lane's code existed: the
first held request holds every request behind it, so a whole session's stream
drains in one burst when the neighbourhood lands. The candidate's median is
2 ms because its session is over less than halfway through the offered window,
so most of the same requests meet a settled server.
**Two numbers in these tables mean different things and should not be added
up.** `scan ms` is the server's own traced scan wall time and is the honest
"completion under load". The probe's own `settled_ms` is **floored by the
request window** whenever the session finishes inside it — the last chatter the
probe sees tracks its own last request — so it understates the improvement
(warm 1 buffer: settle 4 215 → 3 417, −19 %, against the scan's −48 %). For the
same reason `mid_scan_*` misclassifies post-settle answers as mid-scan in the
candidate's rows and is not quoted here. The comparison the tables rest on is
sound without either: **both binaries are offered the identical number of
requests over the identical window and answer all of them.**
### The empty-answer rule, at a cursor the head cannot answer
`scanload`'s cursor names a module in `hw/ip/aes/rtl`, which the head walks
first, so it is non-empty from the first publish and the rule never fires on
it. `scanloadcross` asks the same fixed load at `tl_if` in the same buffer —
an interface declared in `hw/dv/sv/tl_agent`, which the open buffer's folder
does not hold. `unsettled_answers` counts every answer that was not the settled
one, empty ones included: it is the review §2 gate, and it is what the rule is
for.
| cell | | latency p50 | latency max | answered | **unsettled** |
|---|---|---:|---:|---:|---:|
| cold, 1 buffer | REF | 105.1 | **215.8** | 270 | **12** |
| | **CAND** | **1.3** | 486.4 | 270 | **0** |
| cold, 11 buffers | REF | 4 735.8 | 9 217.8 | 270 | **270** |
| | **CAND** | **1.5** | **1 884.0** | 270 | **0** |
| warm, 1 buffer | REF | 120.6 | **212.1** | 105 | **12** |
| | **CAND** | **1.7** | 380.6 | 105 | **0** |
| warm, 11 buffers | REF | 1 822.3 | 3 624.8 | 105 | **105** |
| | **CAND** | **2.0** | **891.0** | 105 | **0** |
**The reference answers this cursor wrongly 12 times in 270 with one buffer
open and *every single time* with eleven** — because with eleven the whole
request stream is held until the neighbourhood lands and is then drained in one
burst off a prefix that does not reach `hw/dv`. The candidate is wrong zero
times in all four cells.
**What that costs, said plainly:** in the two single-buffer cells the tail rises
(216 → 486 ms cold, 212 → 381 warm), because a request whose target the scan
has not reached now waits for the publish that holds it instead of being told
`[]` immediately. That is the trade the lead's ruling asks for, and it is the
right way round — the review's gate is *"do not withhold useful answers"*, and
`[]` when the answer exists is not a useful answer. In the eleven-buffer cells
even the tail improves, by four times.
### Everything the cadence must not have cost
The quiet startup matrix, three fresh sessions a cell, medians:
| `scan` cell | REF | CAND |
|---|---:|---:|
| workspace, cold | 2 747.5 | 2 715.9 |
| workspace, warm | 981.0 | 983.7 |
| workspace cold, **first useful answer** | 78.2 | 80.8 |
| workspace warm, **first useful answer** | 115.1 | 115.8 |
| default scope, cold / warm | 95.1 / 50.7 | 101.9 / 48.5 |
| `{"index":{}}`, cold / warm | 111.0 / 48.8 | 106.3 / 48.9 |
| `scopeDepth 0`, cold / warm | 10.5 / 8.7 | 11.3 / 12.5 |
Memory, which the review's gate says must be *retained*: idle RSS after the
workspace scan **502 736 → 501 872 KiB cold** and **427 200 → 426 448 KiB
warm** (−0.2 % both, peak equal to idle), and the index store on disk **45 404
KiB in both** — byte-for-byte the same size, because nothing about what a scan
writes changed. The cadence holds records staged for longer, which is the one
place it could have cost memory: at most `PUBLISH_EVERY` `FileFacts` instead of
one burst's worth, and the numbers say that is not visible.
Nothing moved outside its spread. The two that had to be checked by name are
the **warm quiet scan** — still under a second, which is the milestone §61.3
reached for the first time — and the **first useful answer**, which is §61.3's
whole result and which the cadence could have delayed by deferring the head
publish. It does not: that drain is the one the cadence exempts, and the number
says so.
### `scanserve` — the review's own probe, unchanged and re-run
The response-paced probe the review used, three fresh sessions a cell. It
served the **same number of requests per session for both binaries** here (13
cold, 5 warm), so its confound does not bite in this comparison:
| | REF | CAND |
|---|---:|---:|
| cold, median mid-scan definition | 122.2 ms | **45.6 ms** |
| cold, worst | 334.0 ms | 334.8 ms |
| cold, session completion | 4 506 ms | **3 938 ms** |
| warm, median | 114.0 ms | 114.2 ms |
| warm, worst | 290.2 ms | **279.4 ms** |
| warm, session completion | 1 692 ms | 1 697 ms |
| `mismatched_answers` / `unsettled_answers` | 0 / 0 | 0 / 0 |
Warm is flat and that is the expected reading, not a disappointment: at one
request per 200 ms *of response* a warm session only gets five of them in, so
the reference pays five publishes and there is nothing for a cadence to
remove. The cadence is for the case where a client asks faster than the server
finishes, which is what `scanload` offers and what the cold column already
shows.
The quiet control did not move: warm quiet scan **1 004.7 → 984.7 ms** at one
buffer (and 1 020 → 1 065, 1 029 → 1 041, 1 201 → 1 156 at 2 / 11 / 101), so
the ≤ 1 s the last round reached is kept and none of this was bought from the
quiet case. A quiet session's mid-scan publishes go **1 → 0**: nothing is
waiting, so nothing is published, which is the promise `scan-interleave` made
and this keeps.
## Status / TODO
- [x] R4a — the fixed-arrival-rate probe (`tools/perf/phases_r4.py::scanload`,
`scanloadcold`, `scanloadcross`), cold and warm, 1 / 2 / 11 / 101 open
buffers, with the quiet control and the publication split; R4 baseline
cells filled from `eb54042`
- [x] the publication cadence (`Scan::publish_is_due`, `PUBLISH_EVERY`)
- [x] the empty-answer rule (`Server::deferred`, `ask_again_if_empty`,
`names_nowhere`, `answer_what_was_deferred`)
- [x] the `HEAD_WALK_MAX` fixture §61.3's QA asked for — and sabotage-checked
(the bound's branch disabled, the test fails with
`515 files (the folder first)`)
- [x] the candidates rebuild and the selective overlay refresh: **measured,
not built.** The cadence takes both down with it, and the overlay is
0.08 % of publication at one open buffer
- [x] measured: `scanload` both rates and all buffer counts, `scanloadcold`,
`scanloadcross`, `scanserve`, quiet `scan` cold/warm, `rss`, the 24 scope
cells; R4 row and experiment record `R4-2026-09-08` in
`docs/perf/take5-tracking.md`
### Gates
- `cargo fmt` clean; guarded `cargo clippy --all-targets` clean with no new
`#[allow]`; guarded `cargo test --workspace` green, **4 360 → 4 365**, none
dropped. Six test functions written, one of which replaces the §61.3 test
whose subject the rule changed, so the count rises by five: the cadence's
exact boundary (in `state`), the cross-folder definition (the replacement),
the cross-folder typeDefinition, the genuinely-empty answer, the hover that
is never deferred, and the `HEAD_WALK_MAX` fixture.
- Under the same offered load: publishes and publication time down, settle down
or held, latency not worse, **served requests equal**.
- `mismatched_answers` 0 and `unsettled_answers` 0 on `scanload` and
`scanserve`, both binaries, cold and warm.
- The quiet warm scan does not regress past 1.0 s.
- opentitan's three known modifications, unchanged, after every phase.
## Work log
### 2026-09-08 — dev (Opus), §61.4
**Order of work: the probe first, and it changed the plan twice.**
1. **The probe, written before anything was touched.** The first run of it was
the finding: under a definition every 100 ms the reference answered
*nothing* until the scan was 74 % over, because `must_wait`'s `held` clause
makes the first held request hold every request behind it — so the whole
session's stream drains in one burst at the head publish. That is
`perf5r-first-answer`'s territory, not this lane's, but the probe says it,
so it is written down.
2. **The probe was wrong the first time, and the way it was wrong is the
review's own confound.** It stopped sending when the server stopped saying
things; a lull in the progress chatter stopped it at 14 requests where the
session ran for 20 ticks, which makes the offered load a function of the
server. Rewritten around a **fixed request count** over a fixed window per
cache state. The first (uncontrolled) series is kept as
`paired-partial-firstattempt.jsonl` and no number in this README comes from
it.
3. **The split named a different lever than the work order expected.**
`publish_absorb` is 78 % and the overlay refresh is 0.08 % at one open
buffer. The work order's first two reductions were the candidates rebuild
and a selective overlay refresh; the measurement says the overlay is noise
at every buffer count an editor has, so **it was not built** and the numbers
are in [Measured](#measured) instead.
4. **The cadence is the reduction that fits this lane's files.** `absorb` ends
in a whole-index merge inside `vlog_semantic`, which this lane may not
change; how *often* that merge is paid is `server/index.rs`'s decision, and
it was "once per burst of requests". `Scan::publish_is_due` makes it once
per 512 staged records, with the drain that has something *waiting* — the
session's first useful answer — exempt.
5. **The empty-answer rule**, the lead's §61.3 ruling, went in beside it
because the two interact: the cadence makes a mid-scan prefix older, and the
rule is what stops that being visible as a wrong `[]`. It is a rule in the
drain and not a second computation — the answer is computed once through the
ordinary handler and either sent or set aside — and a set-aside request is
asked again **once per publish**, which the cadence now bounds to a handful
per scan.
6. **A test that already pinned the old behaviour had to move, and it is the
right kind of move.** `a_buffer_opened_from_the_workspace_root_is_no_
neighbourhood_to_lead_with` asserted that its definition was answered
*inside* the scan; it was answered `[]`. It now asserts the answer is
`ip/aes/rtl/aes.sv`, which arrives later and is right. Said plainly here
because "a test changed" is the sentence a reviewer should be suspicious of.
**Deviations, stated:**
- **`tools/perf/lspclient.py` was changed**, which the work order's file list
describes as "`tools/perf/` (new phase file + README rows)". Two additive
hunks: a response's arrival instant stamped in the reader thread, and
`Session.poll_answers`, which takes every response that has arrived without
blocking on the oldest. A probe that pipelines cannot be written without it —
`await_id` blocks — and measuring each request's own wait through a polling
loop instead would put the poll interval in every number. No existing phase's
behaviour changes; `await_id` gained one line that drops a stamp it does not
read.
- **`scanload` is two phases** (`scanload` warm, `scanloadcold`). A cold cell
under this load is a ten-second session and eight of them do not fit inside
the 1 800-second guard. The first paired attempt was **stopped by hand**
before it reached that limit rather than allowed to be killed; splitting the
run is the answer, and the guard was not touched.
- **`state::discover` and `HEAD_WALK_MAX` widened from `pub(super)` to
`pub(crate)`** so the new fixture is written against the bound rather than
against the number 512 spelled out again. `state/mod.rs` gained no line for
it (`mod discover;` → `pub(crate) mod discover;`).
- **A `scanloadcross` cell was added that the work order did not ask for.** The
cursor `scanload` measures resolves inside the open buffer's own folder, so
the empty-answer rule never fires on it and the row would say nothing about
what that rule costs. The cross-folder cell is what makes the cost visible
rather than asserted.
**Gates.** `cargo fmt` clean; guarded `cargo clippy --all-targets` clean with
no new `#[allow]`; guarded `cargo test --workspace` green at **4 365**, from
4 360, none dropped. opentitan's three known modified files unchanged after
every phase. **No guard kill.**
**File sizes** (non-blank, non-comment, before the trailing test module):
`server/index.rs` **225**, `server/dispatch.rs` **485** (from 464),
`server/mod.rs` **169** (from 158), `state/scan.rs` **128** (from 124),
`state/discover.rs` 329, `candidates.rs` 405, `includes.rs` 605 (untouched).
`state/mod.rs` is **976 production lines, exactly what it was**: the module
visibility change costs no line and the only thing added to it is a test.
**A limitation of the probe, for QA and for whoever reads the rows next.** The
probe's `settled_ms` is the session's last notification, and the session keeps
producing notifications while requests arrive — so when the scan finishes
inside the offered window, `settled_ms` tracks the *window* rather than the
scan, and `mid_scan_median_ms` / `mid_scan_max_ms` then count post-settle
answers as mid-scan. Neither is quoted in this README for that reason: `scan
ms` (the server's own trace) is the completion figure and the latency columns
are over the whole fixed load, which is identical for both binaries. The
notification the requests provoke was not chased down; it is a probe question,
not a server one, and it is written here rather than left for a reader to
notice.
## QA log
### 2026-09-08 — QA (Sonnet), §61.4 R4
Read CLAUDE.md, TODO §61.4, `docs/performance_take5_review.md` §4 and its
"Startup throughput and responsiveness must be judged separately", this
README in full, `docs/features/perf5r-first-answer/README.md`'s Review (the
ruling that sent the empty-answer rule here), `docs/features/scan-interleave/
README.md`'s 2026-09-08 §61.4 entry, `docs/features/cancel-request/README.md`
in full, the tracker's `R4-2026-09-08` record, the working-tree diff, and the
evidence in `~/.cache/lucisv-perf/take5r-4/`. Experiments in a fresh clone at
scratchpad `qa-61-4/repo` (HEAD `eb54042` + the working diff applied,
byte-identical to the working tree — verified `diff -rq` clean except the
tests I added). A second clone `qa-61-4/repo-ref` at bare `eb54042` was built
for the per-binary test comparison. All cargo and all perf commands ran
through `tools/guard.sh -m 8 -t 1800`; no guard kill anywhere; no lingering
background loops (all launched via `run_in_background`/`Monitor`, all exited
on their own and were confirmed dead).
**1. Gates (main tree, guarded).** `cargo fmt --all -- --check` clean.
`cargo clippy --all-targets` clean, zero warnings, no new `#[allow]` (checked
the diff directly). `cargo test --workspace`: **4 365 passed, 0 failed**,
exactly the dev's number. Per-binary diff against the `repo-ref` clone at bare
`eb54042` (4 360 passed there): every binary's count is identical except
`lucisv_server`'s `unittests src/main.rs` (1 645 → 1 650, +5) — matching the
dev's own accounting exactly (one test rewritten in place — the §61.3 test
`a_target_outside_the_head_is_answered_when_the_head_is_published_and_is_empty`
→ `a_target_outside_the_head_is_asked_again_rather_than_answered_nowhere`,
read and judged correct: it now asserts the settled location instead of an
inside-the-scan `[]`, which is exactly right given the rule this lane ships —
plus five new tests). Nothing lost anywhere. Production line counts:
`server/index.rs` 225, `dispatch.rs` 485, `server/mod.rs` 169, `state/scan.rs`
128, `state/discover.rs` 329 — all match the README exactly.
`state/mod.rs` **976**, unchanged, confirmed (counting stops one line before
the `#[cfg(test)]` attribute, not `mod tests {` itself — the same off-by-one
also explains `candidates.rs`, 405 vs my raw 406). **One inaccuracy found and
noted, not fixed** (it is in a Work log entry, not the Status/Handshakes
sections QA may touch): `includes.rs` is cited as "605 (untouched)" but its
actual non-blank/non-comment production count before its first `#[cfg(test)]`
is **273**, under any counting convention I could construct (with or without
doc comments, with or without blank-only stripping). The file is genuinely
untouched by this diff and 273 is nowhere near any CLAUDE.md threshold either
way, so this is a citation slip in the prose, not a gate or a size problem —
flagged for the lead to correct in the work log if they choose.
**2. The probe.** Read `tools/perf/phases_r4.py` and the `lspclient.py` diff
in full.
- `offer()`'s send loop is `while sent < ticks`, ticks fixed
(`WINDOW_MS[cache] // rate`), computed once up front — no early exit on
server silence. The shipped probe cannot reproduce "stopped in a lull";
confirmed by reading the loop, there is no path back to the caller before
`sent == ticks`.
- `lspclient.py`'s `_dispatch` (called only from `_read_loop`, the reader
thread — confirmed by grep) stamps `self._arrived[id] = time.perf_counter()`
the instant a response is parsed, before any caller could see it.
`poll_answers` reads that stamp and never blocks — it only pops entries
already in `self._inbox` matching a pending id. This is the arrival-time
fix the review's confound needed.
- Same offered load to both binaries: confirmed directly off the evidence —
every REF/CAND pair I read had identical `requests_offered` and
`requests_answered` (e.g. 35 offered / 105 answered across 3 tries, both
binaries, warm 100 ms 1-buffer cell).
- `mismatched_answers`/`unsettled_answers` are computed in `summary()` against
`run["settled_answer"]`, which is a **final same-params request sent at the
end of the same session** (`s.request("textDocument/definition", params)`)
— same request, same cursor, correct comparison target.
- The probe's own limitation (`settled_ms` floored by the fixed window) is
understood and does not taint any quoted number: every table in the README
uses `scan_total`/`scan ms` (the server's own trace), never `settled_ms`,
and `mid_scan_*` is explicitly not quoted for the same reason. Confirmed by
reading `publication()` (`out["scan_total"] = stages.get("total", 0.0)`)
and by re-deriving the README's own numbers from the raw evidence (below).
**3. Coherence under load, and the sabotage.** `publish_scan`
(`state/mod.rs:1167`) absorbs the index, the candidates table and the include
graph in one synchronous call with no interleave point inside it — a
structural guarantee, not a tested-and-hoped one, since this is a
single-threaded event loop. `answer_what_is_waiting` (`server/index.rs`)
calls `publish_scan` to completion *before* splicing `self.deferred` or
`arrived` into the batch that gets dispatched, so no request can ever observe
a batch published mid-way through. I wrote and ran the direct witness the
task asked for (`state::tests::a_cadence_publish_never_lets_the_index_and_the_
candidates_table_disagree`, in the scratch clone only — a 513-file tree,
scanned exactly to the `PUBLISH_EVERY` boundary, one `publish_scan` call, then
asserting every one of the 512 just-published module names is in *both*
`index().units()` and `candidates().has_module()`, and the 513th is in
*neither*). It passes on the real candidate. **Sabotage**: commented out
`self.candidates.absorb(&self.index, words)` inside `publish_scan` — the test
fails immediately (`cohmod0000 published: candidates`), then reverted (byte-
diff against the pre-sabotage copy confirmed clean).
`scanload`/`scanloadcross` re-run, independently, on the dev's own release
binaries (hashes verified: REF `f7a5a27e…`, CAND `4af863c1…`, both match the
tracker record exactly) against the same read-only opentitan corpus, fresh
storage under my scratchpad:
- warm 100 ms, 1 buffer: REF p50 102.7 / p90 182.4 / max 209.6 ms; CAND p50
0.8 / p90 177.4 / max 419.9 ms. `mismatched_answers` 0, `unsettled_answers`
0, offered = answered = 105, both binaries.
- warm 100 ms, 11 buffers: REF p50 1970.2 / p90 3367.8 / max 3699.6 ms; CAND
p50 0.9 / p90 396.7 / max 700.7 ms. Same zero/zero, same offered=answered.
- `scanloadcross`, all 8 cells (cold/warm × 1/11 buffers × REF/CAND):
`mismatched_answers` 0 in every cell; `unsettled_answers` — REF 12/270,
270/270, 9/105, 105/105 (the 9 vs the archived 12 at warm/1-buffer is
ordinary run-to-run timing noise around the head-publish boundary — the
*shape* is identical); **CAND 0/0/0/0 in every one of the 8 cells**, on a
completely independent run.
This reproduces the archived record's own numbers closely (warm/1-buffer
REF p50 112.3→102.7, CAND max 421.9→419.9; warm/11-buffer REF p50
1960.1→1970.2, max 3672.0→3699.6, both within a few percent) and confirms
`mismatched_answers`/`unsettled_answers` are 0/0 everywhere for the candidate,
never withholding or coherence-breaking a single answer, on data this session
generated itself rather than only reading the dev's own.
**4. The empty-answer rule.** Three methods (`GotoDefinition`,
`GotoTypeDefinition`, `References`) — confirmed directly in
`server/dispatch.rs`'s `NAVIGATION` const, and the handler match arms confirm
`Hover` is not among them. Dev's shipped tests cover: cross-folder definition
asked again and answered right, exactly once; the same for typeDefinition;
hover never deferred (answered inside the scan); a genuinely-empty answer
(`nowhere`) answered `[]` at settle; `HEAD_WALK_MAX` pinned. Three cases the
shipped tests do not cover, which I wrote in the scratch clone
(`server/tests/startup.rs`, using `process_batch`/`Server::deferred` directly
— both reachable from `server::tests::*` by ordinary Rust module privacy,
since they are plain-private items in an ancestor module):
- `a_cancel_sharing_a_publish_with_a_deferred_request_still_cancels_it` — a
cancel in the **same** batch as a deferred request still cancels it
(`cancelled_in` scans the whole batch regardless of position). Passes.
- `a_cancel_that_arrives_while_its_request_is_still_deferred_does_not_reach_it`
— **a real gap, found and pinned, not a hard-invariant violation.** A
cancel that arrives in its *own* batch, while its request is sitting in
`Server::deferred` (not yet reunited with a publish), is consumed by
`process_batch`'s local `consumed_cancels` for that call and does not
survive to the next one. The deferred request is later answered normally —
a **real, uncancelled answer** — as if the cancel never happened. This
costs nothing under the hard invariants QA is bound to (exactly one
response is still sent, no request is lost, no answer is wrong), so it is
**not** a REWORK finding by the letter of this task's own criteria. But
`docs/features/cancel-request/README.md`'s own stated reasoning for
dropping a late cancel — *"by then the request has been answered"* — is
false for a request sitting in `deferred`: it has not been answered at all
yet. `deferred` is a new kind of "not yet answered but no longer in a
burst" state that predates neither README knew about the other. **Filed as
a handshake request below**, not fixed by QA (touches `cancel-request`'s
own Assumptions section, outside this feature's scope).
- `two_deferred_requests_are_answered_in_the_order_they_arrived` — `deferred`
is append-only (`Vec::push`, `std::mem::take`, never reordered), so two
requests deferred in the same scan are answered in arrival order. Passes.
All three compiled and ran clean against the real candidate
(`cargo test -p lucisv_server --bin lucisv-server deferred`, 4 passed).
**5. Sabotage: "never re-ask."** Commented out
`self.answer_what_was_deferred()` in `finish_scan` (`server/index.rs`) — the
shipped cross-folder test
(`a_target_outside_the_head_is_asked_again_rather_than_answered_nowhere`)
fails with "a result, not a failure" (the request is never answered at all —
a lost request, exactly the REWORK class this task names). Reverted; byte-
diff against the pre-sabotage copy confirmed clean; test passes again.
**6. `HEAD_WALK_MAX`.** Read the bound (`state/discover.rs:450`,
`head.len() > HEAD_WALK_MAX`) and the dev's fixture
(`a_folder_bigger_than_the_head_bound_is_scanned_exactly_as_it_always_was`,
513 files in one folder). Sabotaged the branch (`if false && head.len() >
HEAD_WALK_MAX`) — the test fails exactly as the README claims:
`"515 files (the folder first)"` (513 in the neighbourhood folder + 2 more
from `a_block_and_a_crowd`'s fixed padding). Reverted; clean.
**7. The tail — characterized, not failed.** Re-derived the R4 baseline split
straight from `~/.cache/lucisv-perf/take5r-4/paired.jsonl`'s per-try
`publication` records for the warm/100 ms/1-buffer cell: REF averages
scan 4206.14 ms / publication 3105.27 ms across 34.3 publishes; CAND averages
scan 2188.36 ms / publication 587.99 ms across 4.67 publishes — both exactly
the README's headline numbers, independently recomputed from the raw
per-request arrays rather than trusted from the prose.
*Attributing the CAND max (421.9 ms, warm/1-buffer, this cell is not
cross-folder so the empty-answer rule never fires on it — the wait is purely
cadence).* Average publish spacing here is scan/publishes ≈ 2188/4.67 ≈
469 ms; a request landing just after a publish waits close to the full next
interval. 421.9 ms is consistent with exactly that — a request arriving
right after a publish, waiting almost the whole way to the next one — not a
deferral (none possible on this cursor) and not the startup's `held` clause
(the first useful answer already landed at ~80–115 ms, long before most of
this cell's requests are sent).
*What T = 100 ms would cost, estimated from the trace.* `absorb`'s cost is a
**whole-index merge**, i.e. roughly proportional to the index's size at the
moment of the call, not to the batch just staged (the README's own finding,
confirmed by reading `WorkspaceIndex::absorb`'s doc comment and
`update_facts`'s targeted-merge counterexample beside it). For K evenly
spaced publishes over a scan that reaches a fixed final size S, each publish
i costs roughly c·i·(S/K), so total absorb cost is c·S·(K+1)/2 — **linear in
the number of publishes, for a fixed corpus**. Going from the cadence's
current K≈4.7 (this cell) to a clock bound that fires roughly every 100 ms —
which, given requests arrive every 100 ms and something is almost always
waiting, would mean roughly one publish per 100 ms of wall clock, i.e. K on
the order of 20+ over a ~2 s scan — would raise total publication cost
*roughly in proportion*, back up toward the 2 000–3 000 ms range: most of
this cell's −78 % publication win given back. This is not a coincidence: the
**reference's own pre-cadence behaviour already published once every
4206/34.3 ≈ 123 ms on average** — almost exactly a T=100 ms clock bound. A
secondary time bound at T=100 ms would reproduce close to the *reference's*
publication cost for exactly the load this cell offers, while presumably
still helping a slower (250 ms) or quieter client. That trade is the lead's
to rule on; the count-based `PUBLISH_EVERY` alone does not have this failure
mode because it is insensitive to how fast the client asks.
**8. Controls, re-run** (dev's own REF/CAND release binaries, hashes
verified, fresh storage under my scratchpad, `tools/guard.sh -m 8 -t 1800`):
| cell | archived median | QA re-run median | Δ |
|---|---:|---:|---:|
| quiet scan, warm, REF | 981.0 | 1033.2 | +5.3% |
| quiet scan, warm, CAND | 983.7 | 1051.7 | +6.9% |
| quiet scan, cold, REF | 2747.5 | 2831.6 | +3.1% |
| quiet scan, cold, CAND | 2715.9 | 2826.2 | +4.1% |
| first useful answer, cold, REF | 78.2 | 82.0 | +4.8% |
| first useful answer, cold, CAND | 80.8 | 81.3 | +0.7% |
| first useful answer, warm, REF | 115.1 | 113.0 | −1.9% |
| first useful answer, warm, CAND | 115.8 | 113.4 | −2.1% |
| idle RSS, cold, REF (KiB) | 502736 | 502528 | −0.04% |
| idle RSS, cold, CAND (KiB) | 501872 | 504240 | +0.5% |
| idle RSS, warm, REF (KiB) | 427200 | 427984 | +0.2% |
| idle RSS, warm, CAND (KiB) | 426448 | 426688 | +0.06% |
All twelve within the requested ±10 % (the widest is +6.9 %, general machine-
load noise — the session's one-minute load was higher during this QA rerun
than the dev's own session start). Store 45 404 KiB, identical, both re-runs.
The 24-of-24 scope cells were checked against the archived evidence directly
(every `scopes` row's `result_count` equal REF vs CAND) rather than re-run,
since nothing about scope resolution is in this diff's file list.
**Traceability (item 8): 17 numbers independently reproduced from
`~/.cache/lucisv-perf/take5r-4/` and matched exactly to the README/tracker
prose**, beyond the twelve controls above: 4206, 3105 (REF scan/publication
ms), 2188, 588 (CAND scan/publication ms), 112.3, 168.0 (REF latency
median/max), 1.9, 421.9 (CAND latency median/max), 4506, 3938 (scanserve cold
session completion REF/CAND), 122.2, 45.6 (scanserve cold median REF/CAND),
12/270 and 270/270 (REF cross-folder unsettled counts), 0 (CAND, every
cross-folder cell). One small nuance, not a finding: `scanserve`'s quoted
"1 692 → 1 697" (warm session completion) matches REF's **median** but CAND's
**mean** (median of that row is 1704.7); both readings say "flat," which is
the only claim resting on it, so this is noted rather than filed.
**Verdict: PASS.** No coherence violation (sabotage-tested), no lost request
under the shipped code (the "never re-ask" sabotage is the one that produces
a lost request, and it is not what shipped), no wrong mid-scan answer
(`mismatched_answers` 0 everywhere, in the dev's evidence and in two
independent re-runs this session generated). The tail's four higher cells are
characterized, attributed and estimated, not treated as a failure, per the
task's own framing. One real, non-blocking gap found and pinned by a new test
(`$/cancelRequest` against a `deferred` request outside its own batch is
silently ineffective — exactly-one-response is preserved, nothing is lost or
wrong) and one documentation inaccuracy (`includes.rs`'s cited line count).
**Handshakes/topo, for the lead:**
1. `server::index ──▶ state::scan` (`publish_is_due`) and
`server::mod ──▶ server::dispatch` (`names_nowhere`, `ask_again_if_empty`)
— as the dev already filed.
2. **New, from QA:** `docs/features/cancel-request/README.md`'s Assumptions
section ("a cancel arriving in a later burst than its request is dropped
… by then the request has been answered") is now incomplete: a request in
`Server::deferred` is neither `held` nor answered, and a cancel that
arrives in a batch that does not also carry a publish reuniting it with
`deferred` is dropped without effect, same as the general rule, but the
*reason* stated for that rule no longer covers every case it's applied to.
No code change needed (LSP allows ignoring a cancel; exactly-one-response
holds) — a one- or two-sentence dated amendment to `cancel-request`'s
Assumptions, cross-linked from `perf5r-publication`'s Handshakes, closes
the gap in the documentation rather than the code.
3. `lspclient.py`'s two hunks (`_arrived` timestamp map, `poll_answers`) are
additive and confirmed not to change `await_id`'s existing behaviour
(one line added that writes a stamp `await_id` never reads).
4. The cadence constant is `PUBLISH_EVERY = 512` (`state/scan.rs`),
deliberately equal to `HEAD_WALK_MAX`; both are now `pub(crate)`, tested
directly rather than against the number spelled out again.
TODO §61.4's QA line ticked below.
## Review
**2026-09-08 (lead).** Accepted, with one fix made by the lead and one
ruling.
- The probe came first and its first draft was thrown away for exactly
the reason the review warned about (it stopped sending in a lull). The
shipped one offers the same fixed load to both binaries, and what it
found is the number that mattered: a publish costs the size of the
index, not the batch, because `absorb` ends in a whole-index merge —
3.1 s of publication in a 4.2 s loaded warm scan whose quiet form is
1.0 s.
- The cadence is the boring answer and it lands: one merge per 512 files
instead of one per burst, the waiting drain exempt so the first useful
answer never moves; publication −78 to −88 %, loaded scans −48 to
−65 %, median wait 112 → 1.9 ms warm, served requests equal in every
cell, coherence intact (QA's sabotage of the candidates absorb fails
the agreement test).
- **Ruling on the tail.** Four single-buffer cells have a higher max
(worst 168 → 422 ms warm), attributed by QA to cadence spacing, not to
the deferral. A time bound on the cadence (T ≈ 100 ms while a request
waits) would give most of the publication win back, since the old
spacing was already ~120 ms. Not taken: the median and the completion
are what a user feels across a scan, and the max is one request per
session at a cost that stays under half a second. Recorded in the
tracker as the trade.
- The empty-answer rule closes §61.3's honest limit: `unsettled_answers`
0 in every cell, the cross-folder request answered with the right
location before or at settle, exactly once, and hover untouched.
- **Fixed by the lead (QA's finding):** a `$/cancelRequest` naming a
request in the deferred set was dropped, and the request later
answered normally. `process_batch` now takes a deferred request out and
answers it cancelled where the cancel lands; pinned by
`a_cancel_for_a_deferred_request_answers_it_cancelled_and_forgets_it`
(the request is planted, since a real deferral lives only inside a
running scan).
- `HEAD_WALK_MAX` is now pinned (QA's request from §61.3).
- Deviations accepted: the two additive `lspclient.py` hunks; the warm/
cold split of the probe for the guard; the `scanloadcross` phase.
Docs applied at merge: topo (the cadence, the `deferred` state and its
cancel rule, `HEAD_WALK_MAX`); the cancel-request README's dated entry;
the tail trade in the tracker.
+34
View File
@@ -301,6 +301,40 @@ attached.
## Work log
### 2026-09-08 — §61.4: how often a scan publishes, and what `[]` is worth
**Neither of these is a contract change.** The three tables are still published
together and never one of them; the order contract is `must_wait`'s and is
untouched; `INTERLEAVE_ABOVE` still decides which scans interleave at all. What
moved is *when* the drain pays for a publish, and what it does with an answer
that names nowhere (`docs/features/perf5r-publication/README.md`).
- **A publication cadence.** `answer_what_is_waiting` used to publish whenever
anything at all was waiting — one whole-index merge per burst of requests.
Measured under a definition every 100 ms on opentitan, that was 14 publishes
in a warm scan and 41 in a cold one, and `absorb` + `candidates` alone were
46 % of the warm session and 52 % of the cold one. It now publishes when
something was **waiting** — the startup's held requests, which is the
session's first useful answer and is never deferred — or when
`Scan::publish_is_due()` says `PUBLISH_EVERY` (512) records have been staged
since the last one. **A request may now read an older prefix; it can never
read an inconsistent one**, which is the distinction this feature's decision
1 rests on. A quiet scan still pays nothing at all: the cadence is asked only
when there is something for a publish to be for.
- **An empty navigation answer computed mid-scan is not an answer.** A
definition, a typeDefinition or a references that comes back `[]` while the
index is still growing cannot be told apart from "the scan has not reached
that file", so the request is put back and asked again at the next publish,
and at the latest when the scan ends — where `[]` is the honest answer and
goes out. This closes the case `perf5r-first-answer` pinned openly as its
honest limit (a target in the folder next door answered `[]` at the head
publish). It is a **rule in the drain**, not a second computation of the
answer: the response is computed once through the ordinary handler and either
sent or set aside, and a set-aside request is re-asked once per publish
rather than once per step. The deferred set is deliberately **not** part of
`must_wait` — a hover, a completion or a code action behind a deferred
definition is answered exactly as before, and one is pinned.
### 2026-09-08 — §61.3: a scan that owes itself the rest of its own scope
The coherence contract is untouched — the three tables are still published
+81 -1
View File
@@ -2016,7 +2016,7 @@ checks in its full experiment record. Targets are proposed gates, not promises.
| R3a | Engine-owned empty-cursor preflight avoids whole-workspace materialization | no-symbol refusal 2,192 ms; 3,975 parses, candidate-only trace | ≤16 ms; zero closed-workspace parses; exact refusal/precedence | dev (Opus), §61.1, tree at `e13ae4c` + the §61.1 diff | **0.3 ms** repeat median (paired reference 2,012.3 ms, −100.0%); `trace_parses` **0**, `trace_selected` **0** off the wire; refusal byte-identical; peak RSS 909 → 429 MiB. [Record R3a-2026-09-08](#experiment-record--r3a-2026-09-08-stage-r3a); `~/.cache/lucisv-perf/take5r-1/` | Retained — QA PASS → lead; committed 2026-09-08 |
| R3b | Reuse valid source analysis and reduce initial scope construction | tail rename 398.3 ms; traced index stage 229.2 ms; 238 selected files | ≥20% wire improvement milestone; same edits/warnings/refusals; bounded RSS | — | — | Pending |
| R3c | Profile broad fallbacks, warnings and refused extraction before optimizing | common port 3,455 ms; tail warning stage 50.9 ms; extract refusal 804.9 ms | measured work reduction; no weaker selection or verification | dev (Opus), §61.1 — **refused-extraction half only**; the broad fallbacks and the warning stage remain open for §61.5 | Extract refusal **761.1 → 767.8 ms (+0.9%, unchanged)**: its stage is `boundary::Crossing::read`, which needs `flow::read(&scope, …)` for instantiated-module port directions, so no bounded preflight reaches it. A region-local preflight was built, measured and **removed** — `site_at` (= `extract_site_in`) already answers the parse and `Region::read` refusals, and `plain_identifier`/occupied are already ahead of `Extraction::plan`. New phase `extractrefuse`. [Record R3c-x-2026-09-08](#experiment-record--r3c-x-2026-09-08-stage-r3c-extraction-half) | **Reject** the preflight (no work to remove); **defer** the 805 ms to §61.5's scope reuse |
| R4 | Separate publication overhead from quiet scan decode/merge cost | quiet cold/warm 2,907/1,118 ms; scanserve max 337/328 ms | same offered load; improve queue latency and completion; warm quiet ≤1 s | — | — | Pending |
| R4 | Separate publication overhead from quiet scan decode/merge cost | quiet cold/warm 2,907/1,118 ms; scanserve max 337/328 ms | same offered load; improve queue latency and completion; warm quiet ≤1 s | dev (Opus), §61.4, tree at `eb54042` + the §61.4 diff | **Measured first, and the split named a different lever than the plan.** New phase `scanload` — a definition every 100/250 ms of **wall clock**, a fixed count of them, so both binaries are offered the same load. At `eb54042`, warm, one open buffer, 100 ms: **34 publishes**, `absorb` **2 433 ms (78 %)**, `candidates` **623 (20 %)**, `includes` 47, `overlay` **2.4 (0.08 %)** — **3 105 ms of publication in a 4 206 ms scan** whose quiet form is 1 005 ms; cold **7 973 of 10 675** against 2 766 quiet. `absorb` dominates because it ends in a whole-index merge; the **overlay refresh is not a lever** (0.08 % at 1 buffer, 9.6 % at 101), so the selective refresh the plan asked for was **not built**. Shipped instead: a **publication cadence** (`PUBLISH_EVERY` 512, the first-answer drain exempt). Same offered load, requests answered equal in every cell: publication **−78 to −88 %**, traced scan **−48 to −65 %**, median wait **−98 to −99.5 %** (warm 112.3 → 1.9 ms; cold at 2+ buffers 4 706 → 2.1). Tail improved in **10 of 16** loaded cells, level in 2, higher in 4 — three of them single-open-buffer cells (worst warm 168 → 422 ms), against cold 101 buffers 9 308 → 1 583. Quiet warm scan **1 005 → 985 ms**, quiet cold 2 724 → 2 694. `scanserve` cold median **122.2 → 45.6 ms**, same 13 requests served; quiet `scan` matrix, the first useful answer (78.2 → 80.8 cold, 115.1 → 115.8 warm), idle RSS (−0.2 %), the store size and 24 of 24 scope cells all unchanged. `mismatched_answers` **0** and `unsettled_answers` **0** everywhere — including a new **cross-folder** cell where the reference is unsettled **12 of 270** with one buffer open and **270 of 270** with eleven, and the candidate **0 of 270** in both. Also here: the lead's §61.3 empty-answer ruling and the `HEAD_WALK_MAX` fixture. [Record R4-2026-09-08](#experiment-record--r4-2026-09-08-stage-r4); `~/.cache/lucisv-perf/take5r-4/` | Retained — QA PASS → lead; the single-buffer tail (max 168 → 422 ms warm, cadence spacing) accepted as the trade for median −98 % and completion −48 to −65 %; a cancel-while-deferred fix by the lead; committed 2026-09-08 |
Maintain the successful P3 CLI result as a control: 7,751 style diagnostics,
byte-identical stdout, about 490 ms wall / 2.44 s user CPU here. Preserve the
@@ -2575,3 +2575,83 @@ before implementation; no verifier forgiveness may be weakened for speed.
to §61.5 (R3b/R3c scope reuse) with its stage identified.
- **QA result and lead review link:** pending —
`docs/features/perf5r-preflight/README.md`.
## Experiment record — R4-2026-09-08 (stage R4)
- **Experiment ID / stage / date / owner:** `R4-2026-09-08` / R4 (TODO §61.4)
/ 2026-09-08, America/Chicago / dev agent (Opus).
- **Hypothesis and exact expected work reduction:** the review's §4 — "first
add a fixed-arrival-rate probe and record publication/overlay costs alongside
queue latency and scan completion", then "test incremental table construction
or reduced duplicate publication work, preserving the coherent-prefix
contract". No number was expected of the probe; the *reductions* the work
order named were the candidates rebuild, a selective overlay refresh and a
bounded publish cadence, in that order.
- **Reference commit, candidate commit or diff hash, binary hashes:** reference
trunk `eb54042`, sha256 `f7a5a27eec773eca…` (`REF`). Candidate `CAND` = that
tree + the whole §61.4 diff, sha256 `4af863c145dc4d4b…`. Release,
`cargo build --release --locked`.
- **Files changed / API contracts amended / topology references:**
`tools/perf/phases_r4.py` (new — `scanload`, `scanloadcold`, `scanloadcross`,
`scanloadprobe`), `tools/perf/lspclient.py` (two additive hunks: an arrival
stamp in the reader thread and `Session.poll_answers`), `bench.py`
(registration), `tools/perf/README.md`;
`crates/lucisv_server/src/state/scan.rs` (`PUBLISH_EVERY`,
`Scan::publish_is_due`, additive), `state/discover.rs` and `state/mod.rs`
(visibility only; no production line added to `state/mod.rs`),
`server/index.rs` (the drain's publish decision, `answer_what_was_deferred`),
`server/mod.rs` (`Server::deferred` and the rule's call site),
`server/dispatch.rs` (`NAVIGATION`, `names_nowhere`, `ask_again_if_empty`,
`say_deferred`), `server/startup.rs` (one field), `server/tests/startup.rs`.
**`candidates.rs` and `includes.rs` are unchanged** — see the decision.
No cross-crate contract amended; `WorkspaceIndex::absorb` is called with the
same arguments, fewer times. Amended in their own READMEs, rules unchanged:
`scan-interleave` (a dated entry for the cadence and the empty-answer rule),
`perf5r-first-answer` (its cross-folder `[]` is now answered here).
- **Workload, corpus/input hashes, open files, cursor, capabilities:**
OpenTitan `0098135264` with its three known modified files,
`git status --porcelain` checked after every phase.
`lucisv.index.scope: "workspace"`, `--verbose`, the `aes #(` cursor in
`sites.TB` for `scanload`/`scanserve` and the cross-folder `tl_if` cursor for
`scanloadcross`. 1 / 2 / 11 / 101 open buffers.
- **Machine, profile, load, competing activity:** M1 Max, macOS 27.0, release,
default worker count. One-minute load 2.0–3.6 across the timed phases (13.1
at session start, before any measurement; the first probe run was taken after
it fell). No cargo command during a timed run.
- **Commands, cache state, trial ordering, fresh sessions:**
`tools/guard.sh -m 8 -t 1800 -- python3 tools/perf/bench.py <phase> …
--tries 3`; `scanload`/`scanloadcold` REF then CAND, the remaining phases
CAND then REF (the alternation the protocol asks for). Three fresh processes
per cell; the store deleted before every cold session.
- **Results:** in `docs/features/perf5r-publication/README.md` — the R4
baseline split, the paired warm and cold tables, `scanserve`, the quiet
matrix, the scope cells, RSS and the cross-folder cell. Headline: warm one
buffer at 100 ms, publication **3 105 → 588 ms** and the traced scan
**4 206 → 2 188**; cold **7 973 → 922** and **10 675 → 3 686**; median wait
**112.3 → 1.9 ms** warm and **137.7 → 1.5** cold; publishes **34 → 4.7** warm
and **88 → 7** cold.
- **Two metrics that must not be read as one:** `scan ms` is the server's own
traced scan wall time and is the honest completion figure. The probe's
`settled_ms` is floored by the fixed request window whenever the session
finishes inside it, so it *understates* the gain (warm one buffer:
4 215 → 3 417, −19 %, against the scan's −48 %); `mid_scan_*` misclassifies
post-settle answers for the same reason and is not quoted. Neither is needed:
both binaries are offered the identical request count over the identical
window and answer all of them.
- **Result parity:** requests offered and requests answered equal in **every**
paired cell; `mismatched_answers` 0 and `unsettled_answers` 0 on `scanload`,
`scanloadcold` and `scanserve` for both binaries, cold and warm.
- **Guard outcome:** no kill. The first paired `scanload` attempt was **stopped
by hand** when its projected wall time approached the 1 800-second limit, and
the phase was split into a warm and a cold half rather than the limit raised;
its partial output is kept as `paired-partial-firstattempt.jsonl` and no
number is taken from it.
- **Decision:** **retain** the cadence and the empty-answer rule. **Reject**
the selective overlay refresh — 0.08 % of publication at one open buffer, and
the intersection it needs would cost more than it saves. **Defer** an
incremental candidates rebuild and a targeted `WorkspaceIndex::absorb`: the
cadence takes both down with it, and the second is a `vlog_semantic` change
this lane's file list excludes. `absorb`'s whole-index merge is named as the
next lever for whoever owns that crate next.
- **QA result and lead review link:** pending —
`docs/features/perf5r-publication/README.md`.
+1 -1
View File
@@ -555,7 +555,7 @@ promise:
| `dut-hierarchy ──▶ vscode-hierarchy-sidebar` | depends | TODO §56 (2026-09-06): `hierarchySections.js` consumes the sidebar's model (`rootNode`, the reverse instance index memoised on the model) and its webview renderer's row menu; no edge to any Rust crate — the server is untouched. |
| `coverage-gaps-l` (TODO §54, 0.49.0) | lane | Touches `vlog_parser` (ast + parser + the `randsequence` keyword in the token table), `vlog_formatter` (arms, `[format] uvm-utils-indent`), `vlog_semantic` (bind arms), `vlog_linter`, `vlog_refactor` (match arms), `lucisv_core` (the config key), `lucisv_server` (settings, format) and `editors/vscode` (the setting, the regenerated grammar). New AST: `StmtKind::{EventTrigger, Let, RandSequence}`, `ExprKind::StreamWith`, `DataDecl::strength`, `ClockingSkew`; `size_pins` unmoved. |
| `hover-line-index ──▶ port-detail-spans / index-persistence` | depends + handshake | `DeclLines { name, detail }` rides each indexed `Decl`, so ordinary and split-port hover headings do not reread a file just to compute a line. The record grew again and **`FACTS_FORMAT` went 3 → 4**; the server's bounded `FileView` cache supplies the text/`LineIndex` only when a snippet or a non-indexed position still needs it. Its four invalidation points are `set_document`, `close_document`, `update_one`, and a whole rebuild. |
| `scan-interleave ◀──▶ workspace-index` | handshake | A scan is a stepped `Scan` value; staged `FileFacts` land through `WorkspaceIndex::absorb`, one whole-index merge per queue drain rather than per file. `Candidates::absorb` and (until perf5-p4, `IncludeGraph::absorb`; since 2026-09-08 the graph is rebuilt from each file's staged include list, `IncludeGraph::from_includes`, read in the file's own step) publish their tables in the same drain, so “the workspace as far as scanned” cannot mean three different prefixes. **Amended by perf5-p4 (2026-09-08):** the startup is staged behind the `workspace/configuration` answer with a 2 s bound (`server/startup.rs`), so there is one startup scan at the answered scope and no empty default-scope scan (perf5r-first-answer, 2026-09-08: plus `OPENING_FILE_WAIT`, 25 ms inside that window, spent only by a workspace session whose opening burst holds no `didOpen`; and the scan is discovered in two phases when it pays — the open buffers' raised folders walked, stepped and published first, the rest of the scope walked as a zero-file step afterwards, `state/discover.rs::first_scope` + `PendingDiscovery`; bounded to rung 2, a raised folder that is a strict descendant of a root, at most `HEAD_WALK_MAX` = 512 files, and the session's first scan — otherwise today's single walk); the scan reads each file's text in its own step (`Scan::take_text`, never the whole corpus up front) and orders the work list open buffers → their raised folders → the rest (`scan_order.rs`); `must_wait` gains `staging` and `head_owed` — a held opening request is answered inside the startup scan once the buffers' folder head is published, never off a one-file prefix; the store is opened at the first step that needs it and not rewritten when it was loaded canonical and nothing was appended (`index_cache.rs::already_compact`); `state.rs` is now `state/mod.rs` + `state/scan.rs` (a pure move). The rescan order contract (decision 2) is unchanged. |
| `scan-interleave ◀──▶ workspace-index` | handshake | A scan is a stepped `Scan` value; staged `FileFacts` land through `WorkspaceIndex::absorb`, one whole-index merge per queue drain rather than per file. `Candidates::absorb` and (until perf5-p4, `IncludeGraph::absorb`; since 2026-09-08 the graph is rebuilt from each file's staged include list, `IncludeGraph::from_includes`, read in the file's own step) publish their tables in the same drain, so “the workspace as far as scanned” cannot mean three different prefixes. **Amended by perf5-p4 (2026-09-08):** the startup is staged behind the `workspace/configuration` answer with a 2 s bound (`server/startup.rs`), so there is one startup scan at the answered scope and no empty default-scope scan (perf5r-first-answer, 2026-09-08: plus `OPENING_FILE_WAIT`, 25 ms inside that window, spent only by a workspace session whose opening burst holds no `didOpen`; and the scan is discovered in two phases when it pays — the open buffers' raised folders walked, stepped and published first, the rest of the scope walked as a zero-file step afterwards, `state/discover.rs::first_scope` + `PendingDiscovery`; bounded to rung 2, a raised folder that is a strict descendant of a root, at most `HEAD_WALK_MAX` = 512 files, and the session's first scan — otherwise today's single walk); the scan reads each file's text in its own step (`Scan::take_text`, never the whole corpus up front) and orders the work list open buffers → their raised folders → the rest (`scan_order.rs`); `must_wait` gains `staging` and `head_owed` — a held opening request is answered inside the startup scan once the buffers' folder head is published, never off a one-file prefix; **perf5r-publication (2026-09-08):** a scan publishes at most once per `PUBLISH_EVERY` = 512 staged files (the drain with something waiting exempt, so the first useful answer never moves) — a request between publishes reads a coherent prefix at most that far behind; an empty navigation answer (definition, typeDefinition, references) computed while a scan runs is put in `Server::deferred` and asked again at the next publish and at the latest at scan end (`deferred` is not in `must_wait`, so hover is unaffected), and a `$/cancelRequest` naming a deferred request answers it cancelled where the cancel lands (`cancel_deferred`); `HEAD_WALK_MAX` pinned by test; the store is opened at the first step that needs it and not rewritten when it was loaded canonical and nothing was appended (`index_cache.rs::already_compact`); `state.rs` is now `state/mod.rs` + `state/scan.rs` (a pure move). The rescan order contract (decision 2) is unchanged. |
| `scan-interleave ──▶ hover-line-index` | depends | Delivers hover-line-index's measured startup-wait request: a startup scan above 64 files drains queued messages between files. A rescan deliberately still holds requests; what an answer sees never depends on elapsed wall time. |
| `index-scope ──▶ scan-interleave` | depends | A scope widen is the second `Scan` shape (`begin_widen`) and shares `scan_step`/`finish_scan`; it folds only newly reached folders plus open-buffer analyses, never masquerades as a whole scan, and never interleaves. Folder scope now ships at depth 2; rootless sessions do not climb an unnamed tree. |
| `index-scope ──▶ one-parse / completion-core` | depends | Whole scans and widens reuse each open `Document`'s existing `FileFacts` and completion words rather than reparse its text. `IndexEvent::Analyzed` keeps this distinct from a persistent-cache hit. |
+4
View File
@@ -23,6 +23,7 @@ and take 5 §P0 (TODO §60.0) corrected what some rows *meant*: see
| `phases_p2.py` | take 5 §P2's phase: `renametrace` — eight renames, each with the server's own `timing: rename trace …` line read back off `window/logMessage` and written out as row fields (which rung selected each file, per-stage ms, per-stage **whole-file parse counts**) beside the wire time and the peak RSS |
| `phases_r1.py` | the review round's §R1 phases: `actionprofile` (the `timing: codeaction …` stage split at three cursors × four request shapes), `ruleablation` (one row per default-on rule, `lucisv.lint.select` pushed between rows) and `snapshotrss` (idle RSS at 1 / 10 / 100 buffers, each asked for quick fixes so every one holds a lint snapshot) |
| `phases_p4.py` | take 5 §P4a's phases: `scanprofile` (the startup breakdown, one row per traced scan), `scanwait` (the first useful answer with that session's own trace beside it) and `scanserve` (a definition every 200 ms for as long as the scan runs, with the mid-scan/settled answer coherence check) |
| `phases_r4.py` | the review round's §R4 phases: `scanload` / `scanloadcold` (a definition every 100 or 250 ms of **wall clock**, a fixed number of them, with the server's own publication split in the row), `scanloadcross` (the same load at a cursor the open buffer's folder cannot answer) and `scanloadprobe` (one cell, for checking the probe itself) |
| `sweep.sh` | the timed CLI sweeps (`format --check`, `check`) over five trees, `/usr/bin/time -l` |
| `sweeptable.py` | those logs → the document's §7 Markdown table, plus the format-cache hits each try reported |
| `outcomes.sh` | the untimed per-file outcome runs, for the release-to-release outcome diff |
@@ -89,6 +90,9 @@ apart in `results.jsonl`; run each phase once per binary.
| `actionprofile` | §R1b | one `--verbose` session per cursor, four request shapes each — the first menu of the session, three repeats on the unchanged buffer, a definition queued behind it, and the first menu after each of three `didChange`s — with the server's own `timing: codeaction …` line parsed into `trace_*` fields. Two groups per line: `flush{…}` is the debounced `Document` rebuild and the diagnostics publish inside it, `action{…}` is the handler. A request that lints nothing logs no line, which is why the queued rows say how many the follower logged |
| `ruleablation` | §R1b | *which* rules the pinmux quickfix menu's milliseconds are in: one warm session, `lucisv.lint.select` pushed to a single rule per row by `didChangeConfiguration` (a selection change rescans nothing), the unrestricted control taken first **and** last so session drift is visible rather than blamed on a rule |
| `snapshotrss` | §R1a | idle and peak RSS with 1 / 10 / 100 open buffers, each sent one quickfix-only `codeAction` so that every open document holds a lint snapshot — the memory bound of `docs/features/perf5r-lint-snapshot/README.md`. `rss_kib` / `peak_rss_kib`, never `ms` |
| `scanload` | §R4 | **the controlled form of `scanserve`.** A `textDocument/definition` every 100 and every 250 ms of wall clock, counted from the session's start and **independent of the responses** — a fixed number of them, so both binaries are offered exactly the same load and a faster one shows it as answers arriving *after* settle rather than as requests never sent. Warm cache, 1 / 2 / 11 / 101 open buffers, three fresh sessions a cell, plus a **quiet control** (the same cell, no requests) so a settle time that moved because of the load can be told from one that moved anyway. Each row carries every request's own wait (median and max, and the same two over the mid-scan subset), how many were answered before settle, `mismatched_answers` and `unsettled_answers`, the settle time, `tick_jitter_ms` (how a reader checks the arrival discipline the row claims) and, from the session's own `--verbose` trace, `publishes`, `published` and the four `publish_*` stages |
| `scanloadcold` | §R4 | `scanload` with the index store deleted before every session. A separate phase because a cold cell under this load is a ten-second session, and eight of them do not fit inside the 1 800-second guard — splitting the run is the answer to that, raising the guard is not |
| `scanloadcross` | §R4 | `scanload` at a cursor whose target is **outside** the open buffer's own folder (`tl_if`, declared in `hw/dv/sv/tl_agent`), which is the case the empty-answer rule of `docs/features/perf5r-publication/README.md` is for: in a server without that rule it is answered `[]` at the head publish, and the row says what the rule costs those requests and what it buys |
| `probe` | — | ad-hoc: `--probe FILE:LINE:CHAR` (0-based) prints what a cursor offers. This is how `sites.REFACTOR_SITES` was found |
## The CLI sweeps
+1
View File
@@ -39,6 +39,7 @@ import phases_p2 # noqa: E402,F401 — registers take 5 §P2's phases
import phases_p4 # noqa: E402,F401 — registers take 5 §P4's phases
import phases_r1 # noqa: E402,F401 — registers the review round's R1 phases
import phases_r3 # noqa: E402,F401 — registers the review round's R3 phase
import phases_r4 # noqa: E402,F401 — registers the review round's R4 phases
# =========================================================================
+35
View File
@@ -85,6 +85,13 @@ class Session:
self.server_requests = [] # every server->client request, answered
self.applied = [] # captured workspace/applyEdit pushes, in order
self.pending = {} # id -> (method, sent_at) for in-flight requests
#: id -> the `perf_counter` instant the reader thread parsed the
#: response. Stamped where the bytes land rather than where a caller
#: gets round to looking, so a probe holding many requests in flight
#: at once measures each one's own wait and not its own poll interval
#: (`phases_r4.py`). Entries are consumed by [`Session.poll_answers`];
#: `await_id` neither reads nor needs them.
self._arrived = {}
self.proc = None
self._reader = None
self._lock = threading.Lock()
@@ -172,6 +179,8 @@ class Session:
def _dispatch(self, message):
with self._cond:
if "method" not in message and message.get("id") is not None:
self._arrived[message["id"]] = time.perf_counter()
self._inbox.append(message)
self._cond.notify_all()
# Server->client requests must be answered from the reader thread, or
@@ -253,6 +262,7 @@ class Session:
self._inbox.pop(i)
done = time.perf_counter()
_, sent = self.pending.pop(rid)
self._arrived.pop(rid, None)
self._drain_locked()
return (done - sent) * 1000.0, message
self._drain_locked()
@@ -269,6 +279,31 @@ class Session:
"""Just the round trip in milliseconds."""
return self.request(method, params, timeout)[0]
def poll_answers(self):
"""Take every response that has arrived, without waiting for any.
The pipelining half of [`Session.await_id`]: a probe that sends on a
clock rather than after the previous answer holds many requests in
flight at once and must not block on the oldest of them. Each entry is
`(rid, method, elapsed_ms, arrived)` plus the message, with `elapsed`
measured from the write to the instant the **reader thread** parsed the
response, so the caller's poll interval is not in the number.
"""
out = []
with self._cond:
kept = []
for message in self._inbox:
rid = message.get("id")
if "method" in message or rid not in self.pending:
kept.append(message)
continue
method, sent = self.pending.pop(rid)
arrived = self._arrived.pop(rid, None) or time.perf_counter()
out.append((rid, method, (arrived - sent) * 1000.0, arrived, message))
self._inbox[:] = kept
self._drain_locked()
return out
# -- notification bookkeeping -----------------------------------------
def _drain_locked(self):
+314
View File
@@ -0,0 +1,314 @@
#!/usr/bin/env python3
"""Review round §R4: what a startup scan costs while requests keep arriving.
Imported by `bench.py`, which owns the registry and the command line.
`scanserve` (`phases_p4.py`) sends the next definition 200 ms **after the
previous response**, so a server that answers faster is asked more often and
its session-completion time is not comparable between two binaries. The review
(`docs/performance_take5_review.md` §4, "Startup throughput and responsiveness
must be judged separately") asks for the controlled form instead: a **fixed
arrival rate**, the same offered load whatever the server does with it.
`scanload` is that probe.
- **The clock, not the answers.** A definition goes out every `rate` ms of wall
time counted from the session's own start, whether or not the previous one
has been answered. Requests pipeline; a server that stalls accumulates them,
which is the queue latency this is here to see.
- **Every request's own wait.** `Session.poll_answers` stamps a response where
the reader thread parses it, so a request answered while the probe is busy
sending the next one is not charged for the probe's poll interval.
- **The publication split beside it.** The session runs `--verbose`, so the
server's own `timing: scan <n> stages/counts` lines give `publishes`,
`published` and the four `publish_*` stages
(`docs/features/perf5-p4/README.md`) for the very session whose latencies are
in the row.
- **A quiet control in the same series.** The same cells with no requests at
all, so a settle time that moved can be told apart from a settle time that
moved *because requests arrived*.
Buffer counts are **extra** buffers: the cursor's own file (`sites.TB`) is
always open, because the definition is asked in it. So "0" is one open buffer
and "100" is 101, which is the same convention `scanprofile` uses.
"""
import os
import statistics
import time
from harness import ARGS, at, phase, record, session, sites
from phases_p4 import QUIET, rtl_files, scan_chatter, traces
#: Arrival rates, in milliseconds between two definitions.
RATES = (100, 250)
#: Extra open buffers per cell, beside the cursor's own.
BUFFERS = (0, 1, 10, 100)
#: How long the probe keeps offering, per cache state, in milliseconds.
#:
#: **A fixed window, not "until the scan goes quiet".** The first draft stopped
#: sending when the server stopped saying things, which made the offered load a
#: function of the server — a faster binary was asked fewer times, which is the
#: very confound `scanserve` has and this phase exists to remove. The window is
#: instead long enough to cover the *reference's* whole loaded session (cold
#: 5.9-9.2 s, warm 2.0-3.4 s measured at `eb54042`), so both binaries are asked
#: exactly the same number of times and a binary that finishes sooner shows it
#: as requests answered **after** settle rather than as requests never sent.
WINDOW_MS = {"cold": 9000, "warm": 3500}
#: A request still in flight after the scan settled is waited for this long.
DRAIN_TIMEOUT = 60.0
#: The four `publish_*` stages, in the order `ScanTrace::stage_line` writes.
PUBLISH_STAGES = ("publish_absorb", "publish_candidates", "publish_includes",
"publish_overlay")
def open_buffers(s, extra):
"""Open the cursor's own file and `extra` more. Returns the start instant."""
started = time.perf_counter()
s.did_open(sites.path(sites.TB))
for path in extra:
s.did_open(path if os.path.isabs(path) else sites.path(path))
return started
def take_answers(s, answers, origin):
"""Move every response that has arrived into `answers`, timestamped."""
for rid, _method, elapsed, arrived, message in s.poll_answers():
answers.append({
"rid": rid,
"ms": elapsed,
"at": (arrived - origin) * 1000.0,
"result": message.get("result"),
})
def offer(s, rate_ms, ticks, params, origin, answers):
"""Send `ticks` definitions, one every `rate_ms`, and watch for silence.
The tick is counted from `t0` in whole periods rather than accumulated from
the last send, so a slow iteration cannot make the offered load drift; the
largest gap between a tick's due instant and its write is reported as
`tick_jitter_ms`, which is how a reader checks the arrival discipline the
row claims. **The count is fixed**, so what the server does with a request
cannot change how many it is asked. Returns `(sent, jitter_ms, quiet_at)` —
`quiet_at` being the last instant the *scan* said anything.
"""
t0 = time.perf_counter()
sent, jitter = 0, 0.0
seen, quiet_at = scan_chatter(s), t0
while sent < ticks:
now = time.perf_counter()
due = t0 + sent * rate_ms / 1000.0
if now >= due:
s.send("textDocument/definition", params)
jitter = max(jitter, (time.perf_counter() - due) * 1000.0)
sent += 1
take_answers(s, answers, origin)
chatter = scan_chatter(s)
if chatter != seen:
seen, quiet_at = chatter, now
time.sleep(0.002)
return sent, jitter, quiet_at
def drain_answers(s, answers, origin):
"""Wait, bounded, for the requests still in flight when the scan ended."""
deadline = time.time() + DRAIN_TIMEOUT
while s.pending and time.time() < deadline:
take_answers(s, answers, origin)
time.sleep(0.002)
take_answers(s, answers, origin)
return len(s.pending)
def settled_at(s, quiet_at, origin):
"""Milliseconds from `origin` to the session's **last** notification.
Not "when the probe stopped asking, minus a quiet window": the offered load
runs for a fixed window that may end before the session does or long after
it, so both halves are taken into account — the last chatter the send loop
saw, and anything `wait_quiet` sees after it.
"""
entered = time.perf_counter()
more = s.wait_quiet(QUIET)
last = entered + more / 1000.0 if more > 0.0 else quiet_at
return (last - origin) * 1000.0
def one_session(s, rate_ms, ticks, extra, params):
"""One fresh session under a fixed offered load. Returns its measurements."""
s.initialize()
origin = open_buffers(s, extra)
answers = []
sent, jitter, quiet_at = offer(s, rate_ms, ticks, params, origin, answers)
unanswered = drain_answers(s, answers, origin)
settle = settled_at(s, quiet_at, origin)
settled_answer = s.request("textDocument/definition", params)[1].get("result")
scans = traces(s)
return {
"sent": sent,
"jitter": jitter,
"settle": settle,
"answers": answers,
"unanswered": unanswered,
"settled_answer": settled_answer,
"scans": scans,
}
def publication(scans):
"""The first whole scan's publication counts and per-stage milliseconds."""
if not scans:
return {}
stages = scans[0].get("stages") or {}
counts = scans[0].get("counts") or {}
out = {stage: stages.get(stage, 0.0) for stage in PUBLISH_STAGES}
out["publish_total"] = sum(out.values())
out["publishes"] = counts.get("publishes", 0)
out["published"] = counts.get("published", 0)
out["first_publish"] = counts.get("first_publish", 0.0)
out["scan_total"] = stages.get("total", 0.0)
return out
def summary(runs):
"""Every session's rows folded into the one the cell records."""
latencies = sorted(a["ms"] for run in runs for a in run["answers"])
inside = sorted(a["ms"] for run in runs for a in run["answers"]
if a["at"] <= run["settle"])
mid = len(inside)
mismatched = sum(1 for run in runs for a in run["answers"]
if a["result"] and a["result"] != run["settled_answer"])
unsettled = sum(1 for run in runs for a in run["answers"]
if a["result"] != run["settled_answer"])
answered = len(latencies)
return {
"ms": latencies,
"latency_median_ms": statistics.median(latencies) if latencies else 0.0,
"latency_max_ms": max(latencies) if latencies else 0.0,
"mid_scan_median_ms": statistics.median(inside) if inside else 0.0,
"mid_scan_max_ms": max(inside) if inside else 0.0,
"requests_sent": [run["sent"] for run in runs],
"requests_answered": answered,
"mid_scan_answers": mid,
"after_settle_answers": answered - mid,
"unanswered_requests": sum(run["unanswered"] for run in runs),
"mismatched_answers": mismatched,
"unsettled_answers": unsettled,
"settled_ms": [run["settle"] for run in runs],
"tick_jitter_ms": max((run["jitter"] for run in runs), default=0.0),
"publication": [publication(run["scans"]) for run in runs],
}
def cell_status(got):
"""A cell is a finding when an answer disagreed or a request went missing."""
if not got["ms"]:
return "error", "no request was answered at all"
if got["mismatched_answers"]:
return "error", "%d mid-scan answers disagreed with the settled index" % (
got["mismatched_answers"])
if got["unanswered_requests"]:
return "error", "%d requests were never answered" % got["unanswered_requests"]
return "ok", None
NOTE = (
"ms is every request's own wait, sorted, across all tries; the arrival "
"rate is wall-clock and independent of the responses (`tick_jitter_ms` is "
"the largest slip); `publication` is each try's first traced scan — the "
"four publish_* stages, the publish count and the files published; "
"`mismatched_answers` is the coherence contract of "
"docs/features/index-scope/README.md, `unsettled_answers` the review §2 "
"gate (every answer, empty ones included, equal to the settled one)"
)
QUIET_NOTE = (
"the control: the same cell with no requests at all, so a settle time "
"that moved can be told from one that moved because requests arrived. "
"ms is the session's completion time, not a request latency"
)
def load_cell(cache, buffers, rate, params, where=""):
"""One cell: `--tries` fresh sessions under the same fixed offered load."""
extra = rtl_files(buffers)
ticks = WINDOW_MS[cache] // rate if rate else 0
runs = []
for _ in range(ARGS.tries):
with session("workspace", cold=(cache == "cold"), verbose=True,
storage_name="r4-load") as s:
runs.append(one_session(s, rate, ticks, extra, params))
got = summary(runs)
if not rate:
record(phase="scanload",
row="quiet control, %s cache, %d extra buffer(s)" % (cache, buffers),
fresh_process=True, result_count=0, rate_ms=0,
ms=got["settled_ms"], settled_ms=got["settled_ms"],
publication=got["publication"], open_buffers=buffers + 1,
note=QUIET_NOTE)
return
status, message = cell_status(got)
got["ms"] = got["ms"] or [0.0]
record(phase="scanload",
row="%sdefinition every %d ms, %s cache, %d extra buffer(s)"
% (where, rate, cache, buffers),
fresh_process=True, status=status, message=message,
result_count=got["requests_answered"], requests_offered=ticks,
rate_ms=rate, open_buffers=buffers + 1, note=NOTE, **got)
def every_cell(cache):
"""Both rates and the quiet control at every buffer count, for one cache."""
params = at(sites.TB, " aes #(", 1, 2)
for buffers in BUFFERS:
for rate in RATES:
load_cell(cache, buffers, rate, params)
load_cell(cache, buffers, 0, params)
@phase("scanload")
def phase_scanload():
"""A definition every N ms of wall clock, for the whole **warm** scan.
Warm and cold are two phases rather than one because a cold cell under this
load is a 10-second session and eight of them do not fit inside the
1 800-second guard every perf command runs under. Splitting the *run* is
the answer to that; raising the guard is not (`tools/guard.sh`).
"""
every_cell("warm")
@phase("scanloadcold")
def phase_scanloadcold():
"""[`phase_scanload`] with the index store deleted before every session."""
every_cell("cold")
@phase("scanloadprobe")
def phase_scanloadprobe():
"""One warm cell only — the fast loop for checking the probe itself."""
load_cell("warm", 1, 100, at(sites.TB, " aes #(", 1, 2))
@phase("scanloadcross")
def phase_scanloadcross():
"""The same fixed load at a cursor the open buffer's own folder cannot answer.
`scanload`'s cursor names a module in `hw/ip/aes/rtl`, which the head walks
first — so it is non-empty from the first publish and the empty-answer rule
never fires on it. This one names an interface declared in
`hw/dv/sv/tl_agent`, which the head does not hold: in the reference it is
answered `[]` at the head publish and only becomes right once the scan has
reached that folder. It is what the rule costs (a longer wait for those
requests) and what it buys (`unsettled_answers`, which is the review's own
gate), measured rather than argued.
"""
params = at(sites.TB, "tl_if tl_if (", 1, 0)
for cache in ("cold", "warm"):
for buffers in (0, 10):
load_cell(cache, buffers, 100, params, where="cross-folder ")