Files
lucisv/crates/lucisv_server/src/server/tests/large_file.rs
T
lucioandClaude Fable 5 b96827c51d Decomposition, lane C: lucisv_server's server.rs and completion.rs become modules, a pure move
TODO section 28, lane C (the file-size rule in CLAUDE.md).
server.rs (2 559 production + 6 293 test lines) becomes server/{mod,
dispatch, client, index, notification, progress, diagnostics, batch,
formatting, large_file, semantic_tokens}.rs with the tests in
server/tests/ (16 files, one per former banner section, 15 shared
helpers hoisted into the harness); completion.rs (1 716 + 2 463)
becomes completion/{mod, member, module, tiers, word, site,
harness}.rs with each provider's tests beside it. answer_request (393)
and handle_notification (197) stay whole as the dispatch tables they
are; perf.rs stays whole because its one sentence has no and. Every
import elsewhere in the crate resolves through pub(crate) re-exports,
so main.rs, inline.rs, instantiate.rs, hover.rs, nav.rs and state.rs
are byte-identical. Proof: per-binary counts identical (1 435 / 85 / 3;
workspace 3 215 / 48), e2e and the vsix smoke green, a live LSP session
against opentitan answering byte-identically from this build and the
base, and a line-multiset + signature census (360/360, 188/188) done
by the dev and redone from scratch by QA.

docs/features/decomposition-server/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 21:33:48 -07:00

422 lines
18 KiB
Rust

