Skip to main content

php_lsp/document/
document_store.rs

1use std::collections::HashSet;
2use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
3use std::sync::{Arc, Mutex, OnceLock};
4
5use arc_swap::{ArcSwap, ArcSwapOption};
6
7use dashmap::{DashMap, DashSet};
8use salsa::Setter;
9use tower_lsp_server::ls_types::{SemanticToken, Uri};
10
11use crate::db::mir_queries::{LspWorkspace, LspWsFile};
12use crate::document::ast::ParsedDoc;
13use crate::document::cache_registry::CacheRegistry;
14use crate::index::file_index::FileIndex;
15use crate::lang::autoload::Psr4Map;
16
17pub struct DocumentStore {
18    /// Per-file caches with unified eviction logic. See [`CacheRegistry`].
19    caches: CacheRegistry,
20
21    // ── Salsa-input storage ────────────────────────────────────────────────
22    // Phase E4: `DocumentStore` is now a pure salsa-input wrapper. Open-file
23    // state (live text, version token, parse-diagnostics cache) lives on
24    // `Backend` in its `open_files` map; the set of files tracked by salsa
25    // is exactly `source_files.keys()`.
26    /// `Uri -> LspWsFile` lookup on the shared mir db. Each `LspWsFile` pairs
27    /// mir's `SourceFile` (the shared text input) with the optional warm-start
28    /// `cached_index`. Created/updated through the `AnalysisSession`'s
29    /// `with_db_mut` under the db write lock; reads run on cheap snapshot clones.
30    lsp_ws_files: DashMap<Uri, LspWsFile>,
31    /// URIs that have been removed. Re-opening a deleted URI un-deletes it here
32    /// and reuses the existing `LspWsFile` handle.
33    deleted_uris: DashSet<Uri>,
34    /// Set to `true` when the set of tracked files changes (add or remove).
35    /// `sync_workspace_files` skips the collect/sort/compare path when this
36    /// is `false`, avoiding a lock acquisition on every LSP request.
37    workspace_files_dirty: AtomicBool,
38    /// Cached result of `workspace_file_paths()`. `None` means stale/never
39    /// built — cleared by `mark_workspace_files_dirty` rather than shared
40    /// with `workspace_files_dirty` itself, since `sync_workspace_files`
41    /// destructively consumes that flag (`swap(false, ..)`) and a second
42    /// consumer reading it would race for the same signal.
43    workspace_file_paths_cache: ArcSwapOption<Vec<Arc<str>>>,
44    /// Diagnostic counter: incremented once per call to
45    /// `resolve_reachability_queries`, i.e. once per actual workspace scan
46    /// pass — regardless of how many queries are batched into that pass.
47    /// Lets tests assert that batching N symbols' reachability narrowing
48    /// (e.g. all of one file's code lenses) pays one scan, not N.
49    reachability_scan_passes: AtomicU64,
50    /// Per-URI lock so concurrent callers computing the same uncached file's
51    /// analysis (`cached_analysis_cancellable`) serialize onto one
52    /// computation instead of each redoing the full mir pass — e.g. `did_open`'s
53    /// diagnostics trigger racing a fast-following hover on a large,
54    /// just-opened file. Entries are never removed: bounded by the number of
55    /// distinct files ever analyzed, the same order of magnitude as
56    /// `lsp_ws_files`.
57    analysis_inflight: DashMap<Uri, Arc<Mutex<()>>>,
58    /// Diagnostic counter: incremented once per real `FileAnalyzer::analyze`
59    /// run in `cached_analysis_cancellable` (never on a cache hit). Lets
60    /// tests assert that concurrent callers racing for the same uncached
61    /// file's analysis (see `analysis_inflight`) compute it once, not once
62    /// per caller.
63    analysis_compute_count: AtomicU64,
64    /// `LspWorkspace` salsa input on the shared mir db: the project-file scoping
65    /// set aggregated by `workspace_index`. Created lazily on first sync (the db
66    /// is owned by the lazily-built `AnalysisSession`).
67    lsp_workspace: Mutex<Option<LspWorkspace>>,
68    /// Shared PSR-4 namespace-to-path map. Shared with `Backend` via `Arc`
69    /// so updates from `initialized` (when composer.json is loaded) are
70    /// visible here without any additional wiring. `ArcSwap` makes reads
71    /// lock-free — a poisoned guard can no longer crash a request handler.
72    psr4: Arc<ArcSwap<Psr4Map>>,
73    /// `(target PHP version, cached AnalysisSession built for that version)`.
74    /// One lock for both — `workspace_php_version()` used to read a separate
75    /// `Mutex<PhpVersion>`, so fetching the version and then building/fetching
76    /// the session used to take two locks per call; `current_analysis_session()`
77    /// takes one. `None` only before the first build, or right after
78    /// `set_php_version` invalidates it.
79    /// mir-analyzer's `AnalysisSession` owns the workspace MirDb, runs Pass-2
80    /// analysis, and lazy-loads dependencies via PSR-4.
81    analysis_session: Mutex<(
82        mir_analyzer::PhpVersion,
83        Option<Arc<mir_analyzer::AnalysisSession>>,
84    )>,
85    /// Cache directory shared with the workspace file-index cache. When set,
86    /// new `AnalysisSession`s are built with `with_cache_dir` so that stub
87    /// parsing results survive server restarts.
88    session_cache_dir: OnceLock<std::path::PathBuf>,
89    /// URIs of autoload.files entries from composer.json. These define global
90    /// helper functions (e.g. tap, class_uses_recursive in Laravel) that are
91    /// not discoverable by namespace walk. Pre-ingested into the AnalysisSession
92    /// before each file analysis so mir doesn't emit false UndefinedFunction.
93    autoload_uris: std::sync::RwLock<Vec<Uri>>,
94    /// Set once the workspace scan's reference-index phase finishes, i.e. the
95    /// `subtypes_of` map in `workspace_index` is complete. Visibility-derived
96    /// scope narrowing that relies on the full subtype set (protected methods)
97    /// only applies once this is `true`; before then it falls back to the full
98    /// workspace scope so references are never under-reported.
99    index_ready: AtomicBool,
100    /// Monotonically increasing counter bumped on every actual text write
101    /// (including file deletions). Long-running read operations (e.g.
102    /// `session_references_to`) capture this value before starting and
103    /// cancel themselves if it advances — avoiding stale results and
104    /// unbounded retry loops after concurrent edits.
105    write_revision: AtomicU64,
106    /// Cancel token for the in-flight dependent-diagnostics sweep. A newer
107    /// edit's sweep cancels the previous one via [`Self::begin_reanalyze`], so
108    /// fast typing preempts stale workspace re-analysis rather than queueing
109    /// behind it.
110    reanalyze_cancel: Mutex<mir_analyzer::IndexCancel>,
111    /// Cancel token for the in-flight analysis warm sweep
112    /// ([`Self::warm_analysis_sweep`]); a newer sweep cancels the previous one
113    /// via [`Self::begin_warm_sweep`].
114    warm_sweep_cancel: Mutex<mir_analyzer::IndexCancel>,
115    /// Warm sweeps that ran to completion (not cancelled). Observability only,
116    /// surfaced via `$/php-lsp/debugStats` so benches/tests can await warmth.
117    warm_sweeps_completed: AtomicU64,
118    /// Calls to [`Self::warm_start_indexes`] that actually replayed at least
119    /// one file (not the empty-workspace no-op). Observability only, surfaced
120    /// via `$/php-lsp/debugStats` so tests can await a runtime-added folder's
121    /// warm-start replay instead of guessing a fixed delay.
122    warm_start_replays_completed: AtomicU64,
123    /// Count of in-flight interactive reads (requests the user is waiting on).
124    /// The workspace scan yields at file boundaries while this is non-zero, so
125    /// its per-file salsa writes can't starve a request's snapshot into an
126    /// endless `Cancelled` retry loop. Advisory only — relaxed ordering.
127    interactive_reads: AtomicU64,
128}
129
130/// RAII handle marking an interactive read in flight; see
131/// [`DocumentStore::interactive_read_guard`].
132pub struct InteractiveReadGuard<'a>(&'a AtomicU64);
133
134impl Drop for InteractiveReadGuard<'_> {
135    fn drop(&mut self) {
136        self.0.fetch_sub(1, Ordering::Relaxed);
137    }
138}
139
140impl Default for DocumentStore {
141    fn default() -> Self {
142        Self::new()
143    }
144}
145
146/// Analysis threads need big stacks: deep type-inference recursion on
147/// pathological files overflows rayon's 2 MB default, and salsa 0.28's
148/// `DependencyGraph::update_transferred_edges` recurses per transferred
149/// dependent under contended parallel queries — observed blowing 16 MB on
150/// the Laravel fixture (64 MB measured clean over repeated runs; the pages
151/// are reserved, not committed). Size the global pool before any parallel
152/// analysis runs; build_global fails harmlessly if a pool already exists.
153/// Benches/tests driving `AnalysisSession` without a `DocumentStore` must
154/// call this themselves — rayon otherwise lazily builds the pool with
155/// default stacks on mir's first `par_iter`.
156pub fn ensure_rayon_worker_stacks() {
157    static RAYON_STACK: OnceLock<()> = OnceLock::new();
158    RAYON_STACK.get_or_init(|| {
159        let _ = rayon::ThreadPoolBuilder::new()
160            .stack_size(64 * 1024 * 1024)
161            .build_global();
162    });
163}
164
165impl DocumentStore {
166    pub fn new() -> Self {
167        ensure_rayon_worker_stacks();
168        DocumentStore {
169            caches: CacheRegistry::new(),
170            lsp_ws_files: DashMap::new(),
171            deleted_uris: DashSet::new(),
172            workspace_files_dirty: AtomicBool::new(true),
173            workspace_file_paths_cache: ArcSwapOption::from(None),
174            reachability_scan_passes: AtomicU64::new(0),
175            analysis_inflight: DashMap::new(),
176            analysis_compute_count: AtomicU64::new(0),
177            lsp_workspace: Mutex::new(None),
178            psr4: Arc::new(ArcSwap::from_pointee(Psr4Map::empty())),
179            analysis_session: Mutex::new((mir_analyzer::PhpVersion::LATEST, None)),
180            session_cache_dir: OnceLock::new(),
181            autoload_uris: std::sync::RwLock::new(Vec::new()),
182            index_ready: AtomicBool::new(false),
183            write_revision: AtomicU64::new(0),
184            reanalyze_cancel: Mutex::new(mir_analyzer::IndexCancel::new()),
185            warm_sweep_cancel: Mutex::new(mir_analyzer::IndexCancel::new()),
186            warm_sweeps_completed: AtomicU64::new(0),
187            warm_start_replays_completed: AtomicU64::new(0),
188            interactive_reads: AtomicU64::new(0),
189        }
190    }
191
192    /// Mark an interactive read (a request the user is waiting on) as in
193    /// flight for the guard's lifetime. Background bulk writers poll
194    /// [`Self::yield_to_interactive_reads`] between files and pause while any
195    /// guard is live, giving the read a write-free window to complete.
196    pub fn interactive_read_guard(&self) -> InteractiveReadGuard<'_> {
197        self.interactive_reads.fetch_add(1, Ordering::Relaxed);
198        InteractiveReadGuard(&self.interactive_reads)
199    }
200
201    /// Take an interactive-read guard, wait (bounded ~50 ms) for in-flight
202    /// background writes to go quiet, and return the settled write revision.
203    ///
204    /// For user-facing sweeps that abort when [`Self::write_rev`] advances:
205    /// snapshotting the revision this way ensures only genuine user edits —
206    /// not the background scan the guard just paused — void the sweep.
207    /// Sleeps; call from a blocking thread only.
208    pub fn settled_write_rev_guard(&self) -> (InteractiveReadGuard<'_>, u64) {
209        let guard = self.interactive_read_guard();
210        // Post-scan there is no background write storm to settle; skip the
211        // sleep so steady-state requests pay only the guard's atomic inc.
212        if !self.is_index_ready() {
213            let deadline = std::time::Instant::now() + std::time::Duration::from_millis(50);
214            let mut rev = self.write_rev();
215            loop {
216                std::thread::sleep(std::time::Duration::from_millis(2));
217                let now = self.write_rev();
218                let quiet = now == rev;
219                rev = now;
220                if quiet || std::time::Instant::now() >= deadline {
221                    break;
222                }
223            }
224        }
225        (guard, self.write_rev())
226    }
227
228    /// Pause the calling (background-writer) thread while interactive reads
229    /// are in flight, up to 500 ms per call. Bounded so a wedged reader can
230    /// only slow the scan, never stop it; callers invoke this per file, so
231    /// sustained interactive traffic keeps yielding at each boundary.
232    pub fn yield_to_interactive_reads(&self) {
233        let mut waited = std::time::Duration::ZERO;
234        const STEP: std::time::Duration = std::time::Duration::from_millis(2);
235        const MAX: std::time::Duration = std::time::Duration::from_millis(500);
236        while self.interactive_reads.load(Ordering::Relaxed) > 0 && waited < MAX {
237            std::thread::sleep(STEP);
238            waited += STEP;
239        }
240    }
241
242    /// Install a fresh cancel token for a dependent-diagnostics sweep,
243    /// cancelling whichever sweep was previously in flight. Pass the returned
244    /// token to `reanalyze_dependents_cancellable`; when a newer edit calls
245    /// this again the old token flips and that older sweep stops at its next
246    /// file boundary instead of racing this one to publish stale diagnostics.
247    pub fn begin_reanalyze(&self) -> mir_analyzer::IndexCancel {
248        let fresh = mir_analyzer::IndexCancel::new();
249        let mut guard = self.reanalyze_cancel.lock().unwrap();
250        guard.cancel();
251        *guard = fresh.clone();
252        fresh
253    }
254
255    /// Install a fresh cancel token for an analysis warm sweep, cancelling any
256    /// sweep previously in flight. Mirrors [`Self::begin_reanalyze`] but on a
257    /// separate slot: edit-triggered diagnostic sweeps and background warming
258    /// must not cancel each other.
259    pub fn begin_warm_sweep(&self) -> mir_analyzer::IndexCancel {
260        let fresh = mir_analyzer::IndexCancel::new();
261        let mut guard = self.warm_sweep_cancel.lock().unwrap();
262        guard.cancel();
263        *guard = fresh.clone();
264        fresh
265    }
266
267    /// Drive every workspace file through mir's memoized `analyze_file` query
268    /// so later reference/rename requests are memo hits instead of cold
269    /// analyses (~20 ms per file on real code — a few hundred candidate files
270    /// makes an interactive request take seconds).
271    ///
272    /// `priority` files (and the files declaring the classes they reference —
273    /// the user's working set) are warmed first, so requests against open
274    /// files go warm within the sweep's first seconds even on workspaces
275    /// where the full sweep takes much longer.
276    ///
277    /// Background-priority: processes files in small chunks, yielding to
278    /// interactive reads at each boundary, and stops at the next boundary once
279    /// `cancel` flips. Re-running after edits is cheap — unaffected files
280    /// revalidate via salsa without re-analysis. Blocking; call from
281    /// `spawn_blocking`.
282    pub fn warm_analysis_sweep(&self, priority: &[Uri], cancel: &mir_analyzer::IndexCancel) {
283        // Dedicated thread with a generous stack: the serial prepare phase and
284        // priority resolution recurse over real-world ASTs whose depth can
285        // exceed the default 2 MiB thread stack (debug builds especially).
286        // One pathological file must not abort the whole server process.
287        std::thread::scope(|s| {
288            let _ = std::thread::Builder::new()
289                .name("php-lsp-warm-sweep".into())
290                .stack_size(64 * 1024 * 1024)
291                .spawn_scoped(s, || self.warm_analysis_sweep_inner(priority, cancel))
292                .map(|h| h.join());
293        });
294    }
295
296    /// Build the sweep's ordered file list: `priority` files and the files
297    /// declaring the classes they reference (see [`Self::sweep_priority_files`])
298    /// first, then every other tracked file — except vendor files, which the
299    /// ambient sweep skips regardless of `indexVendor`. A vendor file that
300    /// ends up in `priority` (opened directly, or referenced by an open
301    /// project file) is unaffected: the exclusion only applies to the
302    /// untargeted bulk-sweep tail, not the front of the queue.
303    fn sweep_candidate_files(&self, priority: &[Uri]) -> Vec<Arc<str>> {
304        let front: Vec<Arc<str>> = self.sweep_priority_files(priority);
305        let front_set: HashSet<&str> = front.iter().map(|f| f.as_ref()).collect();
306        front
307            .iter()
308            .cloned()
309            .chain(
310                self.lsp_ws_files
311                    .iter()
312                    .filter(|e| !self.deleted_uris.contains(e.key()))
313                    .filter(|e| !is_vendor_uri(e.key()))
314                    .map(|e| Arc::<str>::from(e.key().as_str()))
315                    .filter(|f| !front_set.contains(f.as_ref())),
316            )
317            .collect()
318    }
319
320    fn warm_analysis_sweep_inner(&self, priority: &[Uri], cancel: &mir_analyzer::IndexCancel) {
321        const CHUNK: usize = 32;
322        let files = self.sweep_candidate_files(priority);
323        let session = self.current_analysis_session();
324        let mut all_chunks_settled = true;
325        for chunk in files.chunks(CHUNK) {
326            if cancel.is_cancelled() {
327                return;
328            }
329            self.yield_to_interactive_reads();
330            // A concurrent write (e.g. another file being ingested) can land
331            // mid-chunk and cancel the analysis snapshot. Retry the same
332            // chunk immediately — `cancel` (not just the transient snapshot
333            // cancellation) is the authoritative stop signal, so a retry loop
334            // here only spins while an unrelated writer keeps landing, and
335            // exits promptly once `cancel` itself flips (a real edit
336            // superseding this sweep). Without the retry, a chunk silently
337            // skipped here has no guaranteed follow-up: `warm_sweeps_completed`
338            // must not count this sweep as covering files it never actually
339            // analyzed, or a caller polling that counter (e.g. a test waiting
340            // for the reference index to be fully warm) can observe "done"
341            // while some files' postings were never written.
342            loop {
343                if cancel.is_cancelled() {
344                    all_chunks_settled = false;
345                    break;
346                }
347                if salsa::Cancelled::catch(std::panic::AssertUnwindSafe(|| {
348                    session.reanalyze_files_cancellable(chunk, cancel)
349                }))
350                .is_ok()
351                {
352                    break;
353                }
354            }
355        }
356        if !cancel.is_cancelled() && all_chunks_settled {
357            // The sweep staged each analyzed file's reference postings into
358            // mir's AnalysisCache; persist them so the next launch's
359            // `warm_start_indexes` replays references index-warm. Flush
360            // before publishing completion — observers of the counter may
361            // rely on the postings being on disk.
362            session.flush_analysis_cache();
363            self.warm_sweeps_completed.fetch_add(1, Ordering::Relaxed);
364        }
365    }
366
367    /// Persist mir's staged analysis-cache entries (reference postings) to
368    /// disk. No-op when nothing changed since the last flush.
369    pub fn flush_analysis_cache(&self) {
370        self.current_analysis_session().flush_analysis_cache();
371    }
372
373    /// Warm sweeps that ran to completion. See `$/php-lsp/debugStats`.
374    pub fn warm_sweeps_completed(&self) -> u64 {
375        self.warm_sweeps_completed.load(Ordering::Relaxed)
376    }
377
378    pub fn warm_start_replays_completed(&self) -> u64 {
379        self.warm_start_replays_completed.load(Ordering::Relaxed)
380    }
381
382    /// The sweep's front of the queue: `priority` files themselves plus the
383    /// files declaring the classes they reference (type hints, `use` imports,
384    /// `new`, `extends`, …) — the set a request against an open file most
385    /// likely touches. Resolution goes through the memoized workspace index,
386    /// matching by FQN with a short-name fallback.
387    fn sweep_priority_files(&self, priority: &[Uri]) -> Vec<Arc<str>> {
388        if priority.is_empty() {
389            return Vec::new();
390        }
391        let ws = self.get_workspace_index_salsa();
392        let mut out: Vec<Arc<str>> = Vec::new();
393        let mut seen: HashSet<Arc<str>> = HashSet::new();
394        let push = |uri: &Uri, out: &mut Vec<Arc<str>>, seen: &mut HashSet<Arc<str>>| {
395            let f: Arc<str> = Arc::from(uri.as_str());
396            if seen.insert(Arc::clone(&f)) {
397                out.push(f);
398            }
399        };
400        for uri in priority {
401            push(uri, &mut out, &mut seen);
402        }
403        for uri in priority {
404            let Some(doc) = self.get_doc_salsa(uri) else {
405                continue;
406            };
407            for fqn in crate::navigation::references::collect_referenced_class_fqns(&doc) {
408                let short = crate::text::fqn_short_name(&fqn);
409                let Some(refs) = ws.classes_by_name.get(short) else {
410                    continue;
411                };
412                for &r in refs {
413                    if let Some((decl_uri, cls)) = ws.at(r)
414                        && cls.fqn.trim_start_matches('\\') == fqn
415                    {
416                        push(decl_uri, &mut out, &mut seen);
417                    }
418                }
419            }
420        }
421        out
422    }
423
424    /// Mark the workspace reference index as fully built. Called by the scan
425    /// when its final phase completes (alongside `$/php-lsp/indexReady`).
426    pub fn mark_index_ready(&self) {
427        self.index_ready.store(true, Ordering::Release);
428    }
429
430    /// Whether the workspace reference index has finished building.
431    pub fn is_index_ready(&self) -> bool {
432        self.index_ready.load(Ordering::Acquire)
433    }
434
435    /// Snapshot of the write-revision counter. Long-running reads should
436    /// capture this before starting and pass it to cancellable operations;
437    /// if the counter advances, those operations abort and return empty rather
438    /// than looping indefinitely against a newly-invalidated database.
439    pub fn write_rev(&self) -> u64 {
440        self.write_revision.load(Ordering::Acquire)
441    }
442
443    /// Set the directory used to persist stub-parse and analysis results across
444    /// server restarts. Subsequent calls are silently ignored (`OnceLock`
445    /// semantics).
446    ///
447    /// If a session was already built — an early request (e.g. the editor's
448    /// restored-buffer `didOpen` racing `initialized`) builds one on demand —
449    /// it was pinned in-memory-only: nothing it computes is ever flushed, and
450    /// the next launch replays nothing, silently re-paying the whole cold
451    /// cost every session. Drop it so the next `analysis_session()` rebuilds
452    /// with the cache attached; the few analyses done that early re-ingest
453    /// on demand.
454    pub fn set_session_cache_dir(&self, dir: std::path::PathBuf) {
455        if self.session_cache_dir.set(dir).is_err() {
456            return;
457        }
458        let dropped = self.analysis_session.lock().unwrap().1.take().is_some();
459        if dropped {
460            self.drop_session_scoped_state();
461        }
462    }
463
464    /// Register URIs discovered from composer.json `autoload.files` entries.
465    /// These PHP files define global helper functions (e.g. `tap()` in Laravel)
466    /// that are not class-resolvable via PSR-4. Clears `analysis_cache` so the
467    /// next per-file analysis pre-ingests them into the AnalysisSession before
468    /// running mir's FileAnalyzer.
469    pub fn set_autoload_uris(&self, uris: Vec<Uri>) {
470        *self.autoload_uris.write().unwrap() = uris;
471        self.caches.evict_analysis_all();
472    }
473
474    /// Get or build the `AnalysisSession` for the given PHP version. Rebuilds
475    /// when the version changes (e.g. user flipped config). The session owns
476    /// the shared salsa db and AnalysisCache; lazy-loads vendor files via the
477    /// shared PSR-4 map. Built-in stubs are *not* pre-loaded: mir's
478    /// `prepare_ast_for_analysis` ingests the stubs each analyzed file
479    /// references, and [`crate::types::stub_members`] faults in single stub
480    /// files for builtin member/hover lookups.
481    pub fn analysis_session(
482        &self,
483        php_version: mir_analyzer::PhpVersion,
484    ) -> Arc<mir_analyzer::AnalysisSession> {
485        let mut guard = self.analysis_session.lock().unwrap();
486        if guard.0 == php_version
487            && let Some(session) = guard.1.as_ref()
488        {
489            return Arc::clone(session);
490        }
491        // Build a fresh session. Hand it the shared PSR-4 map so it can
492        // lazy-resolve `UndefinedClass` candidates without us having to mirror
493        // every vendor file upfront.
494        let resolver: Arc<dyn mir_analyzer::ClassResolver> = self.psr4.load_full();
495        // References/implementations are answered from mir's delta-maintained
496        // inverted indexes (posting lists + subtype edges), which the session
497        // keeps in step with every edit path.
498        let mut builder =
499            mir_analyzer::AnalysisSession::new(php_version).with_class_resolver(resolver);
500        if let Some(dir) = self.session_cache_dir.get() {
501            builder = builder.with_cache_dir(dir);
502        }
503        let session = Arc::new(builder);
504        *guard = (php_version, Some(Arc::clone(&session)));
505        session
506    }
507
508    /// Get-or-build the `AnalysisSession` for the *current* workspace PHP
509    /// version — a single lock acquisition on the common (already-built)
510    /// path. Replaces `self.analysis_session(self.workspace_php_version())`,
511    /// which took two separate locks per call.
512    pub fn current_analysis_session(&self) -> Arc<mir_analyzer::AnalysisSession> {
513        let guard = self.analysis_session.lock().unwrap();
514        if let Some(session) = guard.1.as_ref() {
515            return Arc::clone(session);
516        }
517        let php_version = guard.0;
518        drop(guard);
519        self.analysis_session(php_version)
520    }
521
522    /// Current PHP version tracked by the workspace input.
523    pub fn workspace_php_version(&self) -> mir_analyzer::PhpVersion {
524        self.analysis_session.lock().unwrap().0
525    }
526
527    /// File URIs of all direct and transitive subclasses of `class_fqn`,
528    /// resolved via mir's inheritance graph. Returns an empty vec when the mir
529    /// session hasn't ingested the class yet (cold start, excluded paths).
530    ///
531    /// Used by `goto_implementation` and `subtypes` to scope their lookups to
532    /// the correct files, fixing aliased `extends` and FQN-qualified forms that
533    /// the raw-name `subtypes_of` map misses.
534    pub fn class_subtype_urls(&self, class_fqn: &str) -> Vec<tower_lsp_server::ls_types::Uri> {
535        let session = self.current_analysis_session();
536        session
537            .subtype_files(class_fqn)
538            .into_iter()
539            .filter_map(|p| p.parse::<Uri>().ok())
540            .collect()
541    }
542
543    /// Return the `Arc<ArcSwap<Psr4Map>>` so callers can share it.
544    /// `Backend` clones this arc at construction time so writes
545    /// (e.g. loading composer.json on `initialized`) are immediately visible
546    /// to PSR-4 resolution during analysis without extra plumbing.
547    pub fn psr4_arc(&self) -> Arc<ArcSwap<Psr4Map>> {
548        Arc::clone(&self.psr4)
549    }
550
551    /// Durability for a file's salsa input: vendor files never change within a
552    /// session, so salsa can skip re-validating their queries on user edits.
553    fn input_durability(uri: &Uri) -> salsa::Durability {
554        if uri.as_str().contains("/vendor/") {
555            salsa::Durability::HIGH
556        } else {
557            salsa::Durability::LOW
558        }
559    }
560
561    /// The `LspWsFile` handle for `uri`, if it is mirrored and not deleted.
562    fn lsp_ws_file(&self, uri: &Uri) -> Option<LspWsFile> {
563        if self.deleted_uris.contains(uri) {
564            return None;
565        }
566        self.lsp_ws_files.get(uri).map(|e| *e)
567    }
568
569    /// Take a cheap snapshot of the shared mir db and run `f` on it, retrying
570    /// on `salsa::Cancelled` (raised when a concurrent writer bumps the
571    /// revision). Mirrors [`Self::snapshot_query`] for the converged db.
572    ///
573    /// The loop terminates as soon as the writer pauses long enough for one
574    /// query to complete. Handlers that want an early exit under sustained
575    /// write pressure should pass a write-rev closure (see `code_lenses`) and
576    /// check it at coarser granularity rather than here.
577    fn snapshot_mir_query<R>(&self, f: impl Fn(&mir_analyzer::db::MirDbStorage) -> R) -> R {
578        use std::panic::AssertUnwindSafe;
579        let _interactive = self.interactive_read_guard();
580        let session = self.current_analysis_session();
581        // Each iteration's snapshot clone MUST drop before the next snapshot:
582        // a concurrent writer's salsa `set` holds the mir write lock and waits
583        // for outstanding db handles to drop, while the next `snapshot_db` needs
584        // the read lock — keeping the clone alive across the retry deadlocks.
585        loop {
586            let db = session.snapshot_db();
587            match salsa::Cancelled::catch(AssertUnwindSafe(|| f(&db))) {
588                Ok(r) => return r,
589                Err(_) => drop(db),
590            }
591        }
592    }
593
594    /// Bounded variant of [`Self::snapshot_mir_query`] for cosmetic,
595    /// cursor-triggered reads that must not spin under sustained write pressure.
596    /// Returns `None` if a concurrent writer cancels the query `attempts` times
597    /// in a row (the caller then falls back to a stale result). Same
598    /// drop-before-retry discipline as `snapshot_mir_query`.
599    fn try_snapshot_mir_query<R>(
600        &self,
601        attempts: usize,
602        f: impl Fn(&mir_analyzer::db::MirDbStorage) -> R,
603    ) -> Option<R> {
604        use std::panic::AssertUnwindSafe;
605        let _interactive = self.interactive_read_guard();
606        let session = self.current_analysis_session();
607        for _ in 0..attempts {
608            let db = session.snapshot_db();
609            match salsa::Cancelled::catch(AssertUnwindSafe(|| f(&db))) {
610                Ok(r) => return Some(r),
611                Err(_) => drop(db),
612            }
613        }
614        None
615    }
616
617    /// Mirror a file's current text into the salsa layer. Creates the
618    /// `FileText` input on first sight, otherwise updates `text` on the
619    /// existing input (bumping the salsa revision so downstream queries
620    /// invalidate).
621    pub fn mirror_text(&self, uri: &Uri, text: &str) {
622        // G2 fast path: compare against the lock-free text cache. When the
623        // new text byte-matches what we already mirrored, skip the host
624        // mutex entirely. Common during workspace scan + `did_open` for
625        // unchanged files, where most threads would otherwise serialise on
626        // `host.lock()` just to confirm a no-op.
627        if let Some(cached) = self.caches.text_cache.get(uri)
628            && **cached == *text
629            && !self.deleted_uris.contains(uri)
630            && self.lsp_ws_files.contains_key(uri)
631        {
632            return;
633        }
634        self.mirror_text_arc(uri, Arc::from(text))
635    }
636
637    /// Like [`mirror_text`] but takes an already-allocated `Arc<str>`.
638    ///
639    /// Callers that already hold an `Arc<str>` (e.g. `ingest_from_doc` reusing
640    /// `ParsedDoc::source_arc()`) use this to avoid a second allocation and to
641    /// ensure `text_cache` and `parsed_cache` hold the same Arc pointer —
642    /// enabling `Arc::ptr_eq` validation in `get_parsed_cached`.
643    pub fn mirror_text_arc(&self, uri: &Uri, text_arc: Arc<str>) {
644        let dur = Self::input_durability(uri);
645        let path: Arc<str> = Arc::from(uri.as_str());
646        let session = self.current_analysis_session();
647        if let Some(wf) = self.lsp_ws_files.get(uri).map(|e| *e) {
648            // A resurrected (previously-deleted) file changes
649            // `workspace_file_paths()`'s result set — invalidate its cache.
650            // The common case (an edit to an already-live file) hits `None`
651            // here and pays nothing extra.
652            if self.deleted_uris.remove(uri).is_some() {
653                self.workspace_file_paths_cache.store(None);
654            }
655            // Fast path: byte-identical text already mirrored — skip the write
656            // lock and the revision bump entirely.
657            if let Some(cached) = self.caches.text_cache.get(uri)
658                && **cached == *text_arc
659            {
660                return;
661            }
662            session.with_db_mut(|db| {
663                let sf = wf.source(db);
664                sf.set_text(db).with_durability(dur).to(text_arc.clone());
665                // Any text change invalidates a previously-seeded cached index.
666                // Only set when present to avoid a spurious second revision bump.
667                if wf.cached_index(db).is_some() {
668                    wf.set_cached_index(db).to(None);
669                }
670            });
671            self.caches.text_cache.insert(uri.clone(), text_arc);
672            // Evict only this file's analysis; cross-file invalidation is handled
673            // lazily in `cached_analysis` via the declaration fingerprint.
674            self.caches.evict_analysis(uri);
675            self.write_revision.fetch_add(1, Ordering::Release);
676        } else {
677            let wf = session.with_db_mut(|db| {
678                let sf = db.upsert_source_file_with_durability(path, text_arc.clone(), dur);
679                LspWsFile::new(db, sf, None)
680            });
681            self.lsp_ws_files.insert(uri.clone(), wf);
682            self.caches.text_cache.insert(uri.clone(), text_arc);
683            self.mark_workspace_files_dirty();
684            self.write_revision.fetch_add(1, Ordering::Release);
685        }
686    }
687
688    /// Return the `LspWsFile` handle for a URL, if active (not deleted).
689    #[cfg(test)]
690    pub fn source_file(&self, uri: &Uri) -> Option<LspWsFile> {
691        if self.deleted_uris.contains(uri) {
692            return None;
693        }
694        self.lsp_ws_files.get(uri).map(|e| *e)
695    }
696
697    /// Phase K2: pre-seed a `FileIndex` loaded from the on-disk cache onto
698    /// the `FileText` input for `uri`. The next `file_index` call for that
699    /// file returns the cached index directly, skipping parse + extract.
700    ///
701    /// Must be called **before** any `file_index(db, sf)` call for this file —
702    /// otherwise salsa has already memoized the fresh-parse result and setting
703    /// `cached_index` now would only bump the revision without using the cache.
704    /// In practice the workspace-scan path seeds immediately after `mirror_text`
705    /// and before any query runs.
706    ///
707    /// Returns `false` when `uri` was not mirrored (caller should mirror
708    /// first); returns `true` on success.
709    pub fn seed_cached_index(&self, uri: &Uri, index: Arc<FileIndex>) -> bool {
710        let Some(wf) = self.lsp_ws_file(uri) else {
711            return false;
712        };
713        let session = self.current_analysis_session();
714        session.with_db_mut(|db| wf.set_cached_index(db).to(Some(index)));
715        true
716    }
717
718    /// Evict the semantic-tokens cache for `uri`. Called by Backend when a
719    /// file is closed; diff-based tokens computed against the old revision
720    /// are no longer meaningful.
721    pub fn evict_token_cache(&self, uri: &Uri) {
722        self.caches.evict_tokens(uri);
723    }
724
725    /// Return the `FileIndex` for `uri` by running `file_index` on a salsa
726    /// snapshot.  Returns `None` when `uri` has not been mirrored.
727    ///
728    /// Test-only — production code uses the salsa query directly via
729    /// `snapshot_query`.
730    #[cfg(test)]
731    pub fn source_files_len(&self) -> usize {
732        self.lsp_ws_files.len()
733    }
734
735    #[cfg(test)]
736    pub fn snapshot_query_file_index(
737        &self,
738        uri: &Uri,
739    ) -> Option<crate::index::file_index::FileIndex> {
740        let wf = self.lsp_ws_file(uri)?;
741        Some(
742            self.snapshot_mir_query(move |db| {
743                (*crate::db::mir_queries::file_index(db, wf).0).clone()
744            }),
745        )
746    }
747
748    /// Register a file in the salsa layer without marking it open.
749    ///
750    /// Salsa's `parsed_doc` query parses lazily on first read; diagnostics
751    /// are populated by `did_open` when the editor actually opens the file.
752    pub fn ingest(&self, uri: Uri, text: &str) {
753        self.mirror_text(&uri, text);
754    }
755
756    /// Index a file using an already-parsed `ParsedDoc`, avoiding a second parse.
757    ///
758    /// Prefer this over [`ingest`] when the caller already has a `ParsedDoc` (e.g.
759    /// after running `DefinitionCollector` during workspace scan). Reuses the
760    /// `Arc<str>` already owned by `doc` so that `text_cache` and `SourceFile::text`
761    /// share the same pointer — enabling the `Arc::ptr_eq` fast path in
762    /// `get_parsed_cached` on the first subsequent salsa query, without an extra
763    /// `Arc::from(source)` allocation.
764    pub fn ingest_from_doc(&self, uri: Uri, doc: &ParsedDoc) {
765        self.mirror_text_arc(&uri, doc.source_arc());
766    }
767
768    pub fn remove(&self, uri: &Uri) {
769        self.caches.evict(uri);
770        // Mark the URI as deleted but keep the `lsp_ws_files` entry so the
771        // salsa `LspWsFile`/`SourceFile` handles remain alive. Re-opening the
772        // file reuses the same handle instead of calling `LspWsFile::new()`
773        // again, which would create a new orphaned salsa input on every
774        // delete-reopen cycle. `session.invalidate_file` below already frees
775        // the (potentially large) text this handle holds via mir's own
776        // `remove_source_file`, so keeping the handle costs only its own
777        // small footprint, not the file's content.
778        self.deleted_uris.insert(uri.clone());
779        self.mark_workspace_files_dirty();
780        // Sync workspace files so the deleted file is removed from the salsa
781        // `Workspace::files` list and won't appear in workspace symbols etc.
782        self.sync_workspace_files();
783        // Also evict the file from the `AnalysisSession`'s internal state so
784        // workspace symbol queries don't keep returning the deleted file's
785        // declarations. Cheap when the session hasn't ingested this file.
786        let guard = self.analysis_session.lock().unwrap();
787        if let Some(session) = guard.1.as_ref() {
788            session.invalidate_file(uri.as_str());
789            // `file_index` has no LRU cap (unlike `parsed_doc`/`symbol_map`),
790            // so without this it would keep holding this file's pre-deletion
791            // `FileIndex` (and any seeded on-disk `cached_index`) in memory
792            // for the rest of the process's life. Clear the seed and force
793            // one recompute against the now-emptied text (`invalidate_file`
794            // above already cleared it via mir's `remove_source_file`) to
795            // shrink the memo to near-nothing immediately.
796            if let Some(wf) = self.lsp_ws_files.get(uri).map(|e| *e) {
797                session.with_db_mut(|db| {
798                    if wf.cached_index(db).is_some() {
799                        wf.set_cached_index(db).to(None);
800                    }
801                });
802                let db = session.snapshot_db();
803                let _ = crate::db::mir_queries::file_index(&db, wf);
804            }
805        }
806        self.write_revision.fetch_add(1, Ordering::Release);
807    }
808
809    // ── Salsa-backed accessors ─────────────────────────────────────────────
810    //
811    // Reads run the memoized `parsed_doc` / `file_index` queries, parsing
812    // only on first access per revision. These are the production accessors
813    // used by every handler.
814
815    /// Salsa-backed parsed document.
816    ///
817    /// Salsa-backed parsed document for any mirrored file (open or
818    /// background-indexed). Returns `None` only when the file is not known
819    /// to the store. Callers that want "only if open" should gate on
820    /// `Backend::open_files` at the call site (see `Backend::get_doc`).
821    pub fn get_doc_salsa(&self, uri: &Uri) -> Option<Arc<ParsedDoc>> {
822        self.get_parsed_cached(uri)
823    }
824
825    /// Salsa-backed compact symbol index.
826    pub fn get_index_salsa(&self, uri: &Uri) -> Option<Arc<FileIndex>> {
827        let wf = self.lsp_ws_file(uri)?;
828        Some(
829            self.snapshot_mir_query(move |db| crate::db::mir_queries::file_index(db, wf).0.clone()),
830        )
831    }
832
833    /// Salsa-backed pre-computed symbol map (name → Vec<SymbolEntry>).
834    /// Memoized per revision: stable files serve from cache in O(1).
835    pub fn get_symbol_map_salsa(
836        &self,
837        uri: &Uri,
838    ) -> Option<Arc<crate::types::symbol_map::SymbolMap>> {
839        // Symbol map runs on the shared mir db, sharing its memoized `parsed_doc`.
840        let wf = self.lsp_ws_file(uri)?;
841        Some(self.snapshot_mir_query(move |db| {
842            let sf = *wf.source(db);
843            crate::db::mir_queries::symbol_map(db, sf).0.clone()
844        }))
845    }
846
847    /// Pre-computed symbol maps for every entry in `open_urls` except `uri`.
848    pub fn other_symbol_maps(
849        &self,
850        uri: &Uri,
851        open_urls: &[Uri],
852    ) -> Vec<(Uri, Arc<crate::types::symbol_map::SymbolMap>)> {
853        open_urls
854            .iter()
855            .filter(|u| *u != uri)
856            .filter_map(|u| self.get_symbol_map_salsa(u).map(|m| (u.clone(), m)))
857            .collect()
858    }
859
860    /// G3: shared implementation for `get_doc_salsa`.
861    /// Tries the `parsed_cache` (lock-free) first; validates via
862    /// `Arc::ptr_eq` against the G2 `text_cache` so a concurrent writer
863    /// that has already committed a new text input cannot be masked by a
864    /// stale cache entry. On miss, captures the text Arc and ParsedDoc
865    /// together inside a single `snapshot_query`, then publishes both.
866    fn get_parsed_cached(&self, uri: &Uri) -> Option<Arc<ParsedDoc>> {
867        if let Some(current_text) = self.caches.text_cache.get(uri)
868            && let Some(entry) = self.caches.parsed_cache.get(uri)
869            && Arc::ptr_eq(&*current_text, &entry.0)
870        {
871            let doc = entry.1.clone();
872            drop(entry);
873            self.caches.touch(uri);
874            return Some(doc);
875        }
876
877        // Parse runs on the shared mir db.
878        let wf = self.lsp_ws_file(uri)?;
879        self.caches.bump_parse_count();
880        let (text, doc) = self.snapshot_mir_query(move |db| {
881            let sf = *wf.source(db);
882            let text = sf.text(db).clone();
883            let doc = crate::db::mir_queries::parsed_doc(db, sf).0.clone();
884            (text, doc)
885        });
886        self.caches.insert_parsed(uri.clone(), text, doc.clone());
887        Some(doc)
888    }
889
890    /// Parsed doc for a cosmetic, cursor-triggered read (e.g. `documentHighlight`)
891    /// that must stay responsive while the user types. Unlike [`Self::get_doc_salsa`]
892    /// it never spins on the `Cancelled` retry loop: it tries the lock-free
893    /// `parsed_cache`, then a bounded snapshot parse, and if a concurrent write
894    /// stream keeps cancelling it, returns the last-good cached `ParsedDoc`
895    /// (possibly one edit stale — invisible for a highlight, unlike a hang).
896    /// `None` only when the file has never been parsed.
897    pub fn get_doc_snapshot_or_stale(&self, uri: &Uri) -> Option<Arc<ParsedDoc>> {
898        if let Some(current_text) = self.caches.text_cache.get(uri)
899            && let Some(entry) = self.caches.parsed_cache.get(uri)
900            && Arc::ptr_eq(&*current_text, &entry.0)
901        {
902            let doc = entry.1.clone();
903            drop(entry);
904            self.caches.touch(uri);
905            return Some(doc);
906        }
907
908        if let Some(wf) = self.lsp_ws_file(uri)
909            && let Some((text, doc)) = self.try_snapshot_mir_query(3, move |db| {
910                let sf = *wf.source(db);
911                let text = sf.text(db).clone();
912                let doc = crate::db::mir_queries::parsed_doc(db, sf).0.clone();
913                (text, doc)
914            })
915        {
916            self.caches.bump_parse_count();
917            self.caches.insert_parsed(uri.clone(), text, doc.clone());
918            return Some(doc);
919        }
920
921        self.caches.parsed_cache.get(uri).map(|e| e.1.clone())
922    }
923
924    /// Refresh `workspace.files` to mirror the current active file set.
925    ///
926    /// Skips all work when `workspace_files_dirty` is `false` (the common
927    /// case after the workspace scan completes — file-set changes are rare).
928    pub fn sync_workspace_files(&self) {
929        // Atomically clear the flag.  If it was already false the file set
930        // hasn't changed since the last sync; nothing to do.
931        if !self.workspace_files_dirty.swap(false, Ordering::AcqRel) {
932            return;
933        }
934
935        // Collect active (non-deleted) files, sorted by URI for stable ordering.
936        let mut entries: Vec<(Arc<str>, LspWsFile)> = self
937            .lsp_ws_files
938            .iter()
939            .filter(|e| !self.deleted_uris.contains(e.key()))
940            .map(|e| (Arc::<str>::from(e.key().as_str()), *e.value()))
941            .collect();
942        entries.sort_unstable_by(|(a, _), (b, _)| a.cmp(b));
943        let files: Arc<[LspWsFile]> = entries.iter().map(|(_, wf)| *wf).collect();
944
945        let session = self.current_analysis_session();
946        let mut guard = self.lsp_workspace.lock().unwrap();
947        session.with_db_mut(|db| match *guard {
948            Some(ws) => {
949                ws.set_files(db).to(files);
950            }
951            None => *guard = Some(LspWorkspace::new(db, files)),
952        });
953    }
954
955    /// Mark the workspace file set as dirty so the next `sync_workspace_files`
956    /// call re-runs the collect/sort/compare path, and invalidate the
957    /// `workspace_file_paths()` cache. Exposed for benchmarks that need to
958    /// measure the dirty-path cost in isolation.
959    pub fn mark_workspace_files_dirty(&self) {
960        self.workspace_files_dirty.store(true, Ordering::Release);
961        self.workspace_file_paths_cache.store(None);
962    }
963
964    /// Update the PHP version tracked by the workspace. Salsa will invalidate
965    /// all `semantic_issues` queries so diagnostics are re-evaluated.
966    /// Skips the setter when the version hasn't changed to avoid spurious
967    /// query invalidation. Returns `true` when the version actually changed —
968    /// callers that scan the workspace at runtime (not just at init, before
969    /// any file is mirrored) must re-scan every root when this is `true`,
970    /// since `drop_session_scoped_state` below empties `lsp_ws_files` and
971    /// nothing else repopulates it.
972    pub fn set_php_version(&self, version: mir_analyzer::PhpVersion) -> bool {
973        {
974            let mut guard = self.analysis_session.lock().unwrap();
975            if guard.0 == version {
976                return false;
977            }
978            // Clear the cached session too: `current_analysis_session()` trusts
979            // `guard.1` unconditionally when present, so leaving the old
980            // version's session behind here would silently hand it out under
981            // the new version until something calls `analysis_session(version)`
982            // explicitly to force the mismatch-triggered rebuild.
983            guard.0 = version;
984            guard.1 = None;
985        }
986        // Changing the version selects a different `AnalysisSession` (and thus
987        // a different db). In practice the version is set once at init, before
988        // any file is mirrored — but a runtime change is possible too (the
989        // caller must re-scan in that case, see the `bool` return above).
990        self.drop_session_scoped_state();
991        true
992    }
993
994    /// Discard every piece of state scoped to the current `AnalysisSession`'s
995    /// salsa db. MUST accompany anything that causes `analysis_session()` to
996    /// hand out a different db (version change, cache-dir attach): the
997    /// `LspWsFile` input handles in `lsp_ws_files` index into the *old* db's
998    /// tables, and using one against a new db panics with a salsa slot-type
999    /// mismatch. The workspace scan (or the next edit) re-mirrors files onto
1000    /// the new session.
1001    fn drop_session_scoped_state(&self) {
1002        self.lsp_ws_files.clear();
1003        *self.lsp_workspace.lock().unwrap() = None;
1004        self.mark_workspace_files_dirty();
1005        // Cached FileAnalysis values reference the old session's state.
1006        self.caches.evict_analysis_all();
1007    }
1008
1009    /// Inverted-index reference lookup scoped to `files` (the text-pre-filtered
1010    /// candidate set): a posting-list read for committed-fresh files plus an
1011    /// on-demand analyze+commit for stale/uncommitted candidates, so warm
1012    /// requests are O(results) instead of O(candidates).
1013    ///
1014    /// Returns LSP-style 0-based line/column.
1015    ///
1016    /// `cancel_rev`: when `Some(rev)`, the loop throws `salsa::Cancelled` and
1017    /// returns empty if a concurrent write advances the `write_revision` counter
1018    /// past `rev` — preventing unbounded retries against a newly-invalidated db.
1019    /// Pass `None` to retain the original indefinite-retry behaviour (fast ops
1020    /// like single-file reads where a stale result is not a concern).
1021    pub fn indexed_references(
1022        &self,
1023        symbol: &mir_analyzer::Name,
1024        files: &[Arc<str>],
1025        include_declaration: bool,
1026        cancel_rev: Option<u64>,
1027    ) -> Vec<(Arc<str>, u32, u32, u32)> {
1028        let php_version = self.workspace_php_version();
1029        // Staleness probe threaded into mir: polled at phase boundaries and
1030        // between cancellation retries, so a request invalidated by a
1031        // concurrent edit aborts *inside* mir's retry loop instead of spinning
1032        // there indefinitely (mir catches `Cancelled` internally, so an outer
1033        // catch alone never fires for the parallel phase).
1034        let stale =
1035            || cancel_rev.is_some_and(|rev| self.write_revision.load(Ordering::Acquire) != rev);
1036        // Retry: concurrent db writes (background indexing) cancel snapshot
1037        // queries via resume_unwind; without the loop the panic propagates out
1038        // of the caller's spawn_blocking and the request silently returns empty.
1039        let raw = loop {
1040            let session = self.analysis_session(php_version);
1041            match salsa::Cancelled::catch(std::panic::AssertUnwindSafe(|| {
1042                session.indexed_references_to(symbol, files, include_declaration, &stale)
1043            })) {
1044                Ok(Some(refs)) => break refs,
1045                // mir aborted via the staleness probe — or a Phase-1 unwind
1046                // hit an already-stale request. Propagate as salsa::Cancelled
1047                // so spawn_blocking callers see a JoinError::Panicked and
1048                // return empty via unwrap_or_default.
1049                Ok(None) => {
1050                    std::panic::resume_unwind(Box::new(salsa::Cancelled::PendingWrite));
1051                }
1052                Err(_) if stale() => {
1053                    std::panic::resume_unwind(Box::new(salsa::Cancelled::PendingWrite));
1054                }
1055                // Phase-1 unwind from a write that doesn't invalidate this
1056                // request (mir-internal load_class, scan writes with no
1057                // cancel_rev) — retry.
1058                Err(_) => {}
1059            }
1060        };
1061        raw.into_iter()
1062            .map(|(file, range)| {
1063                // mir uses 1-based lines; 0-based columns (since mir 0.42.0).
1064                let line = range.start.line.saturating_sub(1);
1065                let col_start = range.start.column;
1066                let col_end = range.end.column;
1067                (file, line, col_start, col_end)
1068            })
1069            .collect()
1070    }
1071
1072    /// `use`-import lines referencing `symbol`, from mir's `use:` postings.
1073    /// Read-only lookup with no freshness pass — run [`Self::indexed_references`]
1074    /// over the same `files` first so uncommitted candidates are analyzed.
1075    /// Returns `(file_uri, line, col_start, col_end)` tuples like
1076    /// [`Self::indexed_references`]; the range covers the whole import item.
1077    pub fn indexed_use_imports(
1078        &self,
1079        symbol: &mir_analyzer::Name,
1080        files: &[Arc<str>],
1081    ) -> Vec<(Arc<str>, u32, u32, u32)> {
1082        let session = self.current_analysis_session();
1083        let _interactive = self.interactive_read_guard();
1084        let raw = loop {
1085            if let Ok(locs) = salsa::Cancelled::catch(std::panic::AssertUnwindSafe(|| {
1086                session.indexed_use_import_locations(symbol, files)
1087            })) {
1088                break locs;
1089            }
1090        };
1091        raw.into_iter()
1092            .map(|(file, range)| {
1093                // mir uses 1-based lines; 0-based columns.
1094                let line = range.start.line.saturating_sub(1);
1095                (file, line, range.start.column, range.end.column)
1096            })
1097            .collect()
1098    }
1099
1100    /// Replay disk-cached reference postings and subtype edges for the whole
1101    /// mirrored workspace (mir's `warm_start_files`) — a no-op per file
1102    /// without a content-hash-matching cache entry from a previous run. Call
1103    /// once after the scan mirrors texts, before the analysis warm sweep, so
1104    /// a returning session starts index-warm.
1105    pub fn warm_start_indexes(&self) {
1106        let files: Vec<(Arc<str>, Arc<str>)> = self
1107            .lsp_ws_files
1108            .iter()
1109            .filter(|e| !self.deleted_uris.contains(e.key()))
1110            .filter_map(|e| {
1111                let text = self.caches.text_cache.get(e.key())?;
1112                Some((Arc::<str>::from(e.key().as_str()), Arc::clone(&text)))
1113            })
1114            .collect();
1115        if files.is_empty() {
1116            return;
1117        }
1118        let session = self.current_analysis_session();
1119        session.warm_start_files(&files);
1120        self.warm_start_replays_completed
1121            .fetch_add(1, Ordering::Relaxed);
1122    }
1123
1124    /// Candidate file scope for a posting lookup on `symbol`.
1125    /// Private/protected methods narrow to their visibility scope; everything
1126    /// else gets the whole workspace. mir gates never-committed candidates on
1127    /// a symbol-name text mention internally (with PHP's case-insensitive
1128    /// matching semantics), so a host-side text prefilter would only re-scan
1129    /// the same bytes with weaker semantics.
1130    pub(crate) fn reference_candidate_files(&self, symbol: &mir_analyzer::Name) -> Vec<Arc<str>> {
1131        match symbol {
1132            mir_analyzer::Name::Method { class, name } => {
1133                if let Some(urls) = self.method_reference_scope(class, name) {
1134                    return urls.iter().map(|u| Arc::from(u.as_str())).collect();
1135                }
1136            }
1137            // A class reference always textually resolves the name in the
1138            // referencing file (import, namespace, or qualified path) —
1139            // there's no instance-typed-receiver indirection here, so FQN
1140            // narrowing is always sound.
1141            mir_analyzer::Name::Class(fqcn) => {
1142                if let Some(files) = self.fqn_reachable_files(std::slice::from_ref(fqcn)) {
1143                    return files;
1144                }
1145            }
1146            // Functions/constants resolve like class names ONLY when
1147            // namespaced: an unqualified call to a *global* one (`env()`,
1148            // `PHP_EOL`) works from any namespace via PHP's global
1149            // fallback, so no file can be excluded for those.
1150            mir_analyzer::Name::Function(fqcn) | mir_analyzer::Name::GlobalConstant(fqcn) => {
1151                if fqcn.trim_start_matches('\\').contains('\\')
1152                    && let Some(files) = self.fqn_reachable_files(std::slice::from_ref(fqcn))
1153                {
1154                    return files;
1155                }
1156            }
1157            _ => {}
1158        }
1159        self.workspace_file_paths().to_vec()
1160    }
1161
1162    /// Every active workspace file as a mir path (`Arc<str>` of the URI).
1163    /// The candidate scope handed to mir's queries — mir gates uncommitted
1164    /// candidates on symbol-name mention internally, so this is always safe.
1165    ///
1166    /// Cached behind an `Arc` (invalidated by `mark_workspace_files_dirty`) so
1167    /// the ~15K-file walk + `Arc<str>` allocation per file only happens once
1168    /// per workspace-file-set change, not once per caller per request.
1169    pub fn workspace_file_paths(&self) -> Arc<Vec<Arc<str>>> {
1170        if let Some(cached) = self.workspace_file_paths_cache.load_full() {
1171            return cached;
1172        }
1173        let files: Arc<Vec<Arc<str>>> = Arc::new(
1174            self.lsp_ws_files
1175                .iter()
1176                .filter(|e| !self.deleted_uris.contains(e.key()))
1177                .map(|e| Arc::<str>::from(e.key().as_str()))
1178                .collect(),
1179        );
1180        self.workspace_file_paths_cache
1181            .store(Some(Arc::clone(&files)));
1182        files
1183    }
1184
1185    /// Transitive subtypes of `class_fqn` from mir's maintained subtype edge
1186    /// index, with declaration sites. `include_trait_users` also counts
1187    /// `use Trait;` composition as a subtype edge (trait-usage lenses); leave
1188    /// it off for goto-implementation semantics (extends/implements only).
1189    pub fn indexed_subtype_classes(
1190        &self,
1191        class_fqn: &str,
1192        include_trait_users: bool,
1193    ) -> Vec<mir_analyzer::SubtypeClassSite> {
1194        let files = self.workspace_file_paths();
1195        let session = self.current_analysis_session();
1196        let _interactive = self.interactive_read_guard();
1197        loop {
1198            if let Ok(sites) = salsa::Cancelled::catch(std::panic::AssertUnwindSafe(|| {
1199                session.indexed_subtype_classes(class_fqn, &files, include_trait_users)
1200            })) {
1201                break sites;
1202            }
1203        }
1204    }
1205
1206    /// Concrete implementations of `class_fqn::method` across its subtypes:
1207    /// `(subtype fqcn, file, name range)` from mir's subtype edge index.
1208    pub fn indexed_method_implementations(
1209        &self,
1210        class_fqn: &str,
1211        method: &str,
1212    ) -> Vec<(Arc<str>, Arc<str>, mir_analyzer::Range)> {
1213        let files = self.workspace_file_paths();
1214        let session = self.current_analysis_session();
1215        let _interactive = self.interactive_read_guard();
1216        loop {
1217            if let Ok(sites) = salsa::Cancelled::catch(std::panic::AssertUnwindSafe(|| {
1218                session.indexed_method_implementations(class_fqn, method, &files)
1219            })) {
1220                break sites;
1221            }
1222        }
1223    }
1224
1225    /// The complete set of files a `private` method's references can occur in,
1226    /// or `None` when the search must stay workspace-wide.
1227    ///
1228    /// `owner_fqn` is the enclosing class at the cursor; narrowing applies only
1229    /// when that class *directly declares* `method` (so its `MethodDef`
1230    /// visibility is authoritative — inherited/call-site lookups fall through to
1231    /// `None`). A reference to `Class::method` is recorded only where
1232    /// `analyze_file` resolves an expression to that key, and `analyze_file` is
1233    /// per-source-file, so a `private` member — resolvable only inside the
1234    /// declaring class body, which lives in one file — is fully scoped to the
1235    /// declaring file at any indexing stage.
1236    ///
1237    /// A `protected` member is reachable from the declaring class and its
1238    /// transitive subclasses (`$this->m()`, `parent::m()`, `self::`/`static::`),
1239    /// all of which live in the declaring file or a subtype file — never outside
1240    /// the hierarchy in valid PHP. Its scope is therefore the declaring file plus
1241    /// the transitive subtype files. The complete subtype set is only known once
1242    /// the workspace reference index finishes, so this narrowing applies only
1243    /// when [`Self::is_index_ready`]; before then it falls back to `None` (full
1244    /// workspace scope) so references are never under-reported.
1245    ///
1246    /// Classes that compose traits or mixins are excluded — those inline
1247    /// external resolution context, so a reference could surface in another file.
1248    pub fn method_reference_scope(&self, owner_fqn: &str, method: &str) -> Option<Vec<Uri>> {
1249        match self.method_reference_scope_plan(owner_fqn, method) {
1250            MethodScopePlan::Files(files) => Some(files),
1251            MethodScopePlan::NeedsScan { fqns, extra_needle } => {
1252                let files =
1253                    self.fqn_reachable_files_with_needles(&fqns, &[extra_needle.as_str()])?;
1254                Some(
1255                    files
1256                        .iter()
1257                        .filter_map(|f| (f).parse::<Uri>().ok())
1258                        .collect(),
1259                )
1260            }
1261            MethodScopePlan::FullWorkspace => None,
1262        }
1263    }
1264
1265    /// Whether [`Self::reference_candidate_files`] narrows `class::method`'s
1266    /// scope below the full workspace, without paying for the narrowing scan
1267    /// itself. A caller that further partitions the candidate set by a
1268    /// heuristic text mention (references' priority-result streaming) only
1269    /// has anything to gain when the scope is *not* already narrowed — a
1270    /// narrowed scope is already the minimal necessary set, so partitioning
1271    /// it further just re-scans those files' bytes for no benefit.
1272    pub(crate) fn method_scope_is_narrowed(&self, owner_fqn: &str, method: &str) -> bool {
1273        !matches!(
1274            self.method_reference_scope_plan(owner_fqn, method),
1275            MethodScopePlan::FullWorkspace
1276        )
1277    }
1278
1279    /// Same narrowing decision as [`Self::method_reference_scope`], but stops
1280    /// short of running the FQN/text-needle scan itself — that scan is the
1281    /// expensive part (a parallel pass over every workspace file), and a
1282    /// caller resolving many methods at once (code lens, one call per
1283    /// declaration in a file) needs to batch it across methods via
1284    /// [`Self::resolve_reachability_queries`] instead of paying it per call.
1285    fn method_reference_scope_plan(&self, owner_fqn: &str, method: &str) -> MethodScopePlan {
1286        use crate::index::file_index::{ClassKind, Visibility};
1287
1288        let ws = self.get_workspace_index_salsa();
1289        let owner_fqn = owner_fqn.trim_start_matches('\\');
1290        let owner_short = crate::text::fqn_short_name(owner_fqn);
1291
1292        let Some((decl_uri, decl_class)) = ws.classes_by_name.get(owner_short).and_then(|refs| {
1293            refs.iter()
1294                .filter_map(|&r| ws.at(r))
1295                .find(|(_, cls)| cls.fqn.trim_start_matches('\\') == owner_fqn)
1296        }) else {
1297            return MethodScopePlan::FullWorkspace;
1298        };
1299
1300        // Trait/interface methods, and methods on classes that compose traits or
1301        // mixins, can be referenced from other files — keep the full scope.
1302        if !matches!(decl_class.kind, ClassKind::Class | ClassKind::Enum)
1303            || !decl_class.traits.is_empty()
1304            || !decl_class.mixins.is_empty()
1305        {
1306            return MethodScopePlan::FullWorkspace;
1307        }
1308
1309        let Some(method_def) = decl_class
1310            .methods
1311            .iter()
1312            .find(|m| m.name.eq_ignore_ascii_case(method))
1313        else {
1314            return MethodScopePlan::FullWorkspace;
1315        };
1316
1317        match method_def.visibility {
1318            Visibility::Private => MethodScopePlan::Files(vec![decl_uri.clone()]),
1319            Visibility::Protected => {
1320                if !self.is_index_ready() {
1321                    return MethodScopePlan::FullWorkspace;
1322                }
1323                // Subtype set comes from mir's resolved inheritance graph — it
1324                // matches subclasses by FQCN, so `extends \Ns\Base` and aliased
1325                // `use ... as` forms are all found. Falls back to full scope if
1326                // mir can't resolve the owner.
1327                let session = self.current_analysis_session();
1328                let mut files: std::collections::HashSet<Uri> = session
1329                    .subtype_files(owner_fqn)
1330                    .into_iter()
1331                    .filter_map(|p| p.parse::<Uri>().ok())
1332                    .collect();
1333                files.insert(decl_uri.clone());
1334                MethodScopePlan::Files(files.into_iter().collect())
1335            }
1336            // A public *static* method's call sites come in exactly two
1337            // textual shapes: a resolved class name (`Owner::m()`, inherited
1338            // `Sub::m()`, `self::`/`static::`/`parent::m()` from inside the
1339            // hierarchy, aliased `use Owner as X; X::m()` — all covered by
1340            // owner+subtype FQN reachability) or an *instance* receiver
1341            // (`$obj::m()`, whose file may never name the class but always
1342            // contains the member token — covered by the member-name
1343            // needle). Dynamic member names (`Owner::$m()`) produce no
1344            // posting at all (verified), so the union is exhaustive. This
1345            // beats mir's own gate, which only sees bare short names and
1346            // can't tell this owner apart from an unrelated class sharing
1347            // its short name. Instance methods stay unnarrowed
1348            // (`FullWorkspace` below): a typed receiver can hide both the
1349            // class *and* any distinguishing token cheaper than the member
1350            // name itself.
1351            Visibility::Public
1352                if method_def.is_static || method.eq_ignore_ascii_case("__construct") =>
1353            {
1354                if !self.is_index_ready() {
1355                    return MethodScopePlan::FullWorkspace;
1356                }
1357                let mut fqns: Vec<Arc<str>> = vec![Arc::from(owner_fqn)];
1358                fqns.extend(
1359                    self.indexed_subtype_classes(owner_fqn, false)
1360                        .into_iter()
1361                        .map(|s| s.fqcn),
1362                );
1363                // `__construct`'s extra needle is the call-shaped
1364                // `->__construct` (explicit re-init on a typed receiver),
1365                // not the bare identifier — that would drag in every file
1366                // *declaring* a constructor. `new X` sites and
1367                // `parent::`/`self::`/`static::__construct()` calls need no
1368                // needle: the former textually resolve an owner/subtype
1369                // name, the latter live inside hierarchy files, which the
1370                // subtype closure's namespace rule already admits (unlike
1371                // mir's own gate, which lacks the closure and keeps a
1372                // `::__construct` token for the grandchild-`parent::` case).
1373                let extra_needle = if method.eq_ignore_ascii_case("__construct") {
1374                    "->__construct".to_string()
1375                } else {
1376                    method.to_string()
1377                };
1378                MethodScopePlan::NeedsScan { fqns, extra_needle }
1379            }
1380            Visibility::Public => MethodScopePlan::FullWorkspace,
1381        }
1382    }
1383
1384    /// Batched form of [`Self::reference_candidate_files`]: resolves the
1385    /// candidate scope for every symbol in `symbols` while sharing ONE pass
1386    /// over the workspace for every symbol whose scope needs FQN/text-needle
1387    /// narrowing (class references, public static methods, constructors),
1388    /// instead of one pass per symbol.
1389    ///
1390    /// Code lens is the motivating caller: a single file's declarations can
1391    /// produce dozens of reference-count lenses in one request, and each
1392    /// used to pay its own full `ws.files` scan via
1393    /// [`Self::fqn_reachable_files_with_needles`] — O(declarations × files)
1394    /// text scans instead of the one pass this performs.
1395    ///
1396    /// Order-preserving: `result[i]` is the scope for `symbols[i]`.
1397    pub(crate) fn batch_reference_candidate_files(
1398        &self,
1399        symbols: &[mir_analyzer::Name],
1400    ) -> Vec<Vec<Arc<str>>> {
1401        let mut results: Vec<Option<Vec<Arc<str>>>> = vec![None; symbols.len()];
1402        let mut queries: Vec<ReachabilityQuery> = Vec::new();
1403        // queries[k] resolves the scope for symbols[query_targets[k]].
1404        let mut query_targets: Vec<usize> = Vec::new();
1405
1406        for (i, symbol) in symbols.iter().enumerate() {
1407            match symbol {
1408                mir_analyzer::Name::Method { class, name } => {
1409                    match self.method_reference_scope_plan(class, name) {
1410                        MethodScopePlan::Files(urls) => {
1411                            results[i] = Some(urls.iter().map(|u| Arc::from(u.as_str())).collect());
1412                        }
1413                        MethodScopePlan::NeedsScan { fqns, extra_needle } => {
1414                            queries.push(ReachabilityQuery {
1415                                fqns,
1416                                extra_needles: vec![extra_needle],
1417                            });
1418                            query_targets.push(i);
1419                        }
1420                        MethodScopePlan::FullWorkspace => {}
1421                    }
1422                }
1423                mir_analyzer::Name::Class(fqcn) => {
1424                    queries.push(ReachabilityQuery {
1425                        fqns: vec![fqcn.clone()],
1426                        extra_needles: Vec::new(),
1427                    });
1428                    query_targets.push(i);
1429                }
1430                mir_analyzer::Name::Function(fqcn) | mir_analyzer::Name::GlobalConstant(fqcn)
1431                    if fqcn.trim_start_matches('\\').contains('\\') =>
1432                {
1433                    queries.push(ReachabilityQuery {
1434                        fqns: vec![fqcn.clone()],
1435                        extra_needles: Vec::new(),
1436                    });
1437                    query_targets.push(i);
1438                }
1439                _ => {}
1440            }
1441        }
1442
1443        if !queries.is_empty()
1444            && let Some(scanned) = self.resolve_reachability_queries(&queries)
1445        {
1446            for (files, target) in scanned.into_iter().zip(query_targets) {
1447                results[target] = Some(files);
1448            }
1449        }
1450
1451        let fallback = self.workspace_file_paths();
1452        results
1453            .into_iter()
1454            .map(|r| r.unwrap_or_else(|| fallback.as_ref().clone()))
1455            .collect()
1456    }
1457
1458    /// See the `reachability_scan_passes` field's docs. Exposed via
1459    /// `debugStats` so a protocol-level test can assert a request with many
1460    /// narrowing-requiring declarations (code lens) pays one scan pass, not
1461    /// one per declaration.
1462    pub(crate) fn reachability_scan_passes(&self) -> u64 {
1463        self.reachability_scan_passes.load(Ordering::Relaxed)
1464    }
1465
1466    /// See the `analysis_compute_count` field's docs.
1467    pub(crate) fn analysis_compute_count(&self) -> u64 {
1468        self.analysis_compute_count.load(Ordering::Relaxed)
1469    }
1470
1471    /// Files that could possibly reference any FQN in `fqns`, narrowed via
1472    /// PHP's own name-resolution rules rather than bare-word text mention:
1473    ///
1474    /// 1. **Namespace rule** — the file's namespace equals the target's, or
1475    ///    is a `\`-segment prefix of it: `namespace Foo;` reaches
1476    ///    `Foo\Bar\Baz` through the relative-qualified `Bar\Baz`.
1477    /// 2. **Import rule** — a `use` of the target itself, an alias of it, or
1478    ///    any namespace prefix of it (`use Foo\Bar; Bar\Baz::x()`), all
1479    ///    matched on the import's FQN so aliases come for free.
1480    /// 3. **Text rule** — the qualified path appears literally in the file
1481    ///    (`\App\Widget::class` config arrays with no `use` line, or a
1482    ///    leading-slash-free `App\Widget` from a no-namespace file, where
1483    ///    qualified names resolve from the root). Matched
1484    ///    ASCII-case-insensitively — PHP class names are case-insensitive.
1485    ///
1486    /// These are the *only* ways PHP resolves a class-like or namespaced
1487    /// name, so this is exact narrowing grounded in the language's own
1488    /// resolution order, not a heuristic — unlike mir's own gate, which
1489    /// only sees bare short names and can't distinguish this owner class
1490    /// from an unrelated class sharing its short name elsewhere in the
1491    /// workspace.
1492    ///
1493    /// Callers must NOT use this for global-namespace functions/constants
1494    /// (unqualified calls fall back to the global namespace from *any*
1495    /// namespace, so no file can be excluded) or for instance members (a
1496    /// typed receiver can hide the class entirely).
1497    ///
1498    /// Returns `None` (full workspace) when the boot scan hasn't finished —
1499    /// same conservative discipline as the `Protected` branch above — so
1500    /// references are never under-reported at cold start.
1501    pub fn fqn_reachable_files(&self, fqns: &[Arc<str>]) -> Option<Vec<Arc<str>>> {
1502        self.fqn_reachable_files_with_needles(fqns, &[])
1503    }
1504
1505    /// [`Self::fqn_reachable_files`] plus files whose text contains any of
1506    /// `extra_needles` (ASCII-case-insensitive substring, no word bounds).
1507    /// The union is what makes member-symbol narrowing sound: a static call
1508    /// through an *instance* receiver (`$obj::make()`) or an explicit
1509    /// re-init (`$obj->__construct()`) references a member without the file
1510    /// ever resolving the owner's name, but its text always contains the
1511    /// call token itself.
1512    ///
1513    /// A single-query call through [`Self::resolve_reachability_queries`] —
1514    /// see that method for the batched form multiple callers share.
1515    fn fqn_reachable_files_with_needles(
1516        &self,
1517        fqns: &[Arc<str>],
1518        extra_needles: &[&str],
1519    ) -> Option<Vec<Arc<str>>> {
1520        let query = ReachabilityQuery {
1521            fqns: fqns.to_vec(),
1522            extra_needles: extra_needles.iter().map(|n| n.to_string()).collect(),
1523        };
1524        self.resolve_reachability_queries(std::slice::from_ref(&query))
1525            .map(|mut per_query| per_query.pop().expect("one query in, one result out"))
1526    }
1527
1528    /// Resolves many [`Self::fqn_reachable_files_with_needles`]-shaped
1529    /// queries in a single pass over the workspace, so N callers share one
1530    /// scan instead of paying N.
1531    ///
1532    /// The namespace/import checks are cheap in-memory field comparisons and
1533    /// stay per-query, but the qualified-mention fallback scans each
1534    /// candidate's full text — that scan is what gets shared: every query's
1535    /// needles feed one combined Aho-Corasick automaton, so a file pays one
1536    /// text pass regardless of how many queries are outstanding, instead of
1537    /// one pass per query. Each match is attributed back to its owning
1538    /// query by pattern id.
1539    ///
1540    /// Returns `None` for every query when the boot scan hasn't finished —
1541    /// same conservative discipline as the single-query form — so
1542    /// references are never under-reported at cold start.
1543    fn resolve_reachability_queries(
1544        &self,
1545        queries: &[ReachabilityQuery],
1546    ) -> Option<Vec<Vec<Arc<str>>>> {
1547        use rayon::prelude::*;
1548
1549        if !self.is_index_ready() {
1550            return None;
1551        }
1552        if queries.is_empty() {
1553            return Some(Vec::new());
1554        }
1555        self.reachability_scan_passes
1556            .fetch_add(1, Ordering::Relaxed);
1557
1558        // Per-query targets/namespaces for the cheap checks, plus one needle
1559        // list tagging each pattern with the query it belongs to (a query's
1560        // FQN needles and extra needles can both contribute patterns).
1561        let mut per_query_targets: Vec<Vec<&str>> = Vec::with_capacity(queries.len());
1562        let mut per_query_namespaces: Vec<Vec<Option<&str>>> = Vec::with_capacity(queries.len());
1563        let mut all_needles: Vec<String> = Vec::new();
1564        let mut needle_query: Vec<usize> = Vec::new();
1565
1566        for (qi, q) in queries.iter().enumerate() {
1567            let targets: Vec<&str> = q.fqns.iter().map(|f| f.trim_start_matches('\\')).collect();
1568            let namespaces: Vec<Option<&str>> = targets
1569                .iter()
1570                .map(|t| t.rsplit_once('\\').map(|(ns, _)| ns))
1571                .collect();
1572            // Namespaced targets match with or without the leading `\`; a
1573            // bare global name keeps it (the short name alone would match
1574            // everything).
1575            for t in &targets {
1576                all_needles.push(if t.contains('\\') {
1577                    (*t).to_string()
1578                } else {
1579                    format!("\\{t}")
1580                });
1581                needle_query.push(qi);
1582            }
1583            for n in &q.extra_needles {
1584                all_needles.push(n.clone());
1585                needle_query.push(qi);
1586            }
1587            per_query_targets.push(targets);
1588            per_query_namespaces.push(namespaces);
1589        }
1590        let finder = aho_corasick::AhoCorasick::builder()
1591            .ascii_case_insensitive(true)
1592            .build(&all_needles)
1593            .ok()?;
1594
1595        let ws = self.get_workspace_index_salsa();
1596        let n = queries.len();
1597        // For a common short name most of the corpus fails the cheap
1598        // namespace/import checks and falls through to the text scan, so
1599        // this must run in parallel (mir's own equivalent gate scan does
1600        // the same) or a cold query on a 15K-file workspace pays a
1601        // multi-second sequential scan instead of the few-ms parallel one.
1602        let per_file_matches: Vec<(Arc<str>, Vec<bool>)> = ws
1603            .files
1604            .par_iter()
1605            .filter_map(|(url, idx)| {
1606                let file_ns = idx.namespace.as_deref().map(|s| s.trim_start_matches('\\'));
1607                let mut matched = vec![false; n];
1608                let mut unresolved = 0usize;
1609                for qi in 0..n {
1610                    let ns_match = per_query_namespaces[qi]
1611                        .iter()
1612                        .any(|ns| match (file_ns, ns) {
1613                            (Some(f), Some(t)) => fqn_segment_prefix(f, t),
1614                            (None, None) => true,
1615                            // Global-ns files reach namespaced targets only via
1616                            // the full path (text rule); namespaced files reach
1617                            // global classes only via `\Name` or an import.
1618                            _ => false,
1619                        });
1620                    if ns_match {
1621                        matched[qi] = true;
1622                        continue;
1623                    }
1624                    let import_match = idx.use_imports.iter().any(|(_, f)| {
1625                        let f = f.trim_start_matches('\\');
1626                        per_query_targets[qi]
1627                            .iter()
1628                            .any(|t| fqn_segment_prefix(f, t))
1629                    });
1630                    if import_match {
1631                        matched[qi] = true;
1632                        continue;
1633                    }
1634                    unresolved += 1;
1635                }
1636                if unresolved > 0
1637                    && let Some(text) = self.source_text(url)
1638                {
1639                    // Enumerate matches but stop as soon as every query still
1640                    // unresolved by the cheap checks has been hit once —
1641                    // bounds the scan to the number of distinct needles that
1642                    // actually occur, not every occurrence of a common one.
1643                    for m in finder.find_iter(text.as_ref()) {
1644                        let qi = needle_query[m.pattern().as_usize()];
1645                        if !matched[qi] {
1646                            matched[qi] = true;
1647                            unresolved -= 1;
1648                            if unresolved == 0 {
1649                                break;
1650                            }
1651                        }
1652                    }
1653                }
1654                matched
1655                    .iter()
1656                    .any(|&m| m)
1657                    .then(|| (Arc::<str>::from(url.as_str()), matched))
1658            })
1659            .collect();
1660
1661        let mut out: Vec<Vec<Arc<str>>> = vec![Vec::new(); n];
1662        for (file, matched) in per_file_matches {
1663            for (qi, out_files) in out.iter_mut().enumerate() {
1664                if matched[qi] {
1665                    out_files.push(file.clone());
1666                }
1667            }
1668        }
1669        Some(out)
1670    }
1671
1672    /// Phase J: salsa-memoized aggregate workspace index.
1673    ///
1674    /// Returns the shared `Arc<WorkspaceIndexData>` with flat
1675    /// `(Uri, Arc<FileIndex>)` list plus pre-built `classes_by_name` and
1676    /// `subtypes_of` reverse maps. Used by workspace_symbols,
1677    /// prepare_type_hierarchy, supertypes_of, subtypes_of, and
1678    /// find_implementations so they don't each rebuild the aggregate per
1679    /// request. Invalidates automatically when any file's `file_index`
1680    /// changes.
1681    pub fn get_workspace_index_salsa(&self) -> Arc<crate::db::workspace_index::WorkspaceIndexData> {
1682        self.sync_workspace_files();
1683        let ws = *self.lsp_workspace.lock().unwrap();
1684        let Some(ws) = ws else {
1685            return Arc::new(crate::db::workspace_index::WorkspaceIndexData::from_files(
1686                Vec::new(),
1687            ));
1688        };
1689        self.snapshot_mir_query(move |db| crate::db::mir_queries::workspace_index(db, ws).0.clone())
1690    }
1691
1692    /// Total number of real `ParsedDoc` parses served so far (cache misses).
1693    /// Surfaced via `$/php-lsp/debugStats` so tests can assert the references
1694    /// read path doesn't parse the whole workspace.
1695    pub fn parse_count(&self) -> u64 {
1696        self.caches.parse_count()
1697    }
1698
1699    /// Times mir's `RefIndex` was locked on the current session. Reads are
1700    /// per-key posting lookups and edits commit one file's postings, so this
1701    /// grows by a small bounded amount per operation — never per candidate.
1702    /// Surfaced via `$/php-lsp/debugStats` for the stress-test guard.
1703    pub fn ref_index_lock_count(&self) -> u64 {
1704        self.current_analysis_session().ref_index_lock_count()
1705    }
1706
1707    /// Whether mir's workspace symbol index singleton is populated (warm-start
1708    /// seed or first sweep). See `DebugStats::workspace_symbol_index_ready`.
1709    pub fn workspace_symbol_index_ready(&self) -> bool {
1710        self.analysis_session(self.workspace_php_version())
1711            .workspace_symbol_index_ready()
1712    }
1713
1714    /// Executions of mir's tracked O(all-files) symbol-index walk.
1715    pub fn workspace_index_walks(&self) -> u64 {
1716        self.analysis_session(self.workspace_php_version())
1717            .workspace_index_walks()
1718    }
1719
1720    /// Return the raw source text for `uri` if it has been mirrored into the
1721    /// salsa workspace. Used by the references handler to pre-filter session
1722    /// results by checking whether a file mentions the owning class name.
1723    pub fn source_text(&self, uri: &Uri) -> Option<Arc<str>> {
1724        self.caches.text_cache.get(uri).map(|e| Arc::clone(&e))
1725    }
1726
1727    /// Cache the semantic tokens computed for a delta response.
1728    /// `result_id` is an opaque string (a hash of the token data) returned to the client.
1729    pub fn store_token_cache(&self, uri: &Uri, result_id: String, tokens: Arc<Vec<SemanticToken>>) {
1730        self.caches.store_token(uri, result_id, tokens);
1731    }
1732
1733    /// Return the cached tokens if `result_id` matches the stored one.
1734    pub fn get_token_cache(&self, uri: &Uri, result_id: &str) -> Option<Arc<Vec<SemanticToken>>> {
1735        self.caches.get_token(uri, result_id)
1736    }
1737
1738    /// Raw semantic issues for a file, computed via mir's session-based
1739    /// `FileAnalyzer`. The session lazy-loads dependencies via PSR-4 so the
1740    /// LSP no longer needs to mirror vendor up-front. Callers apply their
1741    /// own `DiagnosticsConfig` filter via
1742    /// [`crate::semantic_diagnostics::issues_to_diagnostics`].
1743    #[tracing::instrument(skip_all)]
1744    pub fn get_semantic_issues_salsa(&self, uri: &Uri) -> Option<Arc<[mir_issues::Issue]>> {
1745        let analysis = self.cached_analysis(uri)?;
1746        let file: Arc<str> = Arc::from(uri.as_str());
1747        // Workspace-level class issues for this file (circular inheritance,
1748        // override violations, abstract-method gaps). These are session-wide
1749        // (a dependency edit changes them without changing this file's bytes),
1750        // so they are recomputed live rather than cached alongside the
1751        // per-file body analysis.
1752        let class_issues = {
1753            let _s = tracing::debug_span!("session.class_issues_for").entered();
1754            // Retry: concurrent db writes cancel snapshot queries via resume_unwind.
1755            loop {
1756                let session = self.current_analysis_session();
1757                if let Ok(issues) = salsa::Cancelled::catch(std::panic::AssertUnwindSafe(|| {
1758                    session.class_issues(std::slice::from_ref(&file))
1759                })) {
1760                    break issues;
1761                }
1762            }
1763        };
1764        let combined: Vec<mir_issues::Issue> = analysis
1765            .issues
1766            .iter()
1767            .cloned()
1768            .chain(class_issues)
1769            .filter(|i| !i.suppressed)
1770            .collect();
1771        Some(Arc::from(combined))
1772    }
1773
1774    /// Run (or reuse) mir's per-file body analysis, retaining the full
1775    /// [`mir_analyzer::FileAnalysis`] — issues **and** resolved symbols — across
1776    /// requests. Diagnostics read `.issues`; position features call
1777    /// `.symbol_at(offset)` for the resolved type at a cursor.
1778    ///
1779    /// Cache hit when the entry's captured source `Arc` is pointer-equal to the
1780    /// file's current `doc.source_arc()`. A miss recomputes and overwrites, so
1781    /// the entry self-evicts on any content edit.
1782    /// Cache-hit-only variant of [`Self::cached_analysis`]: returns the cached
1783    /// analysis when the entry is current for the file's text, never computes.
1784    /// Lets async handlers take the warm path synchronously and reserve
1785    /// `spawn_blocking` for the cold path (mir Pass 1 + Pass 2 can take
1786    /// hundreds of ms on large files).
1787    pub fn cached_analysis_if_fresh(&self, uri: &Uri) -> Option<Arc<mir_analyzer::FileAnalysis>> {
1788        let doc = self.get_doc_salsa(uri)?;
1789        let source = doc.source_arc();
1790        let cur_ver = self.caches.decl_version();
1791        let analysis = {
1792            let entry = self.caches.analysis_cache.get(uri)?;
1793            (Arc::ptr_eq(&entry.0, &source) && entry.1 == cur_ver).then(|| Arc::clone(&entry.2))?
1794        };
1795        self.caches.touch(uri);
1796        Some(analysis)
1797    }
1798
1799    pub fn cached_analysis(&self, uri: &Uri) -> Option<Arc<mir_analyzer::FileAnalysis>> {
1800        self.cached_analysis_cancellable(uri, &|| false)
1801    }
1802
1803    /// Compare `uri`'s current `FileIndex` against its stored declaration
1804    /// fingerprint, bumping `decl_version` (and `session`'s prepare
1805    /// generation) when declarations changed or this is the file's
1806    /// first-seen fingerprint. Body-only edits leave the counter unchanged so
1807    /// sibling files keep serving from cache. Returns whether it bumped.
1808    fn sync_decl_fingerprint(&self, uri: &Uri, session: &mir_analyzer::AnalysisSession) -> bool {
1809        let new_index = self.get_index_salsa(uri);
1810        let old_fp = self
1811            .caches
1812            .decl_fingerprints
1813            .get(uri)
1814            .map(|e| Arc::clone(&*e));
1815        let decl_changed = match (&old_fp, &new_index) {
1816            (Some(old), Some(new)) => **old != **new,
1817            // First analysis: only a file that actually declares something can
1818            // affect other files. Opening a plain script must not invalidate
1819            // every open file's analysis cache and mir's warm-up marks.
1820            (None, Some(new)) => !new.declares_nothing(),
1821            _ => false,
1822        };
1823        if decl_changed {
1824            if let Some(idx) = new_index {
1825                self.caches.decl_fingerprints.insert(uri.clone(), idx);
1826            }
1827            self.caches.bump_decl_version();
1828            // Text reaches mir via direct salsa `set_text` writes, so mir can't
1829            // see declaration deletions itself. A deleted declaration may
1830            // unshadow a lazy-loadable symbol — invalidate mir's warm-up skip
1831            // set so reference queries re-run their prepare pass once.
1832            session.bump_prepare_generation();
1833        }
1834        decl_changed
1835    }
1836
1837    /// Register a newly-discovered file's declarations so a consumer that was
1838    /// analyzed *before* this file existed doesn't keep a stale cached
1839    /// analysis forever.
1840    ///
1841    /// `mirror_text`/`ingest_from_doc` alone never bump `decl_version` —
1842    /// that only happens inside `cached_analysis_cancellable`'s own
1843    /// first-analysis check, which runs when a file undergoes its *own* full
1844    /// analysis. A file that is merely scanned or created as someone else's
1845    /// dependency (what a workspace scan or a `didChangeWatchedFiles`
1846    /// CREATED/CHANGED event does) never goes through that path, so without
1847    /// this call, a consumer analyzed earlier keeps returning a stale
1848    /// `UndefinedClass` (or similar) even after the dependency shows up.
1849    ///
1850    /// Call this after mirroring a file from one of those discovery paths —
1851    /// not from every `mirror_text` call, which would also fire on every
1852    /// keystroke edit to an already-open file and defeat the whole point of
1853    /// caching sibling files' analyses across those edits.
1854    pub fn note_new_file_declarations(&self, uri: &Uri) {
1855        let session = self.current_analysis_session();
1856        self.sync_decl_fingerprint(uri, &session);
1857    }
1858
1859    /// [`Self::cached_analysis`] with an early exit: `should_cancel` is
1860    /// polled whenever a concurrent salsa write cancels the analysis attempt.
1861    /// A handler passes its write-revision staleness probe so a request made
1862    /// obsolete by newer typing stops burning a blocking-pool thread instead
1863    /// of retrying until the writer pauses — the editor re-requests anyway.
1864    #[tracing::instrument(skip_all)]
1865    pub fn cached_analysis_cancellable(
1866        &self,
1867        uri: &Uri,
1868        should_cancel: &(dyn Fn() -> bool + Sync),
1869    ) -> Option<Arc<mir_analyzer::FileAnalysis>> {
1870        // Need the parsed doc both for the analyzer and as the cache key.
1871        let doc = self.get_doc_salsa(uri)?;
1872        let source = doc.source_arc();
1873
1874        if let Some(hit) = self.cached_analysis_if_fresh(uri) {
1875            return Some(hit);
1876        }
1877
1878        // Serialize concurrent callers analyzing the SAME uncached file onto
1879        // one computation instead of each redoing the full mir pass — e.g.
1880        // `did_open`'s diagnostics trigger racing a fast-following hover on a
1881        // large just-opened file (tower-lsp's default concurrency runs up to
1882        // 4 in-flight LSP messages at once, so this genuinely happens). Other
1883        // files never contend: the lock is per-URI.
1884        let inflight = Arc::clone(
1885            self.analysis_inflight
1886                .entry(uri.clone())
1887                .or_insert_with(|| Arc::new(Mutex::new(())))
1888                .value(),
1889        );
1890        let _inflight_guard = inflight.lock().unwrap();
1891
1892        // Re-check now that we hold the per-URI lock: whoever we waited on
1893        // may have just populated the cache. `cur_ver` becomes the freshness
1894        // tag on OUR insert below, so re-fetching it here (rather than reusing
1895        // a value captured before we waited) reflects what was actually true
1896        // right before we started computing, not before we started waiting.
1897        if let Some(hit) = self.cached_analysis_if_fresh(uri) {
1898            return Some(hit);
1899        }
1900        let cur_ver = self.caches.decl_version();
1901
1902        let session = self.current_analysis_session();
1903        let file: Arc<str> = Arc::from(uri.as_str());
1904
1905        let source_map = php_rs_parser::source_map::SourceMap::new(doc.source());
1906        let owned_program = if let Some(cached) = self.caches.owned_program_cache.get(uri)
1907            && Arc::ptr_eq(&cached.0, &source)
1908        {
1909            Arc::clone(&cached.1)
1910        } else {
1911            let prog = Arc::new(php_ast::owned::to_owned_program(doc.program()));
1912            self.caches.shed_stale(
1913                &self.caches.owned_program_cache,
1914                crate::document::cache_registry::OWNED_PROGRAM_CACHE_CAP,
1915            );
1916            self.caches
1917                .owned_program_cache
1918                .insert(uri.clone(), (Arc::clone(&source), Arc::clone(&prog)));
1919            prog
1920        };
1921
1922        // autoload.files helpers (e.g. Laravel's tap()) must be ingested so mir sees their functions.
1923        let autoload_texts: Vec<(Arc<str>, Arc<str>)> = {
1924            let autoload_uris = self.autoload_uris.read().unwrap().clone();
1925            autoload_uris
1926                .iter()
1927                .filter_map(|auri| {
1928                    self.caches
1929                        .text_cache
1930                        .get(auri)
1931                        .map(|t| (Arc::from(auri.as_str()), Arc::clone(&*t)))
1932                })
1933                .collect()
1934        };
1935        // Bare same-namespace / use-imported class refs aren't resolved by mir's priority_index_for_ast; preload them.
1936        let class_fqns = crate::navigation::references::collect_referenced_class_fqns(&doc);
1937
1938        // ingest_file/load_class/analyze take internal salsa snapshots; a concurrent db write cancels them via resume_unwind. Retry the idempotent sequence.
1939        let _interactive = self.interactive_read_guard();
1940        let analysis = loop {
1941            let attempt = salsa::Cancelled::catch(std::panic::AssertUnwindSafe(|| {
1942                session.ingest_file(file.clone(), source.clone());
1943                for (afile, atext) in &autoload_texts {
1944                    session.ingest_file(afile.clone(), atext.clone());
1945                }
1946                for fqcn in &class_fqns {
1947                    let _ = session.load_class(fqcn);
1948                }
1949                let analyzer = mir_analyzer::FileAnalyzer::new(&session);
1950                analyzer.analyze(file.clone(), doc.source(), &owned_program, &source_map)
1951            }));
1952            match attempt {
1953                Ok(a) => {
1954                    self.analysis_compute_count.fetch_add(1, Ordering::Relaxed);
1955                    break Arc::new(a);
1956                }
1957                Err(_) => {
1958                    // A write cancelled the attempt. If it replaced THIS
1959                    // file's text the result is already obsolete (the cache
1960                    // key is the source Arc) and the editor re-requests after
1961                    // its didChange — stop burning the blocking thread.
1962                    // Writes elsewhere just retry as before.
1963                    let text_changed = self
1964                        .caches
1965                        .text_cache
1966                        .get(uri)
1967                        .is_none_or(|t| !Arc::ptr_eq(&t, &source));
1968                    if text_changed || should_cancel() {
1969                        return None;
1970                    }
1971                }
1972            }
1973        };
1974        // Compare the new FileIndex against the stored fingerprint. If
1975        // declarations changed (or this is the first analysis), bump
1976        // `decl_version` so other files' cache entries become stale. Body-only
1977        // edits leave the counter unchanged, allowing sibling files to be
1978        // served from cache on the next request.
1979        let decl_changed = self.sync_decl_fingerprint(uri, &session);
1980        // Tag with the version observed before the analysis ran, plus this
1981        // file's own bump. Reading `decl_version()` here instead would absorb
1982        // a concurrent bump from another file's mid-compute declaration change
1983        // into the tag, marking a possibly-stale result as fresh. The
1984        // conservative tag errs toward one extra recompute, never staleness.
1985        let ver = cur_ver + u64::from(decl_changed);
1986        self.caches.shed_stale(
1987            &self.caches.analysis_cache,
1988            crate::document::cache_registry::ANALYSIS_CACHE_CAP,
1989        );
1990        self.caches.touch(uri);
1991        self.caches
1992            .analysis_cache
1993            .insert(uri.clone(), (source, ver, Arc::clone(&analysis)));
1994        Some(analysis)
1995    }
1996
1997    /// Returns `(uri, doc)` for files currently open in the editor.
1998    ///
1999    /// Resolve `open_urls` (from `Backend::open_urls()`) to parsed docs.
2000    /// Files not mirrored in the salsa layer are filtered out silently.
2001    pub fn docs_for(&self, open_urls: &[Uri]) -> Vec<(Uri, Arc<ParsedDoc>)> {
2002        open_urls
2003            .iter()
2004            .filter_map(|u| self.get_doc_salsa(u).map(|d| (u.clone(), d)))
2005            .collect()
2006    }
2007
2008    /// Parsed docs for every entry in `open_urls` except `uri`.
2009    pub fn other_docs(&self, uri: &Uri, open_urls: &[Uri]) -> Vec<(Uri, Arc<ParsedDoc>)> {
2010        open_urls
2011            .iter()
2012            .filter(|u| *u != uri)
2013            .filter_map(|u| self.get_doc_salsa(u).map(|d| (u.clone(), d)))
2014            .collect()
2015    }
2016
2017    /// Compact symbol index for every mirrored file.
2018    pub fn all_indexes(&self) -> Vec<(Uri, Arc<FileIndex>)> {
2019        self.get_workspace_index_salsa().files.clone()
2020    }
2021
2022    /// Borrow-scoped alternative to `all_indexes()` for callers that only
2023    /// need the slice for the duration of one synchronous call — avoids
2024    /// cloning every `Uri` in the aggregate (`get_workspace_index_salsa()`
2025    /// itself is a cheap `Arc` clone; `all_indexes()`'s `.files.clone()` is
2026    /// the expensive part). Use `all_indexes()` instead when the result must
2027    /// be moved across an `.await`/`spawn_blocking` boundary.
2028    pub fn with_all_indexes<R>(&self, f: impl FnOnce(&[(Uri, Arc<FileIndex>)]) -> R) -> R {
2029        f(&self.get_workspace_index_salsa().files)
2030    }
2031
2032    /// Store a lazily-loaded vendor `FileIndex` in the session cache.
2033    /// Only call this for files that are not part of the normal workspace scan
2034    /// (i.e. vendor files loaded on-demand by PSR-4 navigation).
2035    pub fn cache_vendor_index(&self, uri: Uri, index: Arc<FileIndex>) {
2036        self.caches.vendor_index_cache.insert(uri, index);
2037    }
2038
2039    /// Retrieve a previously cached vendor `FileIndex`.
2040    pub fn get_vendor_index(&self, uri: &Uri) -> Option<Arc<FileIndex>> {
2041        self.caches
2042            .vendor_index_cache
2043            .get(uri)
2044            .map(|e| Arc::clone(&*e))
2045    }
2046
2047    /// Same as `all_indexes` but excludes `uri`.
2048    pub fn other_indexes(&self, uri: &Uri) -> Vec<(Uri, Arc<FileIndex>)> {
2049        self.get_workspace_index_salsa()
2050            .files
2051            .iter()
2052            .filter(|(u, _)| u != uri)
2053            .cloned()
2054            .collect()
2055    }
2056
2057    /// Parsed documents for every mirrored file (open or background-indexed).
2058    /// Suitable for full-scan operations: find-references, rename,
2059    /// call_hierarchy, code_lens.
2060    pub fn all_docs_for_scan(&self) -> Vec<(Uri, Arc<ParsedDoc>)> {
2061        let urls: Vec<Uri> = self
2062            .lsp_ws_files
2063            .iter()
2064            .filter(|e| !self.deleted_uris.contains(e.key()))
2065            .map(|e| e.key().clone())
2066            .collect();
2067        urls.into_iter()
2068            .filter_map(|u| self.get_doc_salsa(&u).map(|d| (u, d)))
2069            .collect()
2070    }
2071
2072    /// Like [`Self::all_docs_for_scan`], but only parses files whose raw text
2073    /// contains at least one of `needles` (ASCII-case-insensitive — PHP class
2074    /// names are case-insensitive, unlike the Laravel string-key prefilter's
2075    /// exact-value match). Used by callers scanning for a class/interface
2076    /// *declaration* by name (e.g. "implement missing methods"), where the
2077    /// needle set is small and a miss guarantees the file declares none of
2078    /// them.
2079    pub fn docs_for_scan_mentioning(&self, needles: &[String]) -> Vec<(Uri, Arc<ParsedDoc>)> {
2080        let Ok(finder) = aho_corasick::AhoCorasick::builder()
2081            .ascii_case_insensitive(true)
2082            .build(needles)
2083        else {
2084            return Vec::new();
2085        };
2086        let urls: Vec<Uri> = self
2087            .lsp_ws_files
2088            .iter()
2089            .filter(|e| !self.deleted_uris.contains(e.key()))
2090            .filter(|e| {
2091                self.source_text(e.key())
2092                    .is_some_and(|text| finder.is_match(text.as_ref()))
2093            })
2094            .map(|e| e.key().clone())
2095            .collect();
2096        urls.into_iter()
2097            .filter_map(|u| self.get_doc_salsa(&u).map(|d| (u, d)))
2098            .collect()
2099    }
2100
2101    /// Files whose `use` imports include `fqn` (leading `\` and ASCII case
2102    /// ignored — PHP names are case-insensitive), from the workspace symbol
2103    /// index — no parsing, no text scan. The candidate scope for `use`-line
2104    /// rewrites on file rename/delete: only importers can carry such a line.
2105    pub fn files_importing(&self, fqn: &str) -> Vec<Uri> {
2106        let target = fqn.trim_start_matches('\\');
2107        self.get_workspace_index_salsa()
2108            .files
2109            .iter()
2110            .filter(|(_, idx)| {
2111                idx.use_imports
2112                    .iter()
2113                    .any(|(_, f)| f.trim_start_matches('\\').eq_ignore_ascii_case(target))
2114            })
2115            .map(|(u, _)| u.clone())
2116            .collect()
2117    }
2118}
2119
2120/// `prefix` equals `whole` or is a `\`-segment-aligned prefix of it,
2121/// ASCII-case-insensitively (PHP name semantics). `"Foo\Bar"` is a segment
2122/// prefix of `"Foo\Bar\Baz"` but `"Foo\Ba"` is not.
2123fn fqn_segment_prefix(prefix: &str, whole: &str) -> bool {
2124    let (p, w) = (prefix.as_bytes(), whole.as_bytes());
2125    w.len() >= p.len()
2126        && w[..p.len()].eq_ignore_ascii_case(p)
2127        && (w.len() == p.len() || w[p.len()] == b'\\')
2128}
2129
2130/// `uri`'s path has a `vendor` component, e.g. `file:///proj/vendor/acme/Lib.php`
2131/// or the nested-monorepo `file:///proj/packages/api/vendor/x/Y.php`. URI
2132/// paths are always `/`-separated regardless of platform, so a plain
2133/// component split is enough — no OS path handling needed.
2134fn is_vendor_uri(uri: &Uri) -> bool {
2135    uri.path().split('/').any(|seg| seg == "vendor")
2136}
2137
2138/// The narrowing decision for a method's reference scope, computed without
2139/// running the expensive part (the FQN/text-needle workspace scan) so a
2140/// batch caller can pool that scan across many methods.
2141enum MethodScopePlan {
2142    /// Fully resolved already — no workspace scan needed at all (private:
2143    /// the declaring file alone; protected: the declaring file plus its
2144    /// resolved subtype set).
2145    Files(Vec<Uri>),
2146    /// A public static method or constructor: resolvable to the declaring
2147    /// class's FQN-reachable files unioned with files matching one extra
2148    /// text needle. This is the case a batch caller pools.
2149    NeedsScan {
2150        fqns: Vec<Arc<str>>,
2151        extra_needle: String,
2152    },
2153    /// No narrowing possible (instance methods, an unresolvable owner, or
2154    /// the boot scan hasn't finished) — full workspace scope.
2155    FullWorkspace,
2156}
2157
2158/// One [`DocumentStore::resolve_reachability_queries`] request: the target
2159/// FQNs for the namespace/import rules, plus raw text needles matched the
2160/// same way (ASCII-case-insensitive substring).
2161struct ReachabilityQuery {
2162    fqns: Vec<Arc<str>>,
2163    extra_needles: Vec<String>,
2164}
2165
2166#[cfg(test)]
2167mod tests {
2168    use super::*;
2169
2170    fn uri(path: &str) -> Uri {
2171        format!("file://{path}").parse::<Uri>().unwrap()
2172    }
2173
2174    /// Phase E4: open-file state lives on `Backend`, not `DocumentStore`.
2175    /// Tests that need to simulate "file is open" just mirror the text into
2176    /// the salsa input — the open/closed distinction is enforced by the
2177    /// caller (Backend) in production.
2178    fn open(store: &DocumentStore, u: Uri, text: String) {
2179        store.mirror_text(&u, &text);
2180    }
2181
2182    // Removed `salsa_codebase_aggregates_all_files`: the salsa-side codebase
2183    // aggregation was deleted with the mir 0.22 migration. Equivalent
2184    // behaviour is now covered by mir-analyzer's own session tests.
2185
2186    // Spawn a thread that calls `yield_to_interactive_reads` and hands back
2187    // the elapsed time it spent waiting. It signals `ready` right before
2188    // entering the call, so the caller can block on that signal instead of
2189    // guessing how long thread start-up takes — a fixed sleep here would
2190    // race the thread scheduler, and that race is exactly what made this
2191    // test flaky under load (e.g. Windows CI runners have much coarser and
2192    // less predictable thread-spawn latency than Linux/macOS).
2193    fn spawn_yield_waiter(
2194        store: &Arc<DocumentStore>,
2195    ) -> (
2196        std::sync::mpsc::Receiver<()>,
2197        std::thread::JoinHandle<std::time::Duration>,
2198    ) {
2199        let (ready_tx, ready_rx) = std::sync::mpsc::channel();
2200        let store = Arc::clone(store);
2201        let handle = std::thread::spawn(move || {
2202            ready_tx.send(()).unwrap();
2203            let t = std::time::Instant::now();
2204            store.yield_to_interactive_reads();
2205            t.elapsed()
2206        });
2207        (ready_rx, handle)
2208    }
2209
2210    #[test]
2211    fn scan_writers_yield_while_interactive_reads_are_in_flight() {
2212        let store = Arc::new(DocumentStore::new());
2213
2214        // No guard: returns immediately.
2215        let t = std::time::Instant::now();
2216        store.yield_to_interactive_reads();
2217        assert!(t.elapsed() < std::time::Duration::from_millis(200));
2218
2219        // Guard held on another thread: the writer waits until it drops.
2220        // We only start the hold timer once the waiter has confirmed it's
2221        // about to poll, so the guard can never be dropped before the
2222        // writer starts waiting on it.
2223        let guard = store.interactive_read_guard();
2224        let (ready_rx, waiter) = spawn_yield_waiter(&store);
2225        ready_rx.recv().unwrap();
2226        const HOLD: std::time::Duration = std::time::Duration::from_millis(60);
2227        std::thread::sleep(HOLD);
2228        drop(guard);
2229        let waited = waiter.join().unwrap();
2230        assert!(
2231            waited >= HOLD,
2232            "writer should have paused at least as long as the read guard was held (waited {waited:?})"
2233        );
2234
2235        // Guard fully released: nested guards count correctly.
2236        let g1 = store.interactive_read_guard();
2237        let g2 = store.interactive_read_guard();
2238        drop(g1);
2239        let (ready_rx, waiter) = spawn_yield_waiter(&store);
2240        ready_rx.recv().unwrap();
2241        const HOLD2: std::time::Duration = std::time::Duration::from_millis(30);
2242        std::thread::sleep(HOLD2);
2243        drop(g2);
2244        let waited = waiter.join().unwrap();
2245        assert!(
2246            waited >= HOLD2,
2247            "writer should have paused while the nested read guard was held (waited {waited:?})"
2248        );
2249        store.yield_to_interactive_reads(); // all guards dropped — no wait
2250    }
2251
2252    #[test]
2253    fn index_registers_file_in_salsa() {
2254        let store = DocumentStore::new();
2255        store.ingest(uri("/lib.php"), "<?php\nfunction lib_fn() {}");
2256        let idx = store.get_index_salsa(&uri("/lib.php")).unwrap();
2257        assert_eq!(idx.functions.len(), 1);
2258        assert_eq!(&*idx.functions[0].name, "lib_fn");
2259    }
2260
2261    #[test]
2262    fn remove_hides_file_from_index() {
2263        let store = DocumentStore::new();
2264        let u = uri("/lib.php");
2265        store.ingest(u.clone(), "<?php");
2266        store.remove(&u);
2267        assert!(store.get_index_salsa(&u).is_none());
2268    }
2269
2270    #[test]
2271    fn remove_frees_mir_source_text() {
2272        let store = DocumentStore::new();
2273        let u = uri("/lib.php");
2274        let big_text = format!("<?php\n{}", "// pad\n".repeat(1000));
2275        store.ingest(u.clone(), &big_text);
2276
2277        let session = store.current_analysis_session();
2278        let sf = session.lookup_source_file(u.as_str()).unwrap();
2279        let len_before = store.snapshot_mir_query(|db| sf.text(db).len());
2280        assert!(len_before > 1000, "sanity: source text should be mirrored");
2281
2282        store.remove(&u);
2283
2284        let len_after = store.snapshot_mir_query(|db| sf.text(db).len());
2285        assert_eq!(
2286            len_after, 0,
2287            "remove() must free mir's SourceFile text, not just hide the file from indexes"
2288        );
2289    }
2290
2291    #[test]
2292    fn remove_shrinks_file_index_memo() {
2293        let store = DocumentStore::new();
2294        let u = uri("/lib.php");
2295        store.ingest(u.clone(), "<?php\nclass BigClassBeforeDelete {}\n");
2296
2297        let wf = store.lsp_ws_files.get(&u).map(|e| *e).unwrap();
2298        let idx_before =
2299            store.snapshot_mir_query(|db| crate::db::mir_queries::file_index(db, wf).0.clone());
2300        assert_eq!(
2301            idx_before.classes.len(),
2302            1,
2303            "sanity: class should be indexed"
2304        );
2305
2306        store.remove(&u);
2307
2308        let idx_after =
2309            store.snapshot_mir_query(|db| crate::db::mir_queries::file_index(db, wf).0.clone());
2310        assert!(
2311            idx_after.classes.is_empty(),
2312            "remove() must shrink file_index's memo (no LRU cap, unlike parsed_doc/symbol_map) \
2313             against the emptied text, not hold the pre-deletion FileIndex forever"
2314        );
2315    }
2316
2317    #[test]
2318    fn remove_and_reopen_reuses_source_file_handle() {
2319        let store = DocumentStore::new();
2320        let u = uri("/lib.php");
2321        store.ingest(u.clone(), "<?php");
2322        let ft_before = store.source_file(&u).unwrap();
2323        store.remove(&u);
2324        assert!(
2325            store.source_file(&u).is_none(),
2326            "deleted file should be hidden"
2327        );
2328        store.mirror_text(&u, "<?php");
2329        let ft_after = store.source_file(&u).unwrap();
2330        assert!(
2331            ft_before == ft_after,
2332            "reopen must reuse the same FileText handle"
2333        );
2334    }
2335
2336    #[test]
2337    fn delete_reopen_churn_does_not_amplify_salsa_inputs() {
2338        let store = DocumentStore::new();
2339        let uris: Vec<Uri> = (0..20).map(|i| uri(&format!("/churn/f{i}.php"))).collect();
2340        for u in &uris {
2341            store.ingest(u.clone(), "<?php class A {}");
2342        }
2343        let count_before = store.source_files_len();
2344        for _ in 0..10 {
2345            for u in &uris {
2346                store.remove(u);
2347            }
2348            for u in &uris {
2349                store.ingest(u.clone(), "<?php class A {}");
2350            }
2351        }
2352        assert_eq!(
2353            store.source_files_len(),
2354            count_before,
2355            "delete-reopen cycles must not create new salsa inputs (L1-B regression guard)"
2356        );
2357    }
2358
2359    #[test]
2360    fn warm_analysis_sweep_preserves_reference_results() {
2361        let store = DocumentStore::new();
2362        store.ingest(
2363            uri("/svc.php"),
2364            "<?php\nnamespace App;\nclass Svc { public function run(): void {} }",
2365        );
2366        store.ingest(
2367            uri("/caller.php"),
2368            "<?php\nnamespace App;\nclass Caller {\n    private Svc $s;\n    public function go(): void { $this->s->run(); }\n}",
2369        );
2370        let sym = mir_analyzer::Name::method("App\\Svc", "run");
2371        let files: Vec<Arc<str>> = [uri("/svc.php"), uri("/caller.php")]
2372            .iter()
2373            .map(|u| Arc::from(u.as_str()))
2374            .collect();
2375        let cold = store.indexed_references(&sym, &files, false, None);
2376        assert_eq!(cold.len(), 1, "caller.php references Svc::run once");
2377
2378        let cancel = store.begin_warm_sweep();
2379        store.warm_analysis_sweep(&[], &cancel);
2380        let warm = store.indexed_references(&sym, &files, false, None);
2381        assert_eq!(cold, warm, "sweep must not change reference results");
2382
2383        // An edit after the sweep is still picked up (memos revalidate).
2384        store.ingest(
2385            uri("/caller.php"),
2386            "<?php\nnamespace App;\nclass Caller {\n    private Svc $s;\n    public function go(): void { $this->s->run(); $this->s->run(); }\n}",
2387        );
2388        let cancel = store.begin_warm_sweep();
2389        store.warm_analysis_sweep(&[], &cancel);
2390        let after_edit = store.indexed_references(&sym, &files, false, None);
2391        assert_eq!(after_edit.len(), 2, "re-sweep must see the new reference");
2392    }
2393
2394    #[test]
2395    fn sweep_priority_puts_open_files_and_their_dependencies_first() {
2396        let store = DocumentStore::new();
2397        store.ingest(
2398            uri("/a.php"),
2399            "<?php\nnamespace App;\nclass A { public function go(B $b): void {} }",
2400        );
2401        store.ingest(uri("/b.php"), "<?php\nnamespace App;\nclass B {}");
2402        store.ingest(uri("/unrelated.php"), "<?php\nnamespace App;\nclass C {}");
2403        store.mark_index_ready();
2404
2405        let front = store.sweep_priority_files(&[uri("/a.php")]);
2406        let front: Vec<&str> = front.iter().map(|f| f.as_ref()).collect();
2407        assert_eq!(
2408            front,
2409            vec![uri("/a.php").as_str(), uri("/b.php").as_str()],
2410            "open file first, then the files declaring its referenced classes"
2411        );
2412    }
2413
2414    #[test]
2415    fn sweep_candidate_files_excludes_vendor_from_the_ambient_tail() {
2416        let store = DocumentStore::new();
2417        store.ingest(
2418            uri("/vendor/acme/Lib.php"),
2419            "<?php\nnamespace Acme;\nclass Lib {}",
2420        );
2421        store.ingest(uri("/src/Own.php"), "<?php\nnamespace App;\nclass Own {}");
2422        store.mark_index_ready();
2423
2424        let files = store.sweep_candidate_files(&[]);
2425        let files: Vec<&str> = files.iter().map(|f| f.as_ref()).collect();
2426        assert!(
2427            !files.contains(&uri("/vendor/acme/Lib.php").as_str()),
2428            "vendor file must not be in the ambient (non-priority) sweep list: {files:?}"
2429        );
2430        assert!(
2431            files.contains(&uri("/src/Own.php").as_str()),
2432            "non-vendor file must still be in the ambient sweep list: {files:?}"
2433        );
2434    }
2435
2436    #[test]
2437    fn sweep_candidate_files_still_includes_an_explicitly_prioritized_vendor_file() {
2438        let store = DocumentStore::new();
2439        store.ingest(
2440            uri("/vendor/acme/Lib.php"),
2441            "<?php\nnamespace Acme;\nclass Lib {}",
2442        );
2443        store.mark_index_ready();
2444
2445        // Opening the vendor file directly makes it a priority target, which
2446        // bypasses the ambient-sweep vendor exclusion.
2447        let files = store.sweep_candidate_files(&[uri("/vendor/acme/Lib.php")]);
2448        let files: Vec<&str> = files.iter().map(|f| f.as_ref()).collect();
2449        assert!(
2450            files.contains(&uri("/vendor/acme/Lib.php").as_str()),
2451            "an explicitly opened/prioritized vendor file must still be warmed: {files:?}"
2452        );
2453    }
2454
2455    #[test]
2456    fn is_vendor_uri_matches_top_level_and_nested_vendor_dirs_only() {
2457        assert!(is_vendor_uri(&uri("/proj/vendor/acme/Lib.php")));
2458        assert!(is_vendor_uri(&uri(
2459            "/proj/packages/api/vendor/acme/Lib.php"
2460        )));
2461        assert!(!is_vendor_uri(&uri("/proj/src/Vendored/Lib.php")));
2462        assert!(!is_vendor_uri(&uri("/proj/src/VendorLib.php")));
2463    }
2464
2465    #[test]
2466    fn warm_analysis_sweep_stops_on_cancel() {
2467        let store = DocumentStore::new();
2468        for i in 0..40 {
2469            store.ingest(
2470                uri(&format!("/f{i}.php")),
2471                "<?php\nclass A { public function m(): int { return 1; } }",
2472            );
2473        }
2474        let cancel = store.begin_warm_sweep();
2475        cancel.cancel();
2476        // Pre-cancelled token: returns without analyzing (must not hang/panic).
2477        store.warm_analysis_sweep(&[], &cancel);
2478        // A newer sweep's token supersedes the old one.
2479        let old = store.begin_warm_sweep();
2480        let _new = store.begin_warm_sweep();
2481        assert!(old.is_cancelled());
2482    }
2483
2484    #[test]
2485    fn all_indexes_includes_every_mirrored_file() {
2486        let store = DocumentStore::new();
2487        open(&store, uri("/a.php"), "<?php\nfunction a() {}".to_string());
2488        store.ingest(uri("/b.php"), "<?php\nfunction b() {}");
2489        assert_eq!(store.all_indexes().len(), 2);
2490    }
2491
2492    #[test]
2493    fn other_indexes_excludes_current_uri() {
2494        let store = DocumentStore::new();
2495        open(&store, uri("/a.php"), "<?php\nfunction a() {}".to_string());
2496        open(&store, uri("/b.php"), "<?php\nfunction b() {}".to_string());
2497        assert_eq!(store.other_indexes(&uri("/a.php")).len(), 1);
2498    }
2499
2500    #[test]
2501    fn other_docs_excludes_current_uri() {
2502        let store = DocumentStore::new();
2503        let ua = uri("/a.php");
2504        let ub = uri("/b.php");
2505        open(&store, ua.clone(), "<?php\nfunction a() {}".to_string());
2506        open(&store, ub.clone(), "<?php\nfunction b() {}".to_string());
2507        let open_urls = vec![ua.clone(), ub];
2508        assert_eq!(store.other_docs(&ua, &open_urls).len(), 1);
2509    }
2510
2511    #[test]
2512    fn evict_token_cache_removes_entry() {
2513        let store = DocumentStore::new();
2514        let u = uri("/a.php");
2515        open(&store, u.clone(), "<?php".to_string());
2516        store.store_token_cache(&u, "id1".to_string(), Arc::new(vec![]));
2517        assert!(store.get_token_cache(&u, "id1").is_some());
2518        store.evict_token_cache(&u);
2519        assert!(store.get_token_cache(&u, "id1").is_none());
2520    }
2521
2522    #[test]
2523    fn vendor_index_cache_evicted_on_remove() {
2524        let store = DocumentStore::new();
2525        let u = uri("/vendor/acme/lib.php");
2526        store.ingest(u.clone(), "<?php\nclass Lib {}");
2527        let idx = store.get_index_salsa(&u).unwrap();
2528        store.cache_vendor_index(u.clone(), idx.clone());
2529        assert!(store.get_vendor_index(&u).is_some());
2530        store.remove(&u);
2531        assert!(store.get_vendor_index(&u).is_none());
2532    }
2533
2534    #[test]
2535    fn index_populates_file_index_with_symbols() {
2536        let store = DocumentStore::new();
2537        store.ingest(uri("/a.php"), "<?php\nfunction hello() {}");
2538        let idx = store.get_index_salsa(&uri("/a.php")).unwrap();
2539        assert_eq!(idx.functions.len(), 1);
2540        assert_eq!(&*idx.functions[0].name, "hello");
2541    }
2542
2543    #[test]
2544    fn open_populates_file_index_with_symbols() {
2545        let store = DocumentStore::new();
2546        open(&store, uri("/a.php"), "<?php\nclass Foo {}".to_string());
2547        let idx = store.get_index_salsa(&uri("/a.php")).unwrap();
2548        assert_eq!(idx.classes.len(), 1);
2549        assert_eq!(&*idx.classes[0].name, "Foo");
2550    }
2551
2552    // ── Mirror invariants ────────────────────────────────────────────────
2553    //
2554    // Every mutation path that changes file text must keep the salsa layer
2555    // consistent. These tests walk a set-edit-reopen cycle and assert that
2556    // the salsa-derived `FileIndex` reflects the latest text at each step.
2557
2558    fn names_of(idx: &FileIndex) -> Vec<String> {
2559        let mut out: Vec<String> = idx.classes.iter().map(|c| c.name.to_string()).collect();
2560        out.extend(idx.functions.iter().map(|f| f.name.to_string()));
2561        out.sort();
2562        out
2563    }
2564
2565    fn salsa_index_names(store: &DocumentStore, url: &Uri) -> Vec<String> {
2566        store
2567            .snapshot_query_file_index(url)
2568            .map(|idx| names_of(&idx))
2569            .unwrap_or_default()
2570    }
2571
2572    #[test]
2573    fn mirror_tracks_repeated_edits() {
2574        let store = DocumentStore::new();
2575        let u = uri("/mirror.php");
2576
2577        open(&store, u.clone(), "<?php\nclass A {}".to_string());
2578        assert_eq!(salsa_index_names(&store, &u), vec!["A".to_string()]);
2579
2580        open(
2581            &store,
2582            u.clone(),
2583            "<?php\nclass A {}\nclass B {}".to_string(),
2584        );
2585        assert_eq!(
2586            salsa_index_names(&store, &u),
2587            vec!["A".to_string(), "B".to_string()]
2588        );
2589
2590        open(&store, u.clone(), "<?php\nfunction greet() {}".to_string());
2591        assert_eq!(salsa_index_names(&store, &u), vec!["greet".to_string()]);
2592    }
2593
2594    #[test]
2595    fn mirror_tracks_ingest_and_ingest_from_doc() {
2596        let store = DocumentStore::new();
2597
2598        // Background `index(url, text)` path.
2599        let u1 = uri("/bg1.php");
2600        store.ingest(u1.clone(), "<?php\nclass Bg1 {}");
2601        assert_eq!(salsa_index_names(&store, &u1), vec!["Bg1".to_string()]);
2602
2603        // `ingest_from_doc(url, &doc)` path (workspace-scan Phase 2).
2604        let u2 = uri("/bg2.php");
2605        let doc = crate::analysis::diagnostics::parse_document_no_diags(
2606            "<?php\nclass Bg2 {}\nfunction f() {}",
2607        );
2608        store.ingest_from_doc(u2.clone(), &doc);
2609        assert_eq!(
2610            salsa_index_names(&store, &u2),
2611            vec!["Bg2".to_string(), "f".to_string()]
2612        );
2613    }
2614
2615    /// G3: confirms the `parsed_cache` actually hits — two consecutive
2616    /// `get_doc_salsa` calls on unchanged text return the same `Arc`
2617    /// (pointer equality), and an edit forces a miss that produces a
2618    /// different `Arc`.
2619    /// parsed_cache must stay bounded — inserting more than
2620    /// `PARSED_CACHE_CAP` unique URLs must not cause unbounded growth.
2621    /// Eviction is probabilistic, so we only assert the bound, not which
2622    /// Seeding a cached index for a URL that was never mirrored is a no-op
2623    /// (returns `false`) — avoids silently allocating SourceFiles outside
2624    /// `mirror_text`'s control.
2625    #[test]
2626    fn seed_cached_index_noops_for_unknown_uri() {
2627        let store = DocumentStore::new();
2628        let u = uri("/never_mirrored.php");
2629        let index = Arc::new(crate::index::file_index::FileIndex::default());
2630        assert!(!store.seed_cached_index(&u, index));
2631    }
2632
2633    /// entries survive.
2634    #[test]
2635    fn parsed_cache_stays_bounded_under_many_inserts() {
2636        let store = DocumentStore::new();
2637        use crate::document::cache_registry::PARSED_CACHE_CAP;
2638        let overflow = PARSED_CACHE_CAP + 100;
2639        for i in 0..overflow {
2640            let u = uri(&format!("/cap/file{i}.php"));
2641            store.ingest(u.clone(), "<?php\nclass A {}");
2642            // Force a parsed_cache insert via get_doc_salsa.
2643            let _ = store.get_doc_salsa(&u);
2644        }
2645        assert!(
2646            store.caches.parsed_cache.len() <= PARSED_CACHE_CAP,
2647            "parsed_cache grew to {} entries (cap {})",
2648            store.caches.parsed_cache.len(),
2649            PARSED_CACHE_CAP
2650        );
2651    }
2652
2653    /// The shed is recency-based: an entry touched right before overflow (an
2654    /// open file being edited) must survive a sweep of cold inserts, while
2655    /// untouched cold entries are the ones dropped.
2656    #[test]
2657    fn parsed_cache_shed_keeps_recently_used_entries() {
2658        let store = DocumentStore::new();
2659        use crate::document::cache_registry::PARSED_CACHE_CAP;
2660
2661        let hot = uri("/cap/hot.php");
2662        store.ingest(hot.clone(), "<?php\nclass Hot {}");
2663        let _ = store.get_doc_salsa(&hot);
2664
2665        // Fill to just below the cap with cold entries, then re-touch the hot
2666        // file so it is the most recently used entry at shed time.
2667        for i in 0..(PARSED_CACHE_CAP - 2) {
2668            let u = uri(&format!("/cap/cold{i}.php"));
2669            store.ingest(u.clone(), "<?php\nclass A {}");
2670            let _ = store.get_doc_salsa(&u);
2671        }
2672        let _ = store.get_doc_salsa(&hot);
2673
2674        // Overflow: this insert triggers the shed of the LRU half.
2675        let trigger = uri("/cap/trigger.php");
2676        store.ingest(trigger.clone(), "<?php\nclass T {}");
2677        let _ = store.get_doc_salsa(&trigger);
2678
2679        assert!(
2680            store.caches.parsed_cache.contains_key(&hot),
2681            "recently-touched entry must survive the recency shed"
2682        );
2683        assert!(
2684            store.caches.parsed_cache.len() <= PARSED_CACHE_CAP,
2685            "cache must stay bounded after the shed"
2686        );
2687    }
2688
2689    /// `analysis_cache` must stay bounded when many distinct files are
2690    /// analyzed across a session (multi-hour usage previously grew it
2691    /// without limit).
2692    #[test]
2693    fn analysis_cache_stays_bounded_under_many_files() {
2694        use crate::document::cache_registry::ANALYSIS_CACHE_CAP;
2695        let store = DocumentStore::new();
2696        let overflow = ANALYSIS_CACHE_CAP + 16;
2697        for i in 0..overflow {
2698            let u = uri(&format!("/acap/file{i}.php"));
2699            store.ingest(u.clone(), "<?php\nfunction f() { return 1; }");
2700            let _ = store.cached_analysis(&u);
2701        }
2702        assert!(
2703            store.caches.analysis_cache.len() <= ANALYSIS_CACHE_CAP,
2704            "analysis_cache grew to {} entries (cap {})",
2705            store.caches.analysis_cache.len(),
2706            ANALYSIS_CACHE_CAP
2707        );
2708    }
2709
2710    #[test]
2711    fn get_doc_salsa_cache_hits_across_calls() {
2712        let store = DocumentStore::new();
2713        let u = uri("/g3_cache.php");
2714        open(&store, u.clone(), "<?php\nclass G3 {}".to_string());
2715
2716        let a = store.get_doc_salsa(&u).unwrap();
2717        let b = store.get_doc_salsa(&u).unwrap();
2718        assert!(
2719            Arc::ptr_eq(&a, &b),
2720            "parsed_cache hit should yield the same Arc across calls"
2721        );
2722
2723        open(&store, u.clone(), "<?php\nclass G3b {}".to_string());
2724        let c = store.get_doc_salsa(&u).unwrap();
2725        assert!(
2726            !Arc::ptr_eq(&a, &c),
2727            "edit should invalidate the parsed_cache entry"
2728        );
2729    }
2730
2731    #[test]
2732    fn get_doc_salsa_returns_some_for_mirrored_files() {
2733        // Phase E4: `get_doc_salsa` no longer gates on open-state. The
2734        // open/closed distinction now lives on `Backend::get_doc`.
2735        let store = DocumentStore::new();
2736        let u = uri("/e4_doc.php");
2737        store.ingest(u.clone(), "<?php\nclass P {}");
2738        assert!(store.get_doc_salsa(&u).is_some());
2739    }
2740
2741    #[test]
2742    fn get_doc_snapshot_or_stale_matches_salsa_on_settled_buffer() {
2743        let store = DocumentStore::new();
2744        let u = uri("/stale_settled.php");
2745        open(&store, u.clone(), "<?php\nclass S {}".to_string());
2746        let fresh = store.get_doc_salsa(&u).unwrap();
2747        let stale = store.get_doc_snapshot_or_stale(&u).unwrap();
2748        assert!(
2749            Arc::ptr_eq(&fresh, &stale),
2750            "on a settled buffer the stale-tolerant accessor must serve the cached parse"
2751        );
2752    }
2753
2754    /// WS1: the cursor-triggered highlight accessor must stay responsive under a
2755    /// sustained write stream — never spin (the deadline join hangs if it does)
2756    /// and always yield a fresh or last-good parse for an open file.
2757    #[test]
2758    fn get_doc_snapshot_or_stale_stays_responsive_under_writes() {
2759        use std::sync::Arc;
2760        use std::thread;
2761        use std::time::{Duration, Instant};
2762
2763        let store = Arc::new(DocumentStore::new());
2764        let urls: Vec<Uri> = (0..8).map(|i| uri(&format!("/hl{i}.php"))).collect();
2765        for (i, u) in urls.iter().enumerate() {
2766            open(&store, u.clone(), format!("<?php\nclass H{i} {{}}"));
2767            // Warm the parse cache so the stale fallback always has a last-good doc.
2768            assert!(store.get_doc_salsa(u).is_some());
2769        }
2770
2771        let deadline = Instant::now() + Duration::from_millis(400);
2772        let mut handles = Vec::new();
2773
2774        {
2775            let store = Arc::clone(&store);
2776            let urls = urls.clone();
2777            handles.push(thread::spawn(move || {
2778                let mut rev = 0u32;
2779                while Instant::now() < deadline {
2780                    for u in &urls {
2781                        store.mirror_text(u, &format!("<?php\nclass H {{}}\n// rev {rev}"));
2782                    }
2783                    rev += 1;
2784                }
2785            }));
2786        }
2787
2788        for _ in 0..4 {
2789            let store = Arc::clone(&store);
2790            let urls = urls.clone();
2791            handles.push(thread::spawn(move || {
2792                while Instant::now() < deadline {
2793                    for u in &urls {
2794                        assert!(
2795                            store.get_doc_snapshot_or_stale(u).is_some(),
2796                            "open file must resolve to a fresh or stale parse, never None"
2797                        );
2798                    }
2799                }
2800            }));
2801        }
2802
2803        for h in handles {
2804            h.join()
2805                .expect("stale accessor must not panic or spin under concurrent writes");
2806        }
2807    }
2808
2809    /// WS1 A/B measurement (not a pass/fail guard): compares the old unbounded
2810    /// `get_doc_salsa` against the new bounded `get_doc_snapshot_or_stale` under
2811    /// an identical continuous write stream. Run explicitly:
2812    /// `cargo test --lib ws1_ab_latency -- --ignored --nocapture`.
2813    #[test]
2814    #[ignore = "timing measurement; run with --ignored --nocapture"]
2815    fn ws1_ab_latency_under_write_pressure() {
2816        use std::sync::Arc;
2817        use std::sync::atomic::{AtomicBool, Ordering};
2818        use std::thread;
2819        use std::time::{Duration, Instant};
2820
2821        // A large file: each parse is long enough that a concurrent write can
2822        // cancel it mid-flight — the condition under which the unbounded retry
2823        // actually spins (a tiny file parses faster than the writer's gap).
2824        fn big_source(rev: u32) -> String {
2825            let mut s = String::from("<?php\nclass Big {\n");
2826            for i in 0..3000 {
2827                s.push_str(&format!(
2828                    "    public function m{i}(int $a, string $b): int {{ return $a + {i}; }}\n"
2829                ));
2830            }
2831            s.push_str(&format!("}}\n// rev {rev}\n"));
2832            s
2833        }
2834
2835        fn measure(
2836            store: &Arc<DocumentStore>,
2837            url: &Uri,
2838            writers: usize,
2839            label: &str,
2840            call: impl Fn(&DocumentStore, &Uri) -> bool,
2841        ) {
2842            let stop = Arc::new(AtomicBool::new(false));
2843            let mut writer_handles = Vec::new();
2844            for w in 0..writers {
2845                let store = Arc::clone(store);
2846                let url = url.clone();
2847                let stop = Arc::clone(&stop);
2848                writer_handles.push(thread::spawn(move || {
2849                    let mut rev = (w as u32) * 1_000_000;
2850                    while !stop.load(Ordering::Relaxed) {
2851                        store.mirror_text(&url, &big_source(rev));
2852                        rev = rev.wrapping_add(1);
2853                    }
2854                }));
2855            }
2856            thread::sleep(Duration::from_millis(30)); // let the writers get hot
2857
2858            let n = 100usize;
2859            let mut max = Duration::ZERO;
2860            let mut total = Duration::ZERO;
2861            for _ in 0..n {
2862                let t = Instant::now();
2863                let ok = call(store, url);
2864                let dt = t.elapsed();
2865                assert!(ok, "{label}: accessor returned None");
2866                max = max.max(dt);
2867                total += dt;
2868            }
2869            stop.store(true, Ordering::Relaxed);
2870            for h in writer_handles {
2871                h.join().unwrap();
2872            }
2873            println!(
2874                "{label}: {n} calls, {writers} writers — max {:>10.3?}, mean {:>10.3?}",
2875                max,
2876                total / n as u32
2877            );
2878        }
2879
2880        let store = Arc::new(DocumentStore::new());
2881        let url = uri("/perf_big.php");
2882        open(&store, url.clone(), big_source(0));
2883        assert!(store.get_doc_salsa(&url).is_some()); // warm the cache
2884
2885        for writers in [2usize, 4] {
2886            measure(
2887                &store,
2888                &url,
2889                writers,
2890                "NEW get_doc_snapshot_or_stale",
2891                |s, u| s.get_doc_snapshot_or_stale(u).is_some(),
2892            );
2893            measure(
2894                &store,
2895                &url,
2896                writers,
2897                "OLD get_doc_salsa (unbounded)  ",
2898                |s, u| s.get_doc_salsa(u).is_some(),
2899            );
2900        }
2901    }
2902
2903    #[test]
2904    fn get_salsa_accessors_return_none_for_unknown_uri() {
2905        let store = DocumentStore::new();
2906        let u = uri("/never-seen.php");
2907        assert!(store.get_doc_salsa(&u).is_none());
2908        assert!(store.get_index_salsa(&u).is_none());
2909    }
2910
2911    /// Phase E1: concurrent readers and writers must not deadlock, panic, or
2912    /// return stale data. Writers briefly bump inputs while readers are
2913    /// running on cloned snapshots; any `salsa::Cancelled` raised on the
2914    /// reader side must be caught and retried by `snapshot_query`.
2915    ///
2916    /// The salsa surface (`get_doc_salsa`, `get_index_salsa`) is protected by
2917    /// `snapshot_query`'s last-resort host-lock fallback.
2918    #[test]
2919    fn concurrent_reads_and_writes_do_not_panic() {
2920        use std::sync::Arc;
2921        use std::thread;
2922        use std::time::{Duration, Instant};
2923
2924        let store = Arc::new(DocumentStore::new());
2925        let urls: Vec<Uri> = (0..8).map(|i| uri(&format!("/f{i}.php"))).collect();
2926        for (i, u) in urls.iter().enumerate() {
2927            open(&store, u.clone(), format!("<?php\nclass C{i} {{}}"));
2928        }
2929
2930        let deadline = Instant::now() + Duration::from_millis(400);
2931        let mut handles = Vec::new();
2932
2933        // Writer thread: keep bumping every file's text.
2934        {
2935            let store = Arc::clone(&store);
2936            let urls = urls.clone();
2937            handles.push(thread::spawn(move || {
2938                let mut rev = 0u32;
2939                while Instant::now() < deadline {
2940                    for u in &urls {
2941                        let text = format!("<?php\nclass C{{}}\n// rev {rev}");
2942                        store.mirror_text(u, &text);
2943                    }
2944                    rev += 1;
2945                }
2946            }));
2947        }
2948
2949        // Reader threads: hammer the salsa accessors.
2950        for _ in 0..4 {
2951            let store = Arc::clone(&store);
2952            let urls = urls.clone();
2953            handles.push(thread::spawn(move || {
2954                while Instant::now() < deadline {
2955                    for u in &urls {
2956                        let _ = store.get_doc_salsa(u);
2957                        let _ = store.get_index_salsa(u);
2958                    }
2959                    // Post mir 0.22: codebase + refs live in the session,
2960                    // not salsa. Concurrent-read smoke is limited to the
2961                    // remaining salsa surface (parsed_doc, file_index).
2962                }
2963            }));
2964        }
2965
2966        for h in handles {
2967            h.join().expect("no panic under concurrent read/write");
2968        }
2969    }
2970
2971    /// PSR-4 lazy-loading: `get_semantic_issues_salsa` must not emit
2972    /// `UndefinedClass` for a class that is PSR-4-resolvable on disk, even
2973    /// when the dependency file is not yet in `source_files`.
2974    #[test]
2975    fn psr4_lazy_load_suppresses_undefined_class() {
2976        let tmp = tempfile::tempdir().unwrap();
2977
2978        // Write Entity.php to disk (not mirrored into the store).
2979        std::fs::create_dir_all(tmp.path().join("src/Model")).unwrap();
2980        std::fs::write(
2981            tmp.path().join("src/Model/Entity.php"),
2982            "<?php\nnamespace App\\Model;\nclass Entity {}\n",
2983        )
2984        .unwrap();
2985
2986        // Write composer.json so Psr4Map::load can build the map.
2987        std::fs::write(
2988            tmp.path().join("composer.json"),
2989            r#"{"autoload":{"psr-4":{"App\\":"src/"}}}"#,
2990        )
2991        .unwrap();
2992
2993        let store = DocumentStore::new();
2994
2995        // Inject a PSR-4 map pointing at the tmp dir.
2996        store
2997            .psr4
2998            .store(Arc::new(crate::lang::autoload::Psr4Map::load(tmp.path())));
2999
3000        // Mirror the consuming file (Entity not yet in source_files).
3001        // Uses Entity as a parameter type hint — the analyzer resolves these
3002        // through use statements, so this exercises the full PSR-4 lazy-load path.
3003        let handler_url = Uri::from_file_path(tmp.path().join("src/Service/Handler.php")).unwrap();
3004        store.mirror_text(
3005            &handler_url,
3006            "<?php\nnamespace App\\Service;\nuse App\\Model\\Entity;\nfunction handle(Entity $e): Entity { return $e; }\n",
3007        );
3008
3009        let issues = store.get_semantic_issues_salsa(&handler_url).unwrap();
3010        let undef: Vec<_> = issues
3011            .iter()
3012            .filter(|i| matches!(i.kind, mir_issues::IssueKind::UndefinedClass { .. }))
3013            .collect();
3014        assert!(
3015            undef.is_empty(),
3016            "PSR-4 lazy-loading must prevent UndefinedClass for App\\Model\\Entity; got: {undef:?}"
3017        );
3018    }
3019
3020    /// Issue #243 repro: a PSR-0-autoloaded vendor class (PEAR-style, e.g.
3021    /// `Legacy_Service`) must lazy-load the same way PSR-4 classes do.
3022    #[test]
3023    fn psr0_lazy_load_suppresses_undefined_class_243_repro() {
3024        let tmp = tempfile::tempdir().unwrap();
3025
3026        std::fs::create_dir_all(tmp.path().join("vendor/legacy/src/Legacy")).unwrap();
3027        std::fs::write(
3028            tmp.path().join("vendor/legacy/src/Legacy/Service.php"),
3029            "<?php\n\nclass Legacy_Service\n{\n    public function name(): string\n    {\n        return 'legacy';\n    }\n}\n",
3030        )
3031        .unwrap();
3032
3033        std::fs::write(
3034            tmp.path().join("composer.json"),
3035            r#"{"autoload":{"psr-0":{"Legacy_":"vendor/legacy/src/"}}}"#,
3036        )
3037        .unwrap();
3038
3039        let store = DocumentStore::new();
3040        store
3041            .psr4
3042            .store(Arc::new(crate::lang::autoload::Psr4Map::load(tmp.path())));
3043
3044        let repro_url = Uri::from_file_path(tmp.path().join("repro.php")).unwrap();
3045        store.mirror_text(
3046            &repro_url,
3047            "<?php\n\n$service = new Legacy_Service();\necho $service->name();\n",
3048        );
3049
3050        let issues = store.get_semantic_issues_salsa(&repro_url).unwrap();
3051        let undef: Vec<_> = issues
3052            .iter()
3053            .filter(|i| matches!(i.kind, mir_issues::IssueKind::UndefinedClass { .. }))
3054            .collect();
3055        assert!(
3056            undef.is_empty(),
3057            "PSR-0 lazy-loading must prevent UndefinedClass for Legacy_Service; got: {undef:?}"
3058        );
3059    }
3060
3061    /// Regression (found while investigating issue #242, root cause is
3062    /// distinct from it — not fixed by the `is_index_ready` gate):
3063    /// `cached_analysis_if_fresh`'s staleness check is keyed on
3064    /// `decl_version`, which only bumps inside `cached_analysis_cancellable`
3065    /// when a file undergoes its *own* full analysis. Mirroring a brand new
3066    /// file into the store (`mirror_text`/`ingest_from_doc`, what a workspace
3067    /// scan or `didChangeWatchedFiles` CREATED event does) doesn't go through
3068    /// that path, so callers on that path must explicitly call
3069    /// `note_new_file_declarations` — exactly what `did_change_watched_files`
3070    /// now does — to invalidate consumers analyzed before the dependency
3071    /// existed.
3072    #[test]
3073    fn stale_cached_analysis_not_invalidated_by_new_dependency_file() {
3074        let store = DocumentStore::new();
3075        let consumer_uri = uri("/app.php");
3076        let dep_uri = uri("/Mage.php");
3077
3078        // Consumer references Mage before Mage exists anywhere in the store —
3079        // correctly flagged, and this analysis gets cached.
3080        store.mirror_text(&consumer_uri, "<?php\n\nnew Mage();\n");
3081        let issues = store.get_semantic_issues_salsa(&consumer_uri).unwrap();
3082        assert!(
3083            issues
3084                .iter()
3085                .any(|i| matches!(i.kind, mir_issues::IssueKind::UndefinedClass { .. })),
3086            "sanity check: Mage must be reported missing before it exists"
3087        );
3088
3089        // Mage now becomes known to the store — exactly what a workspace
3090        // scan or a `didChangeWatchedFiles` CREATED event does.
3091        store.mirror_text(&dep_uri, "<?php\nclass Mage {}\n");
3092        store.note_new_file_declarations(&dep_uri);
3093
3094        // Consumer's diagnostics should now resolve cleanly.
3095        let issues = store.get_semantic_issues_salsa(&consumer_uri).unwrap();
3096        assert!(
3097            !issues
3098                .iter()
3099                .any(|i| matches!(i.kind, mir_issues::IssueKind::UndefinedClass { .. })),
3100            "Mage now exists, but consumer.php's cached analysis was never \
3101             invalidated: {issues:?}"
3102        );
3103    }
3104
3105    /// Issue #191 regression: workspace-wide scans (find-references, rename,
3106    /// call-hierarchy) must not re-parse closed/indexed files on repeated
3107    /// invocations. Once a file's `ParsedDoc` has been produced, subsequent
3108    /// `all_docs_for_scan()` calls must hit the cache and return the same
3109    /// `Arc<ParsedDoc>` (pointer equality), proving no re-parse occurred.
3110    ///
3111    /// The cache layers protecting this are:
3112    ///   1. `parsed_cache` (cap [`PARSED_CACHE_CAP`]) — read-through, validated
3113    ///      via `Arc::ptr_eq` on the text Arc.
3114    ///   2. salsa `parsed_doc` memo (`lru = 2048`) — second line of defense
3115    ///      when `parsed_cache` evicts.
3116    ///
3117    /// Together they keep every workspace-scan op O(N) memo lookups, never
3118    /// O(N) parses, for any workspace whose file count fits the cap.
3119    #[test]
3120    fn all_docs_for_scan_does_not_reparse_indexed_files() {
3121        let store = DocumentStore::new();
3122        const N: usize = 50;
3123        for i in 0..N {
3124            let u = uri(&format!("/scan/file{i}.php"));
3125            store.ingest(u, &format!("<?php\nclass C{i} {{}}\nfunction f{i}() {{}}"));
3126        }
3127
3128        let first: Vec<_> = store.all_docs_for_scan();
3129        let second: Vec<_> = store.all_docs_for_scan();
3130        assert_eq!(first.len(), N);
3131        assert_eq!(second.len(), N);
3132
3133        let by_url_first: std::collections::HashMap<Uri, Arc<ParsedDoc>> =
3134            first.into_iter().collect();
3135        for (u, doc2) in second {
3136            let doc1 = by_url_first
3137                .get(&u)
3138                .expect("second scan returned a URL the first didn't");
3139            assert!(
3140                Arc::ptr_eq(doc1, &doc2),
3141                "{u:?} re-parsed across all_docs_for_scan calls — \
3142                 cache (parsed_cache + salsa parsed_doc memo) failed to hit"
3143            );
3144        }
3145
3146        // Editing one file's text must invalidate just that file's entry,
3147        // not the rest. This locks in self-eviction via Arc::ptr_eq on text.
3148        let edited_url = uri("/scan/file0.php");
3149        let pre_edit = store.get_doc_salsa(&edited_url).unwrap();
3150        store.ingest(edited_url.clone(), "<?php\nclass C0Edited {}");
3151        let post_edit = store.get_doc_salsa(&edited_url).unwrap();
3152        assert!(
3153            !Arc::ptr_eq(&pre_edit, &post_edit),
3154            "edited file must produce a fresh ParsedDoc"
3155        );
3156        for i in 1..N {
3157            let u = uri(&format!("/scan/file{i}.php"));
3158            let original = by_url_first.get(&u).unwrap();
3159            let after = store.get_doc_salsa(&u).unwrap();
3160            assert!(
3161                Arc::ptr_eq(original, &after),
3162                "{u:?} should not have re-parsed because of an unrelated edit"
3163            );
3164        }
3165    }
3166
3167    /// Incremental analysis cache: a body-only edit to file A (no declaration
3168    /// changes) must not bump `decl_version`, so file B's cached analysis
3169    /// survives. A declaration edit MUST bump the version so B's entry goes
3170    /// stale.
3171    #[test]
3172    fn body_only_edit_does_not_invalidate_sibling_analysis_cache() {
3173        let store = DocumentStore::new();
3174        let ua = uri("/ic_a.php");
3175        let ub = uri("/ic_b.php");
3176
3177        // Analyze both files to establish their fingerprints.
3178        open(
3179            &store,
3180            ua.clone(),
3181            "<?php\nfunction a() { return 1; }".to_string(),
3182        );
3183        open(
3184            &store,
3185            ub.clone(),
3186            "<?php\nfunction b() { return 2; }".to_string(),
3187        );
3188        let _ = store.cached_analysis(&ua).unwrap();
3189        let analysis_b_first = store.cached_analysis(&ub).unwrap();
3190        let ver_after_warm = store.caches.decl_version();
3191
3192        // Body-only edit to A: same function name, different body → FileIndex unchanged.
3193        store.mirror_text(&ua, "<?php\nfunction a() { return 999; }");
3194        let _ = store.cached_analysis(&ua);
3195        let ver_after_body_edit = store.caches.decl_version();
3196        assert_eq!(
3197            ver_after_warm, ver_after_body_edit,
3198            "body-only edit must not bump decl_version"
3199        );
3200
3201        // B's cached entry should still be valid (ptr-eq source AND same version).
3202        let analysis_b_second = store.cached_analysis_if_fresh(&ub);
3203        assert!(
3204            analysis_b_second.is_some(),
3205            "B's analysis should hit cache after body-only edit to A"
3206        );
3207        assert!(
3208            Arc::ptr_eq(&analysis_b_first, &analysis_b_second.unwrap()),
3209            "B's analysis should be the identical Arc (no re-analysis)"
3210        );
3211
3212        // Declaration edit to A: rename the function → FileIndex changes.
3213        store.mirror_text(&ua, "<?php\nfunction a_renamed() { return 999; }");
3214        let _ = store.cached_analysis(&ua);
3215        let ver_after_decl_edit = store.caches.decl_version();
3216        assert!(
3217            ver_after_decl_edit > ver_after_body_edit,
3218            "declaration edit must bump decl_version (was {ver_after_body_edit}, now {ver_after_decl_edit})"
3219        );
3220
3221        // B's entry is now stale — cached_analysis_if_fresh must return None.
3222        let analysis_b_stale = store.cached_analysis_if_fresh(&ub);
3223        assert!(
3224            analysis_b_stale.is_none(),
3225            "B's analysis should be stale after A's declaration changed"
3226        );
3227    }
3228
3229    /// snapshot_query must complete without panic when a concurrent writer
3230    /// races the snapshot. The single-retry-then-lock logic should handle this
3231    /// correctly: the lock-held fallback guarantees progress.
3232    #[test]
3233    fn snapshot_query_survives_concurrent_writes() {
3234        use std::sync::Arc;
3235        use std::thread;
3236        use std::time::{Duration, Instant};
3237
3238        let store = Arc::new(DocumentStore::new());
3239        let u = uri("/sq_test.php");
3240        open(
3241            &store,
3242            u.clone(),
3243            "<?php\nfunction f(): int { return 1; }".to_string(),
3244        );
3245
3246        let deadline = Instant::now() + Duration::from_millis(200);
3247        let mut handles = Vec::new();
3248
3249        // Writer: keep bumping the file text to trigger salsa::Cancelled.
3250        {
3251            let store = Arc::clone(&store);
3252            let u = u.clone();
3253            handles.push(thread::spawn(move || {
3254                let mut rev = 0u32;
3255                while Instant::now() < deadline {
3256                    store.mirror_text(&u, &format!("<?php\nfunction f(): int {{ return {rev}; }}"));
3257                    rev += 1;
3258                }
3259            }));
3260        }
3261
3262        // Reader: hammer snapshot_query via get_doc_salsa.
3263        for _ in 0..4 {
3264            let store = Arc::clone(&store);
3265            let u = u.clone();
3266            handles.push(thread::spawn(move || {
3267                while Instant::now() < deadline {
3268                    let _ = store.get_doc_salsa(&u);
3269                    let _ = store.get_index_salsa(&u);
3270                }
3271            }));
3272        }
3273
3274        for h in handles {
3275            h.join()
3276                .expect("no panic in snapshot_query under concurrent writes");
3277        }
3278    }
3279
3280    /// Concurrent callers racing to analyze the SAME uncached file (e.g.
3281    /// `did_open`'s diagnostics trigger vs. a fast-following hover, which
3282    /// tower-lsp's default concurrency genuinely allows) must serialize onto
3283    /// one `FileAnalyzer::analyze` run and all observe its identical result
3284    /// — not each redo the full analysis independently.
3285    #[test]
3286    fn concurrent_callers_share_one_analysis_computation() {
3287        use std::sync::{Arc, Barrier};
3288        use std::thread;
3289
3290        let store = Arc::new(DocumentStore::new());
3291        let u = uri("/inflight_test.php");
3292        open(
3293            &store,
3294            u.clone(),
3295            "<?php\nfunction f(): int { return 1; }".to_string(),
3296        );
3297
3298        const N: usize = 8;
3299        let barrier = Arc::new(Barrier::new(N));
3300        let handles: Vec<_> = (0..N)
3301            .map(|_| {
3302                let store = Arc::clone(&store);
3303                let u = u.clone();
3304                let barrier = Arc::clone(&barrier);
3305                thread::spawn(move || {
3306                    barrier.wait();
3307                    store.cached_analysis(&u)
3308                })
3309            })
3310            .collect();
3311        let results: Vec<_> = handles
3312            .into_iter()
3313            .map(|h| h.join().expect("no panic in cached_analysis"))
3314            .collect();
3315
3316        assert_eq!(
3317            store.analysis_compute_count(),
3318            1,
3319            "{N} concurrent callers analyzing the same uncached file must compute once, not {N} times"
3320        );
3321        let first = results[0].clone().expect("analysis must succeed");
3322        for r in &results {
3323            let r = r.as_ref().expect("analysis must succeed");
3324            assert!(
3325                Arc::ptr_eq(&first, r),
3326                "every caller must observe the identical analysis Arc, not its own copy"
3327            );
3328        }
3329    }
3330
3331    /// Manual perf diagnostic (`cargo test --release -- --ignored --nocapture
3332    /// diagnostic_coalescing_cpu_time_ms`): N threads race `cached_analysis`
3333    /// for the same uncached, moderately expensive file. `computations`
3334    /// (from `analysis_compute_count`) is the direct proof of the fix: it
3335    /// must stay at 1 regardless of N. `wall_ms` is secondary color — without
3336    /// the per-URI lock, N threads each independently running the full
3337    /// analyze pass genuinely in parallel can contend for the same cores/
3338    /// caches and degrade wall time as N grows past the core count; with the
3339    /// lock, added threads just wait on the one real computation.
3340    #[test]
3341    #[ignore]
3342    fn diagnostic_coalescing_cpu_time_ms() {
3343        use std::sync::{Arc, Barrier};
3344        use std::thread;
3345        use std::time::Instant;
3346
3347        let mut src = "<?php\nclass Big {\n".to_string();
3348        for m in 0..200 {
3349            src.push_str(&format!(
3350                "    public function m{m}(int $x): int {{ $y = $x * {m} + strlen((string)$x); return $y > 0 ? $y : -$y; }}\n"
3351            ));
3352        }
3353        src.push_str("}\n");
3354
3355        for &nthreads in &[1usize, 4, 8, 16, 32] {
3356            let store = Arc::new(DocumentStore::new());
3357            let u = uri("/coalesce_bench.php");
3358            open(&store, u.clone(), src.clone());
3359
3360            let barrier = Arc::new(Barrier::new(nthreads));
3361            let wall_start = Instant::now();
3362            let handles: Vec<_> = (0..nthreads)
3363                .map(|_| {
3364                    let store = Arc::clone(&store);
3365                    let u = u.clone();
3366                    let barrier = Arc::clone(&barrier);
3367                    thread::spawn(move || {
3368                        barrier.wait();
3369                        let _ = store.cached_analysis(&u);
3370                    })
3371                })
3372                .collect();
3373            for h in handles {
3374                h.join().unwrap();
3375            }
3376            let wall_ms = wall_start.elapsed().as_secs_f64() * 1000.0;
3377            eprintln!(
3378                "threads={nthreads:>3}  computations={:>3}  wall_ms={wall_ms:>8.3}",
3379                store.analysis_compute_count()
3380            );
3381        }
3382    }
3383
3384    /// Manual perf diagnostic (`cargo test --release -- --ignored --nocapture
3385    /// diagnostic_batch_vs_per_symbol_scan_ms`), not a CI-run assertion:
3386    /// isolates the pure scan-count effect of `batch_reference_candidate_files`
3387    /// vs M independent `reference_candidate_files` calls, excluding the
3388    /// surrounding `code_lenses()`/`indexed_references` cost entirely — this
3389    /// measures scope narrowing alone. See `benches/code_lens_scaling.rs` for
3390    /// the end-to-end request-level number.
3391    #[test]
3392    #[ignore]
3393    fn diagnostic_batch_vs_per_symbol_scan_ms() {
3394        use std::time::Instant;
3395        let num_methods = 100usize;
3396        for &n_noise in &[500usize, 1500, 3000, 8000] {
3397            let store = DocumentStore::new();
3398            let owner = "App\\Service";
3399            let mut src = "<?php\nnamespace App;\nclass Service {\n".to_string();
3400            for m in 0..num_methods {
3401                src.push_str(&format!(
3402                    "    public static function alpha{m}(): void {{}}\n"
3403                ));
3404            }
3405            src.push_str("}\n");
3406            store.ingest(("file:///synth/Service.php").parse::<Uri>().unwrap(), &src);
3407            for i in 0..n_noise {
3408                let u = format!("file:///synth/N{i}.php").parse::<Uri>().unwrap();
3409                let t = format!(
3410                    "<?php\nnamespace Other{i};\nclass N{i} {{ public function run(){{}} }}\n"
3411                );
3412                store.ingest(u, &t);
3413            }
3414            store.mark_index_ready();
3415
3416            let mut symbols = vec![mir_analyzer::Name::class(owner)];
3417            for m in 0..num_methods {
3418                symbols.push(mir_analyzer::Name::method(owner, &format!("alpha{m}")));
3419            }
3420
3421            let t = Instant::now();
3422            for s in &symbols {
3423                std::hint::black_box(store.reference_candidate_files(s));
3424            }
3425            let per_symbol_ms = t.elapsed().as_secs_f64() * 1000.0;
3426
3427            let t = Instant::now();
3428            std::hint::black_box(store.batch_reference_candidate_files(&symbols));
3429            let batch_ms = t.elapsed().as_secs_f64() * 1000.0;
3430
3431            eprintln!(
3432                "n_noise={n_noise:>6}  symbols={:>4}  per_symbol_ms={per_symbol_ms:>10.3}  batch_ms={batch_ms:>10.3}  speedup={:>6.2}x",
3433                symbols.len(),
3434                per_symbol_ms / batch_ms
3435            );
3436        }
3437    }
3438
3439    /// Manual perf diagnostic (`cargo test --release -- --ignored --nocapture
3440    /// diagnostic_priority_scan_avoided_cost_ms`): measures the cost of
3441    /// `handle_references`'s priority-partition owner-mention scan
3442    /// (`navigation.rs`) run over an already-narrowed candidate scope — the
3443    /// exact cost `method_scope_is_narrowed` now lets the handler skip
3444    /// entirely for private/protected/static methods. The scope size here
3445    /// models a protected method's subtype-closure narrowing (the case where
3446    /// a widely-subclassed base class makes the "narrowed" scope non-trivial).
3447    #[test]
3448    #[ignore]
3449    fn diagnostic_priority_scan_avoided_cost_ms() {
3450        use std::time::Instant;
3451
3452        let store = DocumentStore::new();
3453        let owner_short = "Owner";
3454        for &n in &[10usize, 100, 1000, 3000] {
3455            let mut files: Vec<Arc<str>> = Vec::with_capacity(n);
3456            for i in 0..n {
3457                let u = format!("file:///synth/S{i}.php").parse::<Uri>().unwrap();
3458                let t = format!(
3459                    "<?php\nclass S{i} extends Owner {{\n\
3460                     \x20   public function run(): void {{\n\
3461                     \x20       parent::process();\n\
3462                     \x20   }}\n\
3463                     }}\n"
3464                );
3465                store.ingest(u.clone(), &t);
3466                files.push(Arc::<str>::from(u.as_str()));
3467            }
3468
3469            let t0 = Instant::now();
3470            use rayon::prelude::*;
3471            let matched: Vec<Arc<str>> = files
3472                .par_iter()
3473                .filter(|f| {
3474                    (f.as_ref())
3475                        .parse::<Uri>()
3476                        .ok()
3477                        .and_then(|u| store.source_text(&u))
3478                        .is_some_and(|txt| {
3479                            crate::text::contains_ascii_case_insensitive(&txt, owner_short)
3480                        })
3481                })
3482                .cloned()
3483                .collect();
3484            let avoided_ms = t0.elapsed().as_secs_f64() * 1000.0;
3485            eprintln!(
3486                "narrowed_scope_files={n:>5}  avoided_scan_ms={avoided_ms:>9.4}  matched={}  (new code: 0.000ms — skipped entirely)",
3487                matched.len()
3488            );
3489        }
3490    }
3491
3492    /// Manual perf diagnostic (`cargo test --release -- --ignored --nocapture
3493    /// diagnostic_laravel_scan_blocking_vs_spawn_blocking`): demonstrates the
3494    /// actual effect of moving `handle_references`'s Laravel string-key scan
3495    /// (`navigation.rs`) into `spawn_blocking`. On a single-worker-thread
3496    /// runtime, a CPU-bound scan with no `.await` points inside it hogs that
3497    /// one worker until it completes — a concurrently-spawned trivial task
3498    /// can't run until the scan yields. `spawn_blocking` moves the scan to a
3499    /// separate thread, freeing the worker immediately.
3500    #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
3501    #[ignore]
3502    async fn diagnostic_laravel_scan_blocking_vs_spawn_blocking() {
3503        use std::time::Instant;
3504
3505        fn run_scan_inline(store: &DocumentStore, n: usize) -> usize {
3506            let mut count = 0;
3507            for i in 0..n {
3508                let u = format!("file:///synth/F{i}.php").parse::<Uri>().unwrap();
3509                if store
3510                    .source_text(&u)
3511                    .is_some_and(|t| t.contains("APP_NAME_0"))
3512                    && let Some(doc) = store.get_doc_salsa(&u)
3513                {
3514                    let _ = crate::laravel::find_call_sites(&doc, &["env"], "APP_NAME_0");
3515                    count += 1;
3516                }
3517            }
3518            count
3519        }
3520
3521        let store = Arc::new(DocumentStore::new());
3522        let n = 30_000usize;
3523        for i in 0..n {
3524            let u = format!("file:///synth/F{i}.php").parse::<Uri>().unwrap();
3525            let t = format!("<?php\n$x = env('APP_NAME_{i}');\n");
3526            store.ingest(u, &t);
3527        }
3528
3529        // Both scenarios spawn the scan AND a trivial task as separate
3530        // `tokio::spawn`ed tasks — the same relationship real tower-lsp
3531        // request handlers have (each dispatched request is its own spawned
3532        // task on the shared worker pool), unlike driving the scan inline in
3533        // this test function's own body (which `#[tokio::test]` runs via
3534        // `block_on` on the harness thread, not a pool worker, and so
3535        // wouldn't actually contend with `tokio::spawn`ed tasks at all).
3536
3537        // OLD shape: scan task runs the work inline, no yield points inside.
3538        let spawn_time = Instant::now();
3539        let store_c = Arc::clone(&store);
3540        let scan_handle = tokio::spawn(async move { run_scan_inline(&store_c, n) });
3541        let (tx, rx) = tokio::sync::oneshot::channel();
3542        tokio::spawn(async move {
3543            let _ = tx.send(Instant::now());
3544        });
3545        let matched = scan_handle.await.unwrap();
3546        let scan_ms = spawn_time.elapsed().as_secs_f64() * 1000.0;
3547        let trivial_ran_at = rx.await.unwrap();
3548        let trivial_delay_ms = trivial_ran_at.duration_since(spawn_time).as_secs_f64() * 1000.0;
3549        eprintln!(
3550            "OLD (inline on the request's own task):  scan_ms={scan_ms:>8.3}  matched={matched:>4}  concurrent_trivial_task_delay_ms={trivial_delay_ms:>8.3}"
3551        );
3552
3553        // NEW shape: scan task hands the work to spawn_blocking and awaits it.
3554        let spawn_time = Instant::now();
3555        let store_c = Arc::clone(&store);
3556        let scan_handle = tokio::spawn(async move {
3557            tokio::task::spawn_blocking(move || run_scan_inline(&store_c, n))
3558                .await
3559                .unwrap()
3560        });
3561        let (tx, rx) = tokio::sync::oneshot::channel();
3562        tokio::spawn(async move {
3563            let _ = tx.send(Instant::now());
3564        });
3565        let matched = scan_handle.await.unwrap();
3566        let scan_ms = spawn_time.elapsed().as_secs_f64() * 1000.0;
3567        let trivial_ran_at = rx.await.unwrap();
3568        let trivial_delay_ms = trivial_ran_at.duration_since(spawn_time).as_secs_f64() * 1000.0;
3569        eprintln!(
3570            "NEW (via spawn_blocking):                scan_ms={scan_ms:>8.3}  matched={matched:>4}  concurrent_trivial_task_delay_ms={trivial_delay_ms:>8.3}"
3571        );
3572    }
3573
3574    /// When a sibling file's declaration changes (bumping decl_version), the
3575    /// owned_program_cache entry for the unchanged file B should be reused
3576    /// rather than deep-cloned again. We verify this via Arc pointer equality.
3577    #[test]
3578    fn owned_program_cache_reused_after_sibling_declaration_change() {
3579        let store = DocumentStore::new();
3580        let ua = uri("/prog_a.php");
3581        let ub = uri("/prog_b.php");
3582
3583        open(
3584            &store,
3585            ua.clone(),
3586            "<?php\nfunction alpha(): void {}".to_string(),
3587        );
3588        open(
3589            &store,
3590            ub.clone(),
3591            "<?php\nfunction beta(): void {}".to_string(),
3592        );
3593
3594        // Warm both analysis caches and populate owned_program_cache for both files.
3595        let _ = store.cached_analysis(&ua);
3596        let _ = store.cached_analysis(&ub);
3597
3598        // Capture B's owned_program Arc before the sibling edit.
3599        let prog_b_first = store
3600            .caches
3601            .owned_program_cache
3602            .get(&ub)
3603            .map(|e| Arc::clone(&e.1))
3604            .expect("B's owned_program should be cached after first analysis");
3605
3606        // Declaration change to A: bumps decl_version, invalidating all cached_analysis entries.
3607        store.mirror_text(&ua, "<?php\nfunction alpha_renamed(): void {}");
3608        // Re-analyze A to trigger the decl_version bump.
3609        let _ = store.cached_analysis(&ua);
3610
3611        // Now re-analyze B. Its source is unchanged, so owned_program_cache must hit.
3612        let _ = store.cached_analysis(&ub);
3613
3614        let prog_b_second = store
3615            .caches
3616            .owned_program_cache
3617            .get(&ub)
3618            .map(|e| Arc::clone(&e.1))
3619            .expect("B's owned_program should still be cached after sibling edit");
3620
3621        assert!(
3622            Arc::ptr_eq(&prog_b_first, &prog_b_second),
3623            "B's owned_program Arc should be identical (cache hit) after sibling declaration change"
3624        );
3625    }
3626
3627    /// write_rev() increments on each real text write (identical text is a no-op).
3628    #[test]
3629    fn write_rev_increments_on_write() {
3630        let store = DocumentStore::new();
3631        let u = uri("/rev_test.php");
3632        let before = store.write_rev();
3633        store.mirror_text(&u, "<?php echo 1;");
3634        let after_first = store.write_rev();
3635        assert!(after_first > before, "first write must bump the revision");
3636        // Identical text must NOT bump the revision (fast path).
3637        store.mirror_text(&u, "<?php echo 1;");
3638        assert_eq!(
3639            store.write_rev(),
3640            after_first,
3641            "identical text must not bump the revision"
3642        );
3643        // Different text must bump again.
3644        store.mirror_text(&u, "<?php echo 2;");
3645        assert!(
3646            store.write_rev() > after_first,
3647            "changed text must bump the revision"
3648        );
3649    }
3650
3651    /// begin_reanalyze() cancels the previously-issued sweep token so a newer
3652    /// edit preempts an in-flight dependent walk, and hands back a fresh token.
3653    #[test]
3654    fn begin_reanalyze_cancels_previous_token() {
3655        let store = DocumentStore::new();
3656        let first = store.begin_reanalyze();
3657        assert!(!first.is_cancelled(), "a fresh token starts un-cancelled");
3658        let second = store.begin_reanalyze();
3659        assert!(
3660            first.is_cancelled(),
3661            "issuing a new token must cancel the previous in-flight sweep"
3662        );
3663        assert!(
3664            !second.is_cancelled(),
3665            "the newly-issued token must itself be un-cancelled"
3666        );
3667    }
3668
3669    /// A session built before the cache dir is known (an editor's
3670    /// restored-buffer `didOpen` racing `initialized`) must be rebuilt with
3671    /// the cache attached when the dir arrives — not stay pinned
3672    /// in-memory-only for the server's lifetime.
3673    #[test]
3674    fn set_session_cache_dir_rebuilds_pinned_session() {
3675        let store = DocumentStore::new();
3676        let early = store.analysis_session(mir_analyzer::PhpVersion::LATEST);
3677        let dir = tempfile::tempdir().unwrap();
3678        store.set_session_cache_dir(dir.path().to_path_buf());
3679        let rebuilt = store.analysis_session(mir_analyzer::PhpVersion::LATEST);
3680        assert!(
3681            !Arc::ptr_eq(&early, &rebuilt),
3682            "the cache-less early session must be dropped and rebuilt"
3683        );
3684        assert!(
3685            dir.path().join("stubs").exists(),
3686            "the rebuilt session must have opened the on-disk stub cache"
3687        );
3688    }
3689
3690    /// write_rev() increments when a file is removed.
3691    #[test]
3692    fn write_rev_increments_on_remove() {
3693        let store = DocumentStore::new();
3694        let u = uri("/rev_remove.php");
3695        store.mirror_text(&u, "<?php class A {}");
3696        let before = store.write_rev();
3697        store.remove(&u);
3698        assert!(store.write_rev() > before, "remove must bump the revision");
3699    }
3700}