php_lsp/backend/debug_gate.rs
1//! Test-only hold points for blocking-pool work.
2//!
3//! The responsiveness regression tests need to prove a notification handler's
4//! synchronous work runs off the connection's serve future. Requests can pin
5//! that with a pure ordering check (see `assert_stays_responsive` in the test
6//! harness), but a notification has no response to order against — earlier
7//! versions fell back to wall-clock budgets, which flaked on loaded CI
8//! runners. A gate makes the check deterministic instead: the test arms a
9//! named section, the handler's blocking closure parks in `pass` until
10//! released, and the test asserts the server still answers a probe while the
11//! work is provably in flight. On a correct build that holds under any
12//! scheduling; on a regressed (inline) build the serve future itself parks,
13//! no later message is processed, and the probe times out — a hard failure,
14//! never a flake.
15//!
16//! Production builds compile the whole mechanism out: without the
17//! `test-hooks` feature (enabled only for test targets, via the self
18//! dev-dependency in Cargo.toml) `DebugGate` is a zero-sized no-op and the
19//! hold/release custom methods are never registered, so a real client cannot
20//! arm anything.
21
22/// Gate section around `did_open`'s parse-diagnostics closure.
23pub const GATE_DID_OPEN_PARSE: &str = "didOpen.parse";
24/// Gate section around `did_close`'s on-disk resynchronization.
25pub const GATE_DID_CLOSE_DISK_SYNC: &str = "didClose.diskSync";
26/// Gate section around `did_save`'s diagnostics-recompute closure.
27pub const GATE_DID_SAVE_DIAGNOSTICS: &str = "didSave.diagnostics";
28/// Gate section around `did_change_watched_files`' batched parse closure.
29pub const GATE_DID_CHANGE_WATCHED_FILES: &str = "didChangeWatchedFiles.parse";
30/// Gate section around `will_rename_files`' `use`-edit batch closure.
31pub const GATE_WILL_RENAME_FILES: &str = "willRenameFiles.useEdits";
32/// Gate section around `will_delete_files`' `use`-edit batch closure.
33pub const GATE_WILL_DELETE_FILES: &str = "willDeleteFiles.useEdits";
34/// Gate section around `prepare_call_hierarchy`'s indexed-lookup closure.
35pub const GATE_PREPARE_CALL_HIERARCHY: &str = "prepareCallHierarchy.lookup";
36/// Gate section around `selection_range`'s AST-walk closure.
37pub const GATE_SELECTION_RANGE: &str = "selectionRange.walk";
38/// Gate section around `goto_implementation`'s method-decl cursor check.
39pub const GATE_GOTO_IMPLEMENTATION: &str = "gotoImplementation.methodDeclCheck";
40/// Gate section around `goto_definition`'s same-document/index fallback work.
41pub const GATE_GOTO_DEFINITION: &str = "gotoDefinition.lookup";
42/// Gate section around `rename`'s property-decl cursor check + variable rename.
43pub const GATE_RENAME_VARIABLE: &str = "rename.variable";
44/// Gate section around `references`' same-document variable walk.
45pub const GATE_REFERENCES_VARIABLE: &str = "references.variable";
46/// Gate section around `completion_resolve`'s all-indexes signature/doc lookup.
47pub const GATE_COMPLETION_RESOLVE: &str = "completionResolve.lookup";
48/// Gate section around `inlay_hint_resolve`'s all-indexes doc lookup.
49pub const GATE_INLAY_HINT_RESOLVE: &str = "inlayHintResolve.lookup";
50/// Gate section around `on_type_formatting`'s whole-document scan.
51pub const GATE_ON_TYPE_FORMATTING: &str = "onTypeFormatting.scan";
52/// Gate section around `prepare_rename`'s keyword member-access check.
53pub const GATE_PREPARE_RENAME: &str = "prepareRename.walk";
54/// Gate section around `document_symbol`'s AST walk.
55pub const GATE_DOCUMENT_SYMBOL: &str = "documentSymbol.walk";
56/// Gate section around `folding_range`'s AST walk plus comment/region scan.
57pub const GATE_FOLDING_RANGE: &str = "foldingRange.walk";
58/// Gate section around `document_link`'s AST walk plus `@link`/`@see` scan.
59pub const GATE_DOCUMENT_LINK: &str = "documentLink.walk";
60/// Gate section around `semantic_tokens_full`'s AST walk.
61pub const GATE_SEMANTIC_TOKENS_FULL: &str = "semanticTokensFull.walk";
62/// Gate section around `semantic_tokens_range`'s AST walk.
63pub const GATE_SEMANTIC_TOKENS_RANGE: &str = "semanticTokensRange.walk";
64/// Gate section around `semantic_tokens_full_delta`'s AST walk.
65pub const GATE_SEMANTIC_TOKENS_FULL_DELTA: &str = "semanticTokensFullDelta.walk";
66/// Gate section around `linked_editing_range`'s highlight/class-scoping walk.
67pub const GATE_LINKED_EDITING_RANGE: &str = "linkedEditingRange.walk";
68/// Gate section around `goto_type_definition`'s exact-resolution chain.
69pub const GATE_GOTO_TYPE_DEFINITION: &str = "gotoTypeDefinition.walk";
70/// Gate section around type-hierarchy lookup/result construction.
71pub const GATE_TYPE_HIERARCHY: &str = "typeHierarchy.lookup";
72/// Gate section around `moniker`'s AST member lookup.
73pub const GATE_MONIKER: &str = "moniker.lookup";
74/// Gate section around `inline_value`'s range text scan.
75pub const GATE_INLINE_VALUE: &str = "inlineValue.scan";
76/// Gate section around `codeAction/resolve`'s deferred action generation.
77pub const GATE_CODE_ACTION_RESOLVE: &str = "codeActionResolve.generate";
78/// Gate section around the usage-symbol settle-wait in `handle_references`/
79/// `indexed_rename`, held right after mir's own per-file resolution first
80/// comes back empty (companion file not yet known) and before the
81/// wait-then-retry — lets a test force a companion declaring file to open
82/// while mir's resolution attempt is still in flight, so the retry can
83/// observe mir resolving it correctly instead of falling through to the
84/// AST-heuristic FQN fallback.
85pub const GATE_USAGE_SYMBOL_RETRY: &str = "usageSymbol.retry";
86
87#[cfg(not(feature = "test-hooks"))]
88#[derive(Default)]
89pub struct DebugGate;
90
91#[cfg(not(feature = "test-hooks"))]
92impl DebugGate {
93 #[inline(always)]
94 pub fn new() -> Self {
95 DebugGate
96 }
97
98 #[inline(always)]
99 pub fn pass(&self, _section: &str) {}
100
101 #[inline(always)]
102 pub fn held_section(&self) -> Option<String> {
103 None
104 }
105}
106
107#[cfg(feature = "test-hooks")]
108pub use real::DebugGate;
109
110#[cfg(feature = "test-hooks")]
111mod real {
112 use std::sync::{Condvar, Mutex};
113
114 #[derive(Default)]
115 struct GateState {
116 /// Section name the next matching `pass` call should hold at.
117 armed: Option<String>,
118 /// Section currently parked at the gate (surfaced via `debugStats`).
119 held: Option<String>,
120 released: bool,
121 }
122
123 #[derive(Default)]
124 pub struct DebugGate {
125 state: Mutex<GateState>,
126 cv: Condvar,
127 }
128
129 impl DebugGate {
130 pub fn new() -> Self {
131 Self::default()
132 }
133
134 /// Arm the gate: the next `pass(section)` parks until [`release`](Self::release).
135 /// One passage per arm; re-arming replaces any previous armed section.
136 pub fn arm(&self, section: &str) {
137 let mut s = self.state.lock().unwrap();
138 s.armed = Some(section.to_owned());
139 s.released = false;
140 }
141
142 pub fn release(&self) {
143 let mut s = self.state.lock().unwrap();
144 s.armed = None;
145 s.released = true;
146 self.cv.notify_all();
147 }
148
149 /// Section currently parked at the gate, if any.
150 pub fn held_section(&self) -> Option<String> {
151 self.state.lock().unwrap().held.clone()
152 }
153
154 /// Hold point. No-op unless the gate is armed for exactly `section`;
155 /// when it is, claims the arm (so concurrent passages can't stack) and
156 /// parks until released. The park is capped at 60s: a test that fails
157 /// without releasing must not leave this task parked forever — tokio's
158 /// runtime shutdown joins in-flight blocking tasks, so an uncapped park
159 /// would turn that test's failure report into an eternal hang.
160 pub fn pass(&self, section: &str) {
161 let s = self.state.lock().unwrap();
162 if s.armed.as_deref() != Some(section) {
163 return;
164 }
165 let mut s = s;
166 s.armed = None;
167 s.held = Some(section.to_owned());
168 let (mut s, _timed_out) = self
169 .cv
170 .wait_timeout_while(s, std::time::Duration::from_secs(60), |s| !s.released)
171 .unwrap();
172 s.held = None;
173 s.released = false;
174 }
175 }
176}
177
178#[cfg(all(test, feature = "test-hooks"))]
179mod tests {
180 use super::*;
181 use std::sync::Arc;
182
183 #[test]
184 fn unarmed_pass_is_a_no_op() {
185 let gate = DebugGate::default();
186 gate.pass("anything");
187 assert_eq!(gate.held_section(), None);
188 }
189
190 #[test]
191 fn armed_pass_parks_until_release() {
192 let gate = Arc::new(DebugGate::default());
193 gate.arm("sec");
194 let g = Arc::clone(&gate);
195 let t = std::thread::spawn(move || g.pass("sec"));
196 while gate.held_section().as_deref() != Some("sec") {
197 std::thread::yield_now();
198 }
199 assert!(!t.is_finished());
200 gate.release();
201 t.join().unwrap();
202 assert_eq!(gate.held_section(), None);
203 }
204
205 #[test]
206 fn arm_holds_only_the_named_section_and_only_once() {
207 let gate = Arc::new(DebugGate::default());
208 gate.arm("sec");
209 gate.pass("other"); // wrong section: must not park
210 let g = Arc::clone(&gate);
211 let t = std::thread::spawn(move || g.pass("sec"));
212 while gate.held_section().is_none() {
213 std::thread::yield_now();
214 }
215 gate.release();
216 t.join().unwrap();
217 gate.pass("sec"); // arm consumed: must not park again
218 }
219}