//! The large-file fast path (`docs/features/large-file-mode/README.md`).
use super::*;
// ------------------------------------------------------------------
// the large-file fast path (`docs/features/large-file-mode/README.md`)
// ------------------------------------------------------------------
/// A session whose fast path starts at 100 bytes, so a test buffer can be
/// three lines long instead of four megabytes.
fn fast_path_settings() -> ClientSettings {
ClientSettings { large_file_threshold: 100, ..Default::default() }
}
/// A source file that is real Verilog and over the test threshold.
fn big_source() -> String {
let mut text = String::from("module top;\n wire sig_a;\n");
for i in 0..20 {
text.push_str(&format!(" assign sig_a = w{i};\n"));
}
text.push_str("endmodule\n");
assert!(text.len() > 100, "the premise: over the test threshold");
text
}
/// A session with one large buffer open, and its URI.
///
/// Every call gets its own tree: this is the one `Tree::new` name shared
/// by roughly a dozen tests (every large-file-mode test that does not
/// need bespoke source text), which — unlike the rest of this module's
/// trees, each named for the one test that uses it — would otherwise
/// collide on the same `/tmp` directory under `cargo test`'s default
/// parallelism and race each other's `remove_dir_all`/`create_dir_all`.
/// The counter is what makes the shared literal safe to share.
fn fast_path_session(abilities: ClientAbilities) -> (Tree, Session, Uri) {
static CALLS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let n = CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let tree = Tree::new(&format!("largefile{n}"));
let path = tree.path.join("net.v");
tree.write("net.v", &big_source());
let mut session = Session::started(vec![tree.path.clone()], abilities, fast_path_settings());
let uri = session.open(&path, &big_source());
let _ = session.drain();
(tree, session, uri)
}
/// The params a document-scoped request carries, at a position on the
/// `sig_a` declaration.
fn at_sig_a(uri: &Uri) -> Value {
serde_json::json!({
"textDocument": { "uri": uri },
"position": { "line": 1, "character": 9 },
})
}
#[test]
fn a_buffer_over_the_threshold_opens_on_the_fast_path_and_says_so_once() {
let (_tree, mut session, uri) = {
let tree = Tree::new("largeannounce");
let path = tree.path.join("net.v");
tree.write("net.v", &big_source());
let mut session = Session::started(
vec![tree.path.clone()],
ClientAbilities::default(),
fast_path_settings(),
);
let uri = session.open(&path, &big_source());
(tree, session, uri)
};
let lines: Vec<String> = session
.logged()
.into_iter()
.map(|(_, message)| message)
.filter(|message| message.contains("large-file fast path"))
.collect();
assert_eq!(lines.len(), 1, "once per entry into the mode: {lines:?}");
assert!(lines[0].contains("net.v"), "{}", lines[0]);
assert!(lines[0].contains("bytes"), "{}", lines[0]);
// A keystroke in it does not say it again.
change(&mut session, &uri, 2, serde_json::json!([{ "text": big_source() }]));
assert!(
!session.logged().iter().any(|(_, m)| m.contains("large-file fast path")),
"the line is per entry, not per notification"
);
}
#[test]
fn a_large_buffer_is_diagnosed_as_empty_and_clears_what_it_left_behind() {
let tree = Tree::new("largesquiggles");
let path = tree.path.join("grow.v");
let mut session =
Session::started(vec![tree.path.clone()], ClientAbilities::default(), fast_path_settings());
// Small and broken: a real diagnostic is drawn.
let uri = session.open(&path, "module m;\n wire ;\nendmodule\n");
let drawn = session.published();
assert_eq!(drawn.len(), 1);
assert!(!drawn[0].diagnostics.is_empty(), "premise: squiggles were drawn");
// The same buffer, edited past the threshold: one publish, empty, so
// the squiggles go away rather than being left frozen on screen.
change(
&mut session,
&uri,
2,
serde_json::json!([{ "text": format!("module m;\n wire ;\n{}", " ".repeat(200)) }]),
);
let cleared = session.published();
assert_eq!(cleared.len(), 1, "one publish, as every change makes");
assert!(cleared[0].diagnostics.is_empty(), "and it is empty: {cleared:?}");
}
#[test]
fn semantic_tokens_range_paints_a_large_buffer() {
let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default());
let data = session.result(
SemanticTokensRangeRequest::METHOD,
serde_json::json!({
"textDocument": { "uri": uri },
"range": {
"start": { "line": 1, "character": 0 },
"end": { "line": 3, "character": 0 },
},
}),
);
let tokens = data["data"].as_array().expect("a token array").clone();
assert!(!tokens.is_empty(), "the window was lexed: {data}");
assert!(data["resultId"].is_null(), "a range answer is not delta material");
// First token: `wire` on line 1, five numbers per token.
assert_eq!(tokens.len() % 5, 0);
assert_eq!(tokens[0], 1, "delta_line — the first line of the window");
}
#[test]
fn semantic_tokens_full_is_declined_rather_than_answered_empty() {
// The whole reason: VS Code marks a model whose document provider
// answered *anything* as complete and never asks its range provider
// again. An error leaves it incomplete, so the viewport keeps
// painting. `serverCancelSupport` decides which code says so.
let cancels = ClientAbilities { token_server_cancel: true, ..Default::default() };
let (_tree, mut session, uri) = fast_path_session(cancels);
let params = serde_json::json!({ "textDocument": { "uri": uri } });
for method in [SemanticTokensFullRequest::METHOD, SemanticTokensFullDeltaRequest::METHOD] {
let mut params = params.clone();
params["previousResultId"] = serde_json::json!("1");
let error = session.request(method, params).response_result.expect_err("declined");
assert_eq!(error.code, lsp_server::ErrorCode::ServerCancelled as i32, "{method}");
assert!(error.message.contains("largeFile.threshold"), "{}", error.message);
}
// A client that never advertised it gets the code every 3.16 client
// already understands.
let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default());
let error = session
.request(
SemanticTokensFullRequest::METHOD,
serde_json::json!({ "textDocument": { "uri": uri } }),
)
.response_result
.expect_err("declined");
assert_eq!(error.code, lsp_server::ErrorCode::ContentModified as i32);
}
#[test]
fn formatting_a_large_buffer_refuses_out_loud_and_edits_nothing() {
let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default());
let edits = session.result(
Formatting::METHOD,
serde_json::json!({
"textDocument": { "uri": uri },
"options": { "tabSize": 2, "insertSpaces": true },
}),
);
assert_eq!(edits, serde_json::json!([]), "no edit, ever");
let shown = session.shown();
assert_eq!(shown.len(), 1, "the user pressed a key and is owed a reason: {shown:?}");
assert_eq!(shown[0].0, MessageType::ERROR);
assert!(shown[0].1.contains("largeFile.threshold"), "{}", shown[0].1);
}
#[test]
fn the_two_formatting_requests_the_user_did_not_press_stay_silent() {
let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default());
let edits = session.result(
OnTypeFormatting::METHOD,
serde_json::json!({
"textDocument": { "uri": uri },
"position": { "line": 1, "character": 9 },
"ch": ";",
"options": { "tabSize": 2, "insertSpaces": true },
}),
);
assert_eq!(edits, serde_json::json!([]));
let saved = session.result(
WillSaveWaitUntil::METHOD,
serde_json::json!({ "textDocument": { "uri": uri }, "reason": 1 }),
);
assert_eq!(saved, Value::Null);
assert!(session.shown().is_empty(), "neither fires on a key the user pressed");
}
#[test]
fn a_rename_is_refused_rather_than_applied_to_every_file_but_this_one() {
let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default());
assert_eq!(
session.result(PrepareRenameRequest::METHOD, at_sig_a(&uri)),
Value::Null,
"the box never opens"
);
let mut params = at_sig_a(&uri);
params["newName"] = serde_json::json!("sig_b");
let error = session.request(Rename::METHOD, params).response_result.expect_err("refused");
assert_eq!(error.code, lsp_server::ErrorCode::RequestFailed as i32);
assert!(error.message.contains("largeFile.threshold"), "{}", error.message);
}
#[test]
fn definition_and_references_answer_from_one_scan_of_the_buffer() {
let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default());
// The cursor is on the `sig_a` of `wire sig_a;`, and every `sig_a` in
// the file is one answer.
let found = session.result(GotoDefinition::METHOD, at_sig_a(&uri));
let locations = found.as_array().expect("an array");
assert_eq!(locations.len(), 1, "{found}");
assert_eq!(locations[0]["range"]["start"]["line"], 1);
assert_eq!(locations[0]["uri"].as_str(), Some(uri.as_str()));
let mut params = at_sig_a(&uri);
params["context"] = serde_json::json!({ "includeDeclaration": true });
let all = session.result(References::METHOD, params.clone());
assert_eq!(all.as_array().expect("an array").len(), 21, "the wire and its 20 uses");
params["context"] = serde_json::json!({ "includeDeclaration": false });
let uses = session.result(References::METHOD, params);
assert_eq!(uses.as_array().expect("an array").len(), 20, "minus the declaration");
}
/// **The dispatch table.** Every document-scoped request, and what a
/// buffer on the fast path answers it. The point is that the list is
/// complete and pinned: a handler added later that reads a large buffer's
/// *text* will fail here rather than in a user's editor.
#[test]
fn every_other_request_a_large_buffer_gets_answers_nothing_at_all() {
let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default());
let document = serde_json::json!({ "textDocument": { "uri": uri } });
let position = at_sig_a(&uri);
let range = serde_json::json!({
"textDocument": { "uri": uri },
"range": {
"start": { "line": 0, "character": 0 },
"end": { "line": 3, "character": 0 },
},
});
let empty = serde_json::json!([]);
// (method, params, expected answer)
let table: Vec<(&str, Value, Value)> = vec![
(HoverRequest::METHOD, position.clone(), Value::Null),
(GotoTypeDefinition::METHOD, position.clone(), empty.clone()),
(LinkedEditingRange::METHOD, position.clone(), Value::Null),
(DocumentLinkRequest::METHOD, document.clone(), empty.clone()),
(DocumentHighlightRequest::METHOD, position.clone(), Value::Null),
(FoldingRangeRequest::METHOD, document.clone(), empty.clone()),
(DocumentSymbolRequest::METHOD, document.clone(), empty.clone()),
(CodeLensRequest::METHOD, document.clone(), empty.clone()),
(InlayHintRequest::METHOD, range.clone(), empty.clone()),
(
CodeActionRequest::METHOD,
{
let mut params = range.clone();
params["context"] = serde_json::json!({ "diagnostics": [] });
params
},
empty.clone(),
),
(Completion::METHOD, position.clone(), Value::Null),
(SignatureHelpRequest::METHOD, position.clone(), Value::Null),
(
InlineCompletionRequest::METHOD,
{
let mut params = position.clone();
params["context"] =
serde_json::json!({ "triggerKind": 2, "selectedCompletionInfo": null });
params
},
Value::Null,
),
(CallHierarchyPrepare::METHOD, position.clone(), Value::Null),
(TypeHierarchyPrepare::METHOD, position.clone(), Value::Null),
// The one custom method: an object with both lists empty, which is
// what "this buffer has no scopes" already looks like.
(
pairs::SCOPE_PAIRS_METHOD,
document.clone(),
serde_json::json!({ "pairs": [], "unmatched": [] }),
),
];
for (method, params, expected) in table {
assert_eq!(session.result(method, params), expected, "{method}");
}
// `selectionRange` is the one request that answers something: the
// whole document is a legal expand-selection step even with nothing
// parsed, and it costs one span.
let mut selection = document.clone();
selection["positions"] = serde_json::json!([{ "line": 1, "character": 9 }]);
let chain = session.result(SelectionRangeRequest::METHOD, selection);
assert_eq!(chain.as_array().expect("one chain per position").len(), 1);
assert!(chain[0]["parent"].is_null(), "one step, the file: {chain}");
// Nothing above said a word to the user.
assert!(session.shown().is_empty());
}
#[test]
fn a_pull_diagnostics_client_gets_an_empty_report_for_a_large_buffer() {
let pulling = ClientAbilities { pull_diagnostics: true, ..Default::default() };
let (_tree, mut session, uri) = fast_path_session(pulling);
let report = session.result(
DocumentDiagnosticRequest::METHOD,
serde_json::json!({ "textDocument": { "uri": uri } }),
);
assert_eq!(report["items"], serde_json::json!([]), "{report}");
}
/// `workspace/diagnostic` walks every open buffer (`workspace_report`
/// above), a large one included — it is not skipped, it is present with
/// an empty **full** report, the same answer `diagnostics::all` gives
/// `textDocument/diagnostic`. Pinned because the workspace-scoped sweep is
/// a different code path from the per-document one already covered by
/// `a_pull_diagnostics_client_gets_an_empty_report_for_a_large_buffer`.
#[test]
fn a_large_buffer_is_present_in_workspace_diagnostics_with_an_empty_full_report() {
let pulling = ClientAbilities { pull_diagnostics: true, ..Default::default() };
let (_tree, mut session, uri) = fast_path_session(pulling);
let report = session.result(
WorkspaceDiagnosticRequest::METHOD,
serde_json::json!({ "identifier": diagnostics::SOURCE, "previousResultIds": [] }),
);
let items = report["items"].as_array().expect("items");
assert_eq!(items.len(), 1, "{report:#?}");
assert_eq!(items[0]["uri"].as_str(), Some(uri.as_str()));
assert_eq!(items[0]["kind"], "full", "present, not skipped: {report:#?}");
assert_eq!(items[0]["items"], serde_json::json!([]), "{report:#?}");
}
#[test]
fn the_threshold_arrives_by_push_and_by_pull_and_takes_effect_on_the_next_change() {
let tree = Tree::new("largethreshold");
let path = tree.path.join("net.v");
tree.write("net.v", &big_source());
// Default settings: the buffer is nowhere near 4 MiB, so it is
// analyzed in full.
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&path, &big_source());
assert!(!session.server.workspace.document(&uri).expect("open").large);
// Pushed. The buffer already open does not change mode on the spot —
// the decision is taken where a document is built.
session.notify(
DidChangeConfiguration::METHOD,
serde_json::json!({ "settings": { "lucisv": { "largeFile": { "threshold": 100 } } } }),
);
assert_eq!(session.server.workspace.client_settings().large_file_threshold, 100);
assert!(
!session.server.workspace.document(&uri).expect("open").large,
"the open buffer keeps the mode it was built in"
);
change(&mut session, &uri, 2, serde_json::json!([{ "text": big_source() }]));
assert!(
session.server.workspace.document(&uri).expect("open").large,
"and takes the fast path at its next change"
);
// Pulled: the same value through the other door.
let mut session = Session::with(
vec![tree.path.clone()],
ClientAbilities { configuration: true, ..Default::default() },
);
let (id, _) = configuration_request(&session);
session.answer(id, serde_json::json!([{ "largeFile": { "threshold": 100 } }]));
assert_eq!(session.server.workspace.client_settings().large_file_threshold, 100);
let uri = session.open(&path, &big_source());
assert!(session.server.workspace.document(&uri).expect("open").large);
}
#[test]
fn an_edit_to_a_large_buffer_moves_its_lines_and_the_next_window_agrees() {
let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default());
// Insert a line at the top. `sig_a`'s declaration moves from line 1
// to line 2, which is only true if the line index was rebuilt.
session.notify(
DidChangeTextDocument::METHOD,
serde_json::json!({
"textDocument": { "uri": uri, "version": 2 },
"contentChanges": [{
"range": {
"start": { "line": 0, "character": 0 },
"end": { "line": 0, "character": 0 },
},
"text": "// a new first line\n",
}],
}),
);
let data = session.result(
SemanticTokensRangeRequest::METHOD,
serde_json::json!({
"textDocument": { "uri": uri },
"range": {
"start": { "line": 2, "character": 0 },
"end": { "line": 3, "character": 0 },
},
}),
);
let tokens = data["data"].as_array().expect("tokens");
assert_eq!(tokens[0], 2, "the window's own line, after the insertion");
let found = session.result(
GotoDefinition::METHOD,
serde_json::json!({
"textDocument": { "uri": uri },
"position": { "line": 2, "character": 9 },
}),
);
assert_eq!(found[0]["range"]["start"]["line"], 2, "{found}");
}