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_save`'s diagnostics-recompute closure.
25pub const GATE_DID_SAVE_DIAGNOSTICS: &str = "didSave.diagnostics";
26/// Gate section around `did_change_watched_files`' batched parse closure.
27pub const GATE_DID_CHANGE_WATCHED_FILES: &str = "didChangeWatchedFiles.parse";
28/// Gate section around `will_rename_files`' `use`-edit batch closure.
29pub const GATE_WILL_RENAME_FILES: &str = "willRenameFiles.useEdits";
30/// Gate section around `will_delete_files`' `use`-edit batch closure.
31pub const GATE_WILL_DELETE_FILES: &str = "willDeleteFiles.useEdits";
32/// Gate section around `prepare_call_hierarchy`'s indexed-lookup closure.
33pub const GATE_PREPARE_CALL_HIERARCHY: &str = "prepareCallHierarchy.lookup";
34/// Gate section around `selection_range`'s AST-walk closure.
35pub const GATE_SELECTION_RANGE: &str = "selectionRange.walk";
36/// Gate section around `goto_implementation`'s method-decl cursor check.
37pub const GATE_GOTO_IMPLEMENTATION: &str = "gotoImplementation.methodDeclCheck";
38/// Gate section around `rename`'s property-decl cursor check + variable rename.
39pub const GATE_RENAME_VARIABLE: &str = "rename.variable";
40/// Gate section around `completion_resolve`'s all-indexes signature/doc lookup.
41pub const GATE_COMPLETION_RESOLVE: &str = "completionResolve.lookup";
42/// Gate section around `inlay_hint_resolve`'s all-indexes doc lookup.
43pub const GATE_INLAY_HINT_RESOLVE: &str = "inlayHintResolve.lookup";
44/// Gate section around `on_type_formatting`'s whole-document scan.
45pub const GATE_ON_TYPE_FORMATTING: &str = "onTypeFormatting.scan";
46/// Gate section around `prepare_rename`'s keyword member-access check.
47pub const GATE_PREPARE_RENAME: &str = "prepareRename.walk";
48/// Gate section around `document_symbol`'s AST walk.
49pub const GATE_DOCUMENT_SYMBOL: &str = "documentSymbol.walk";
50/// Gate section around `folding_range`'s AST walk plus comment/region scan.
51pub const GATE_FOLDING_RANGE: &str = "foldingRange.walk";
52/// Gate section around `document_link`'s AST walk plus `@link`/`@see` scan.
53pub const GATE_DOCUMENT_LINK: &str = "documentLink.walk";
54/// Gate section around `semantic_tokens_full`'s AST walk.
55pub const GATE_SEMANTIC_TOKENS_FULL: &str = "semanticTokensFull.walk";
56/// Gate section around `semantic_tokens_range`'s AST walk.
57pub const GATE_SEMANTIC_TOKENS_RANGE: &str = "semanticTokensRange.walk";
58/// Gate section around `semantic_tokens_full_delta`'s AST walk.
59pub const GATE_SEMANTIC_TOKENS_FULL_DELTA: &str = "semanticTokensFullDelta.walk";
60/// Gate section around `linked_editing_range`'s highlight/class-scoping walk.
61pub const GATE_LINKED_EDITING_RANGE: &str = "linkedEditingRange.walk";
62/// Gate section around `goto_type_definition`'s exact/short-name fallback chain.
63pub const GATE_GOTO_TYPE_DEFINITION: &str = "gotoTypeDefinition.walk";
64
65#[cfg(not(feature = "test-hooks"))]
66#[derive(Default)]
67pub struct DebugGate;
68
69#[cfg(not(feature = "test-hooks"))]
70impl DebugGate {
71 #[inline(always)]
72 pub fn new() -> Self {
73 DebugGate
74 }
75
76 #[inline(always)]
77 pub fn pass(&self, _section: &str) {}
78
79 #[inline(always)]
80 pub fn held_section(&self) -> Option<String> {
81 None
82 }
83}
84
85#[cfg(feature = "test-hooks")]
86pub use real::DebugGate;
87
88#[cfg(feature = "test-hooks")]
89mod real {
90 use std::sync::{Condvar, Mutex};
91
92 #[derive(Default)]
93 struct GateState {
94 /// Section name the next matching `pass` call should hold at.
95 armed: Option<String>,
96 /// Section currently parked at the gate (surfaced via `debugStats`).
97 held: Option<String>,
98 released: bool,
99 }
100
101 #[derive(Default)]
102 pub struct DebugGate {
103 state: Mutex<GateState>,
104 cv: Condvar,
105 }
106
107 impl DebugGate {
108 pub fn new() -> Self {
109 Self::default()
110 }
111
112 /// Arm the gate: the next `pass(section)` parks until [`release`](Self::release).
113 /// One passage per arm; re-arming replaces any previous armed section.
114 pub fn arm(&self, section: &str) {
115 let mut s = self.state.lock().unwrap();
116 s.armed = Some(section.to_owned());
117 s.released = false;
118 }
119
120 pub fn release(&self) {
121 let mut s = self.state.lock().unwrap();
122 s.armed = None;
123 s.released = true;
124 self.cv.notify_all();
125 }
126
127 /// Section currently parked at the gate, if any.
128 pub fn held_section(&self) -> Option<String> {
129 self.state.lock().unwrap().held.clone()
130 }
131
132 /// Hold point. No-op unless the gate is armed for exactly `section`;
133 /// when it is, claims the arm (so concurrent passages can't stack) and
134 /// parks until released. The park is capped at 60s: a test that fails
135 /// without releasing must not leave this task parked forever — tokio's
136 /// runtime shutdown joins in-flight blocking tasks, so an uncapped park
137 /// would turn that test's failure report into an eternal hang.
138 pub fn pass(&self, section: &str) {
139 let s = self.state.lock().unwrap();
140 if s.armed.as_deref() != Some(section) {
141 return;
142 }
143 let mut s = s;
144 s.armed = None;
145 s.held = Some(section.to_owned());
146 let (mut s, _timed_out) = self
147 .cv
148 .wait_timeout_while(s, std::time::Duration::from_secs(60), |s| !s.released)
149 .unwrap();
150 s.held = None;
151 s.released = false;
152 }
153 }
154}
155
156#[cfg(all(test, feature = "test-hooks"))]
157mod tests {
158 use super::*;
159 use std::sync::Arc;
160
161 #[test]
162 fn unarmed_pass_is_a_no_op() {
163 let gate = DebugGate::default();
164 gate.pass("anything");
165 assert_eq!(gate.held_section(), None);
166 }
167
168 #[test]
169 fn armed_pass_parks_until_release() {
170 let gate = Arc::new(DebugGate::default());
171 gate.arm("sec");
172 let g = Arc::clone(&gate);
173 let t = std::thread::spawn(move || g.pass("sec"));
174 while gate.held_section().as_deref() != Some("sec") {
175 std::thread::yield_now();
176 }
177 assert!(!t.is_finished());
178 gate.release();
179 t.join().unwrap();
180 assert_eq!(gate.held_section(), None);
181 }
182
183 #[test]
184 fn arm_holds_only_the_named_section_and_only_once() {
185 let gate = Arc::new(DebugGate::default());
186 gate.arm("sec");
187 gate.pass("other"); // wrong section: must not park
188 let g = Arc::clone(&gate);
189 let t = std::thread::spawn(move || g.pass("sec"));
190 while gate.held_section().is_none() {
191 std::thread::yield_now();
192 }
193 gate.release();
194 t.join().unwrap();
195 gate.pass("sec"); // arm consumed: must not park again
196 }
197}