Skip to main content

fallow_engine/
session.rs

1//! Engine-owned analysis session orchestration.
2
3use std::path::{Path, PathBuf};
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::sync::{Arc, Mutex};
6use std::time::Instant;
7
8use fallow_config::{ResolvedConfig, WorkspaceInfo};
9use fallow_types::discover::DiscoveredFile;
10use fallow_types::extract::{ModuleInfo, SourceParseDegradation, SourceReadFailure};
11#[cfg(test)]
12use fallow_types::results::AnalysisResults;
13use fallow_types::source_fingerprint::{SourceFingerprint, now_ns};
14use fallow_types::workspace::{WorkspaceDiagnostic, merge_workspace_diagnostics};
15use rustc_hash::{FxHashMap, FxHashSet};
16
17pub use crate::session_reuse::SessionParseCounts;
18use crate::session_reuse::{
19    MAX_INCREMENTAL_REPARSE_FILES, ParseCountCells, changed_file_indices, merge_reparsed_modules,
20};
21use crate::{
22    EngineResult, core_backend,
23    project_config::{DuplicationScope, ProjectConfig},
24    results::{
25        DeadCodeAnalysis, DeadCodeAnalysisArtifacts, DeadCodeAnalysisOutput,
26        SharedDeadCodeAnalysisArtifacts,
27    },
28    warm_parse::{WarmParse, WarmParseKey, WarmParseStore},
29};
30
31/// Reusable engine session for one resolved project.
32///
33/// The session owns the resolved config and discovered file set so future
34/// consumers can share graph-sensitive inputs without each surface recreating
35/// its own partial orchestration.
36#[derive(Debug)]
37pub struct AnalysisSession {
38    pub(crate) config: ResolvedConfig,
39    config_path: Option<PathBuf>,
40    config_inputs: fallow_config::ConfigInputs,
41    config_inputs_before_resolve: fallow_config::ConfigInputsSnapshot,
42    pub(crate) discovery: crate::discover::AnalysisDiscovery,
43    workspaces: Vec<WorkspaceInfo>,
44    workspace_diagnostics: Vec<WorkspaceDiagnostic>,
45    parsed_cache: Mutex<Option<ParsedModuleCache>>,
46    styling_cache: Mutex<Option<Arc<crate::health::StylingAnalysisArtifacts>>>,
47    pub(crate) cancellation: Option<Arc<AtomicBool>>,
48    warm_parse: Option<Arc<WarmParseStore>>,
49    /// Config load already resolved the workspaces, so a discovery refresh
50    /// keeps them.
51    preloaded_workspaces: bool,
52    parse_counts: ParseCountCells,
53    /// An incremental parse changed modules that the persisted parse cache
54    /// does not hold yet. [`AnalysisSession::flush_parse_cache`] writes them.
55    disk_cache_stale: AtomicBool,
56    duplication: duplication::DuplicationFiles,
57}
58
59#[derive(Debug)]
60struct ParsedModuleCache {
61    need_complexity: bool,
62    fingerprints: Vec<SourceFingerprint>,
63    /// The wall-clock time before the session read `fingerprints`. A
64    /// fingerprint that is not settled before this time can belong to a
65    /// later write in the same timestamp tick, so it does not prove that the
66    /// module is current.
67    read_started_ns: u64,
68    modules: Arc<[ModuleInfo]>,
69    /// The read failures of the parse, kept so that an incremental parse can
70    /// record the full set of the project again.
71    read_failures: Vec<SourceReadFailure>,
72    /// The parse degradations of the parse, kept for the same reason.
73    parse_degradations: Vec<SourceParseDegradation>,
74}
75
76/// Owned session parts for runners that need to continue an existing pipeline.
77#[derive(Debug)]
78pub struct AnalysisSessionParts {
79    /// Resolved project config the session was created with.
80    pub config: ResolvedConfig,
81    /// Path of the loaded config file; `None` when defaults were used.
82    pub config_path: Option<PathBuf>,
83    /// Files discovered under the session root.
84    pub files: Vec<DiscoveredFile>,
85    /// Workspace metadata discovered during config resolution.
86    pub workspaces: Vec<WorkspaceInfo>,
87    /// Diagnostics from workspace discovery (undeclared or invalid members).
88    pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
89}
90
91/// Owned session parts after parsing the discovered files.
92#[derive(Debug)]
93pub struct ParsedAnalysisSessionParts {
94    /// Resolved project config the session was created with.
95    pub config: ResolvedConfig,
96    /// Path of the loaded config file; `None` when defaults were used.
97    pub config_path: Option<PathBuf>,
98    /// Files discovered under the session root.
99    pub files: Vec<DiscoveredFile>,
100    /// Parsed modules, one per discovered file.
101    pub modules: Vec<ModuleInfo>,
102    /// Workspace metadata discovered during config resolution.
103    pub workspaces: Vec<WorkspaceInfo>,
104    /// Diagnostics from workspace discovery (undeclared or invalid members).
105    pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
106    /// Parse wall time in milliseconds.
107    pub parse_ms: f64,
108    /// Parse-cache write-back wall time in milliseconds.
109    pub cache_update_ms: f64,
110    /// Files served from the parse cache.
111    pub cache_hits: usize,
112    /// Files that had to be parsed fresh.
113    pub cache_misses: usize,
114    /// Summed parse CPU time across rayon workers in milliseconds.
115    pub parse_cpu_ms: f64,
116}
117
118#[derive(Debug)]
119pub(crate) struct SharedParsedAnalysisSessionParts {
120    pub(crate) config: ResolvedConfig,
121    pub(crate) files: Vec<DiscoveredFile>,
122    pub(crate) modules: Arc<[ModuleInfo]>,
123    pub workspaces: Vec<WorkspaceInfo>,
124    pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
125    pub parse_ms: f64,
126    pub parse_cpu_ms: f64,
127}
128
129/// Reusable artifacts produced by one session-owned dead-code run.
130#[derive(Debug)]
131pub struct AnalysisSessionArtifacts {
132    /// Retained dead-code analysis output (results, graph, timings).
133    pub analysis: DeadCodeAnalysisArtifacts,
134    /// Diff scope the run was limited to, when one was resolved.
135    pub changed_files: Option<FxHashSet<PathBuf>>,
136    /// Per-file source fingerprints for downstream cache invalidation.
137    pub source_fingerprints: FxHashMap<PathBuf, SourceFingerprint>,
138}
139
140impl AnalysisSession {
141    /// Build a session from the project config of a mode entry.
142    #[must_use]
143    pub(crate) fn from_project_config(project_config: ProjectConfig) -> Self {
144        let uses_preloaded_workspaces = project_config.workspace_discovery_ms.is_some();
145        let discovery = if let Some(workspace_discovery_ms) = project_config.workspace_discovery_ms
146        {
147            crate::discover::prepare_analysis_discovery_with_workspaces(
148                &project_config.config,
149                &project_config.workspaces,
150                workspace_discovery_ms,
151            )
152        } else {
153            crate::discover::prepare_analysis_discovery(&project_config.config)
154        };
155        let workspaces = if uses_preloaded_workspaces {
156            project_config.workspaces
157        } else {
158            discovery.workspaces().to_vec()
159        };
160        // Read analysis-stage entries live. Concurrent walks can have different
161        // production scopes, so keep source skips from this walk (#2366).
162        let workspace_diagnostics = merge_workspace_diagnostics(
163            merge_workspace_diagnostics(
164                project_config.workspace_diagnostics,
165                fallow_config::workspace_diagnostics_for(&project_config.config.root)
166                    .into_iter()
167                    .filter(|diagnostic| {
168                        !diagnostic.kind.is_analysis_stage()
169                            && !diagnostic.kind.is_source_discovery()
170                    })
171                    .collect(),
172            ),
173            discovery.source_diagnostics().to_vec(),
174        );
175        Self {
176            config: project_config.config,
177            config_path: project_config.path,
178            config_inputs: project_config.inputs,
179            config_inputs_before_resolve: project_config.inputs_before_resolve,
180            discovery,
181            workspaces,
182            workspace_diagnostics,
183            parsed_cache: Mutex::new(None),
184            styling_cache: Mutex::new(None),
185            cancellation: None,
186            warm_parse: crate::warm_parse::installed(),
187            preloaded_workspaces: uses_preloaded_workspaces,
188            parse_counts: ParseCountCells::default(),
189            disk_cache_stale: AtomicBool::new(false),
190            duplication: duplication::DuplicationFiles::new(project_config.duplication),
191        }
192    }
193
194    /// Attach a caller-owned cancellation token to this session.
195    ///
196    /// Analyses that run through the session check the token at each pipeline
197    /// stage boundary and inside the per-file parse loop, and return
198    /// [`crate::EngineError::cancelled`] instead of a partial result once it is
199    /// set. A session without a token can never be cancelled, so existing
200    /// callers keep their current behavior.
201    ///
202    /// The stop is cooperative, and how long it takes is bounded by the
203    /// longest stage that holds no check, not by any promised latency. Only
204    /// the parse loop stops per file. Duplication detection (tokenization plus
205    /// suffix-array matching) and the dead-code detectors run to the end of the
206    /// stage once entered, and on a large repository either is seconds of work.
207    /// A caller that needs a bounded stop has to kill the process instead.
208    #[must_use]
209    pub fn with_cancellation(mut self, cancellation: Arc<AtomicBool>) -> Self {
210        self.cancellation = Some(cancellation);
211        self
212    }
213
214    /// Use `store` for parsed modules across sessions, in place of the store
215    /// that the process installed with [`crate::warm_parse::install`].
216    /// `None` makes the session parse through the persisted cache only.
217    #[cfg(all(test, unix))]
218    fn with_warm_parse(mut self, store: Option<Arc<WarmParseStore>>) -> Self {
219        self.warm_parse = store;
220        self
221    }
222
223    /// Replace the cancellation token of a session that serves several runs.
224    ///
225    /// A long-lived session gets the token of each new run, so a set token of
226    /// an earlier run does not stop the next one.
227    pub fn set_cancellation(&mut self, cancellation: Arc<AtomicBool>) {
228        self.cancellation = Some(cancellation);
229    }
230
231    /// The parse work of this session since it was created.
232    #[must_use]
233    pub fn parse_counts(&self) -> SessionParseCounts {
234        self.parse_counts.snapshot()
235    }
236
237    /// Walk the project again and keep the parsed modules when the file set
238    /// did not change.
239    ///
240    /// A session that serves several runs calls this before each run, so a
241    /// created or deleted file reaches the analysis without a config reload.
242    /// When the file set changed, the file ids move, so the session writes its
243    /// parsed modules to the persisted parse cache and drops them. The next
244    /// parse then reads that cache. Returns whether the file set changed.
245    ///
246    /// The session also drops its modules when a fingerprint of the cached
247    /// parse cannot stand in for the file content, as on a platform without
248    /// ctime. A same-size edit with a restored mtime keeps such a
249    /// fingerprint, so only the persisted cache, which then compares content
250    /// hashes, can tell whether the module is current.
251    pub fn refresh_discovery(&mut self) -> bool {
252        let discovery = if self.preloaded_workspaces {
253            crate::discover::prepare_analysis_discovery_with_workspaces(
254                &self.config,
255                &self.workspaces,
256                0.0,
257            )
258        } else {
259            crate::discover::prepare_analysis_discovery(&self.config)
260        };
261        let same_files = discovery.files().len() == self.files().len()
262            && discovery
263                .files()
264                .iter()
265                .zip(self.files())
266                .all(|(fresh, known)| fresh.path == known.path);
267        if !same_files || !self.cached_fingerprints_are_trustworthy() {
268            self.flush_parse_cache();
269            *self
270                .parsed_cache
271                .get_mut()
272                .unwrap_or_else(std::sync::PoisonError::into_inner) = None;
273            self.clear_styling_cache();
274        }
275        if !self.preloaded_workspaces {
276            self.workspaces = discovery.workspaces().to_vec();
277        }
278        if !self.discovery.source_diagnostics().is_empty()
279            || !discovery.source_diagnostics().is_empty()
280        {
281            self.workspace_diagnostics
282                .retain(|d| !d.kind.is_source_walk_recorded());
283            self.workspace_diagnostics = merge_workspace_diagnostics(
284                std::mem::take(&mut self.workspace_diagnostics),
285                discovery.source_diagnostics().to_vec(),
286            );
287        }
288        self.discovery = discovery;
289        self.duplication.forget_files();
290        !same_files
291    }
292
293    /// Whether each fingerprint of the cached parse can stand in for the file
294    /// content. No cached parse counts as trustworthy.
295    fn cached_fingerprints_are_trustworthy(&mut self) -> bool {
296        self.parsed_cache
297            .get_mut()
298            .unwrap_or_else(std::sync::PoisonError::into_inner)
299            .as_ref()
300            .is_none_or(|cache| {
301                cache
302                    .fingerprints
303                    .iter()
304                    .all(|fingerprint| fingerprint.is_trustworthy_without_content())
305            })
306    }
307
308    /// Write the modules of incremental parses to the persisted parse cache.
309    ///
310    /// Each module is stored with the fingerprint that the session read before
311    /// it parsed the file. A file that changed after that parse then misses
312    /// the cache instead of serving the older module. Does nothing when no
313    /// incremental parse happened since the last write, or when the cache is
314    /// off.
315    ///
316    /// The session does not write these modules when it is dropped. A caller
317    /// that parses again after files changed, such as a session that lives
318    /// across editor runs, calls this method before it drops the session. A
319    /// session that parses once needs no call: the full parse writes the
320    /// persisted cache itself. The editor server is the only caller now.
321    pub fn flush_parse_cache(&self) {
322        if self.config.no_cache || !self.disk_cache_stale.swap(false, Ordering::SeqCst) {
323            return;
324        }
325        let Ok(cache) = self.parsed_cache.lock() else {
326            return;
327        };
328        let Some(cache) = cache.as_ref() else {
329            return;
330        };
331        let cache_max_size_bytes =
332            crate::project_config::resolve_cache_max_size_bytes(&self.config);
333        let mut store = fallow_extract::cache::CacheStore::load(
334            &self.config.cache_dir,
335            &self.config.root,
336            self.config.cache_config_hash,
337            cache_max_size_bytes,
338        )
339        .ok();
340        let files = self.files();
341        write_parse_cache(
342            &self.config,
343            &mut store,
344            &ParseCacheWrite {
345                modules: &cache.modules,
346                files,
347                needs: parse_needs(&self.config, cache.need_complexity),
348                metadata_hits: &[],
349                fingerprint_of: &|file: &DiscoveredFile| {
350                    cache.fingerprints.get(file.id.0 as usize).map_or_else(
351                        || SourceFingerprint::new(0, 0),
352                        |fingerprint| fingerprint.for_content_read_at(cache.read_started_ns),
353                    )
354                },
355            },
356        );
357    }
358
359    /// Parse the discovered files into the module cache of the session,
360    /// without analysis. A later run of this session then starts from warm
361    /// modules.
362    ///
363    /// # Errors
364    ///
365    /// Returns [`crate::EngineError::cancelled`] when the token of the session
366    /// is set.
367    pub fn prewarm_parsed_modules(&self, need_complexity: bool) -> EngineResult<()> {
368        self.shared_parsed_modules_cancellable(need_complexity, "prewarm")
369            .map(drop)
370    }
371
372    fn clear_styling_cache(&self) {
373        if let Ok(mut cache) = self.styling_cache.lock() {
374            *cache = None;
375        }
376    }
377
378    /// Whether this session's caller has requested cancellation.
379    #[must_use]
380    pub fn is_cancelled(&self) -> bool {
381        self.cancellation
382            .as_ref()
383            .is_some_and(|cancelled| cancelled.load(Ordering::SeqCst))
384    }
385
386    pub(crate) fn ensure_not_cancelled(&self, stage: &str) -> EngineResult<()> {
387        if self.is_cancelled() {
388            return Err(crate::EngineError::cancelled(stage));
389        }
390        Ok(())
391    }
392
393    /// Build a session from a resolved config when the caller already owns
394    /// command-specific config loading. Duplication analyzes the files of
395    /// this config, so the caller resolves it in the production mode of each
396    /// analysis that the session runs.
397    ///
398    /// # Errors
399    ///
400    /// Returns an engine error when root manifest loading fails during
401    /// workspace discovery, matching `ProjectConfig::load`.
402    pub fn from_resolved_config(config: ResolvedConfig) -> EngineResult<Self> {
403        let (workspaces, workspace_diagnostics, workspace_discovery_ms) =
404            crate::project_config::collect_workspace_metadata(&config)?;
405        Ok(Self::from_project_config(ProjectConfig {
406            inputs: fallow_config::ConfigInputs::default(),
407            inputs_before_resolve: fallow_config::ConfigInputsSnapshot::default(),
408            config,
409            path: None,
410            workspaces,
411            workspace_diagnostics,
412            workspace_discovery_ms: Some(workspace_discovery_ms),
413            duplication: DuplicationScope::SameAsSession,
414        }))
415    }
416
417    /// Resolved project root.
418    #[must_use]
419    pub fn root(&self) -> &Path {
420        &self.config.root
421    }
422
423    /// Resolved project config.
424    #[must_use]
425    pub fn config(&self) -> &ResolvedConfig {
426        &self.config
427    }
428
429    /// Config file path when one was loaded.
430    #[must_use]
431    pub fn config_path(&self) -> Option<&Path> {
432        self.config_path.as_deref()
433    }
434
435    /// The plugin files, rule packs and `autoDiscover` directories that
436    /// config resolution read. A session built from a resolved config
437    /// lists none.
438    #[must_use]
439    pub const fn config_inputs(&self) -> &fallow_config::ConfigInputs {
440        &self.config_inputs
441    }
442
443    /// The content of [`Self::config_inputs`] just before config resolution
444    /// read them. A snapshot after the load that differs from this one tells
445    /// that an input changed during the load.
446    #[must_use]
447    pub const fn config_inputs_before_resolve(&self) -> &fallow_config::ConfigInputsSnapshot {
448        &self.config_inputs_before_resolve
449    }
450
451    /// The estimated heap memory of the parsed modules that the session
452    /// keeps between calls, with the estimate of
453    /// [`crate::warm_parse::estimated_retained_bytes`]. Zero before the first
454    /// parse.
455    #[must_use]
456    pub fn retained_bytes_estimate(&self) -> u64 {
457        self.parsed_cache
458            .lock()
459            .ok()
460            .and_then(|cache| {
461                cache
462                    .as_ref()
463                    .map(|cache| crate::warm_parse::estimated_retained_bytes(&cache.fingerprints))
464            })
465            .unwrap_or(0)
466    }
467
468    /// Discovered files for this session.
469    #[must_use]
470    pub fn files(&self) -> &[DiscoveredFile] {
471        self.discovery.files()
472    }
473
474    /// Workspace packages discovered during config/session setup.
475    #[must_use]
476    pub fn workspaces(&self) -> &[WorkspaceInfo] {
477        &self.workspaces
478    }
479
480    /// Source metadata fingerprints for every discovered source file.
481    #[must_use]
482    fn source_fingerprints(&self) -> FxHashMap<PathBuf, SourceFingerprint> {
483        self.discovery
484            .files()
485            .iter()
486            .map(|file| {
487                let fingerprint = std::fs::metadata(&file.path).map_or_else(
488                    |_| SourceFingerprint::new(0, file.size_bytes),
489                    |metadata| SourceFingerprint::from_metadata(&metadata),
490                );
491                (file.path.clone(), fingerprint)
492            })
493            .collect()
494    }
495
496    /// Resolve files changed since a git ref against this session root.
497    ///
498    /// # Errors
499    ///
500    /// Returns an error when the ref is invalid, git is unavailable, or the
501    /// root is not part of a repository.
502    pub(crate) fn changed_files_since(
503        &self,
504        git_ref: &str,
505    ) -> Result<FxHashSet<PathBuf>, crate::changed_files::ChangedFilesError> {
506        crate::changed_files::changed_files(&self.config.root, git_ref)
507    }
508
509    /// The discovery this session walked.
510    pub(crate) const fn discovery(&self) -> &crate::discover::AnalysisDiscovery {
511        &self.discovery
512    }
513
514    /// Workspace and source-discovery diagnostics captured for this session.
515    #[must_use]
516    pub fn workspace_diagnostics(&self) -> &[WorkspaceDiagnostic] {
517        &self.workspace_diagnostics
518    }
519
520    /// Current diagnostics, including the source read failures the parse stage
521    /// discovers and the analysis-stage entries the analyze pass records, both
522    /// of which land in the registry after the session was created.
523    ///
524    /// [`fallow_config::registry_diagnostics_to_fold`] excludes walk-recorded
525    /// entries. This session owns its latest walk, even when another walk on
526    /// the same root writes different skips to the registry (#2366).
527    #[must_use]
528    pub fn current_workspace_diagnostics(&self) -> Vec<WorkspaceDiagnostic> {
529        merge_workspace_diagnostics(
530            self.workspace_diagnostics.clone(),
531            fallow_config::registry_diagnostics_to_fold(&self.config.root),
532        )
533    }
534
535    pub(crate) fn styling_analysis_artifacts(
536        &self,
537    ) -> Arc<crate::health::StylingAnalysisArtifacts> {
538        if let Ok(cache) = self.styling_cache.lock()
539            && let Some(artifacts) = cache.as_ref()
540        {
541            return Arc::clone(artifacts);
542        }
543
544        let modules = self.shared_parsed_modules(false);
545        let artifacts = Arc::new(crate::health::build_styling_analysis_artifacts(
546            self.files(),
547            &modules,
548            self.config(),
549        ));
550        if let Ok(mut cache) = self.styling_cache.lock() {
551            *cache = Some(Arc::clone(&artifacts));
552        }
553        artifacts
554    }
555
556    /// Consume the session and return the resolved config plus discovery data.
557    #[must_use]
558    pub fn into_parts(self) -> AnalysisSessionParts {
559        let workspace_diagnostics = self.current_workspace_diagnostics();
560        AnalysisSessionParts {
561            config: self.config,
562            config_path: self.config_path,
563            files: self.discovery.into_files(),
564            workspaces: self.workspaces,
565            workspace_diagnostics,
566        }
567    }
568
569    /// Parse discovered files without consuming the session.
570    #[must_use]
571    pub fn parsed_parts(&self, need_complexity: bool) -> ParsedAnalysisSessionParts {
572        let SharedParsedModules { modules, metrics } = self.parse_modules(need_complexity, None);
573        self.parsed_parts_from_modules(modules.to_vec(), metrics)
574    }
575
576    /// Parse discovered files while retaining shared immutable module storage.
577    #[must_use]
578    pub(crate) fn shared_parsed_parts(
579        &self,
580        need_complexity: bool,
581    ) -> SharedParsedAnalysisSessionParts {
582        let SharedParsedModules { modules, metrics } = self.parse_modules(need_complexity, None);
583        SharedParsedAnalysisSessionParts {
584            config: self.config.clone(),
585            files: self.discovery.files().to_vec(),
586            modules,
587            workspaces: self.workspaces.clone(),
588            workspace_diagnostics: self.current_workspace_diagnostics(),
589            parse_ms: metrics.parse_ms,
590            parse_cpu_ms: metrics.parse_cpu_ms,
591        }
592    }
593
594    /// Return immutable parsed modules backed by the reusable session cache.
595    ///
596    /// Workspace-owned consumers use this additive path when they only need
597    /// parsed modules and can borrow discovery and config directly from the
598    /// session. Stable owned callers can continue using [`Self::parsed_parts`].
599    #[doc(hidden)]
600    #[must_use]
601    pub(crate) fn shared_parsed_modules(&self, need_complexity: bool) -> Arc<[ModuleInfo]> {
602        self.parse_modules(need_complexity, None).modules
603    }
604
605    /// Parse the discovered files, stopping if the session's caller cancelled.
606    ///
607    /// The token is checked on both sides of the parse loop, so the truncated
608    /// module set a cancelled parse produces is never returned as a smaller
609    /// project. `stage` names the work that would have followed.
610    ///
611    /// # Errors
612    ///
613    /// Returns [`crate::EngineError::cancelled`] when the token is set. A
614    /// session without a token can never return it.
615    pub(crate) fn shared_parsed_modules_cancellable(
616        &self,
617        need_complexity: bool,
618        stage: &str,
619    ) -> EngineResult<Arc<[ModuleInfo]>> {
620        self.ensure_not_cancelled("parsing")?;
621        let modules = self
622            .parse_modules(need_complexity, self.cancellation.as_deref())
623            .modules;
624        self.ensure_not_cancelled(stage)?;
625        Ok(modules)
626    }
627
628    /// Parse discovered files without consuming the session or retaining parser
629    /// output in the session cache.
630    #[must_use]
631    pub fn parsed_parts_uncached(&self, need_complexity: bool) -> ParsedAnalysisSessionParts {
632        let read_started_ns = now_ns();
633        let fingerprints = self
634            .warm_parse
635            .as_ref()
636            .and_then(|_| source_fingerprints_for_files(self.files()));
637        if let Some(warm) = self.warm_parse(
638            need_complexity,
639            fingerprints.as_deref(),
640            read_started_ns,
641            None,
642        ) {
643            return self.parsed_parts_from_modules(warm.modules.to_vec(), warm.metrics);
644        }
645        let ParsedModules {
646            modules, metrics, ..
647        } = parse_files_with_config(&self.config, self.files(), need_complexity, None);
648        self.parsed_parts_from_modules(modules, metrics)
649    }
650
651    fn parsed_parts_from_modules(
652        &self,
653        modules: Vec<ModuleInfo>,
654        metrics: core_backend::ParseMetrics,
655    ) -> ParsedAnalysisSessionParts {
656        ParsedAnalysisSessionParts {
657            config: self.config.clone(),
658            config_path: self.config_path.clone(),
659            files: self.discovery.files().to_vec(),
660            modules,
661            workspaces: self.workspaces.clone(),
662            workspace_diagnostics: self.current_workspace_diagnostics(),
663            parse_ms: metrics.parse_ms,
664            cache_update_ms: metrics.cache_ms,
665            cache_hits: metrics.cache_hits,
666            cache_misses: metrics.cache_misses,
667            parse_cpu_ms: metrics.parse_cpu_ms,
668        }
669    }
670
671    /// Run dead-code analysis for this session.
672    ///
673    /// # Errors
674    ///
675    /// Returns an error if parsing or analysis fails.
676    pub fn analyze_dead_code(&self) -> EngineResult<DeadCodeAnalysis> {
677        self.analyze_dead_code_with_artifacts(false, false)
678            .map(|output| DeadCodeAnalysis {
679                results: output.results,
680            })
681    }
682
683    /// Run dead-code analysis with retained complexity artifacts.
684    ///
685    /// # Errors
686    ///
687    /// Returns an error if parsing or analysis fails.
688    pub fn analyze_dead_code_with_complexity(&self) -> EngineResult<DeadCodeAnalysisOutput> {
689        self.analyze_dead_code_with_artifacts(true, false)
690            .map(|output| DeadCodeAnalysisOutput {
691                results: output.results,
692                modules: output.modules,
693                files: output.files,
694            })
695    }
696
697    /// Run dead-code analysis with retained modules, discovered files and graph.
698    ///
699    /// # Errors
700    ///
701    /// Returns an error if parsing or analysis fails.
702    pub fn analyze_dead_code_with_artifacts(
703        &self,
704        need_complexity: bool,
705        retain_graph: bool,
706    ) -> EngineResult<DeadCodeAnalysisArtifacts> {
707        self.analyze_dead_code_with_shared_artifacts(need_complexity, retain_graph)
708            .map(SharedDeadCodeAnalysisArtifacts::into_owned)
709    }
710
711    /// Run dead-code analysis with shared immutable parser artifacts.
712    ///
713    /// Workspace-owned consumers use this additive path to retain warm parser
714    /// modules without deep-cloning the session cache. External callers can
715    /// continue using [`Self::analyze_dead_code_with_artifacts`].
716    ///
717    /// # Errors
718    ///
719    /// Returns an error if parsing or analysis fails.
720    #[doc(hidden)]
721    pub fn analyze_dead_code_with_shared_artifacts(
722        &self,
723        need_complexity: bool,
724        retain_graph: bool,
725    ) -> EngineResult<SharedDeadCodeAnalysisArtifacts> {
726        self.analyze_dead_code_with_reuse_artifacts(need_complexity, retain_graph, need_complexity)
727    }
728
729    /// Run dead-code analysis while retaining discovered files for downstream
730    /// command stages that reuse discovery but do not need parser modules.
731    ///
732    /// # Errors
733    ///
734    /// Returns an error if parsing or analysis fails.
735    pub fn analyze_dead_code_retaining_files(
736        &self,
737        need_complexity: bool,
738        retain_graph: bool,
739    ) -> EngineResult<DeadCodeAnalysisArtifacts> {
740        self.analyze_dead_code_with_reuse_artifacts(need_complexity, retain_graph, true)
741            .map(SharedDeadCodeAnalysisArtifacts::into_owned)
742    }
743
744    /// Run dead-code analysis from modules already parsed through this session.
745    ///
746    /// This preserves the session's resolved config and discovered file set for
747    /// follow-up analyses that reuse parser output without redoing discovery.
748    ///
749    /// # Errors
750    ///
751    /// Returns an error if graph construction or analysis fails.
752    pub fn analyze_dead_code_with_parsed_modules(
753        &self,
754        modules: &[ModuleInfo],
755    ) -> EngineResult<DeadCodeAnalysisArtifacts> {
756        self.analyze_dead_code_with_shared_modules(Arc::from(modules))
757    }
758
759    /// Run dead-code analysis from shared immutable parser modules.
760    ///
761    /// # Errors
762    ///
763    /// Returns an error if graph construction or analysis fails.
764    #[doc(hidden)]
765    pub(crate) fn analyze_dead_code_with_shared_modules(
766        &self,
767        modules: Arc<[ModuleInfo]>,
768    ) -> EngineResult<DeadCodeAnalysisArtifacts> {
769        run_engine_owned_dead_code_pipeline(EngineDeadCodePipelineInput {
770            config: &self.config,
771            discovery: &self.discovery,
772            modules,
773            metrics: reused_parse_metrics(),
774            collect_usages: true,
775            graph: crate::session_graph::GraphChoice::WithTrace,
776            retain_modules: false,
777            retain_files: false,
778            cancellation: self.cancellation.as_deref(),
779        })
780        .map(SharedDeadCodeAnalysisArtifacts::into_owned)
781    }
782
783    pub(crate) fn analyze_dead_code_with_reuse_artifacts(
784        &self,
785        need_complexity: bool,
786        graph: impl Into<crate::session_graph::GraphChoice>,
787        retain_files: bool,
788    ) -> EngineResult<SharedDeadCodeAnalysisArtifacts> {
789        self.ensure_not_cancelled("parsing")?;
790        let SharedParsedModules { modules, metrics } =
791            self.parse_modules(need_complexity, self.cancellation.as_deref());
792        // The parse loop no-ops the files it has not reached yet, so a token
793        // set during parsing leaves `modules` truncated. It must never reach
794        // the graph as if it were the whole project.
795        self.ensure_not_cancelled("the dead-code pipeline")?;
796        run_engine_owned_dead_code_pipeline(EngineDeadCodePipelineInput {
797            config: &self.config,
798            discovery: &self.discovery,
799            modules,
800            metrics,
801            collect_usages: true,
802            graph: graph.into(),
803            retain_modules: need_complexity,
804            retain_files,
805            cancellation: self.cancellation.as_deref(),
806        })
807    }
808
809    /// Run dead-code analysis and return the session-scoped reuse artifacts.
810    ///
811    /// Callers pass a changed-file set they have already resolved for the
812    /// command. The returned value keeps that set beside parser, graph, and
813    /// source-fingerprint data so downstream runners do not have to rebuild or
814    /// rediscover the same inputs.
815    ///
816    /// # Errors
817    ///
818    /// Returns an error if parsing or analysis fails.
819    pub fn analyze_dead_code_with_session_artifacts(
820        &self,
821        need_complexity: bool,
822        retain_graph: bool,
823        changed_files: Option<FxHashSet<PathBuf>>,
824    ) -> EngineResult<AnalysisSessionArtifacts> {
825        Ok(AnalysisSessionArtifacts {
826            analysis: self.analyze_dead_code_with_artifacts(need_complexity, retain_graph)?,
827            changed_files,
828            source_fingerprints: self.source_fingerprints(),
829        })
830    }
831
832    /// Parse the discovered files, reusing the session's warm module cache.
833    ///
834    /// `cancellation` is threaded through to the per-file parse loop, so a set
835    /// token truncates the returned modules. Only callers that convert a set
836    /// token into an error may pass one.
837    pub(crate) fn parse_modules(
838        &self,
839        need_complexity: bool,
840        cancellation: Option<&AtomicBool>,
841    ) -> SharedParsedModules {
842        let read_started_ns = now_ns();
843        let fingerprints = source_fingerprints_for_files(self.files());
844        if let Some(fingerprints) = fingerprints.as_ref()
845            && let Some(parsed) = self.reparse_changed_modules(
846                need_complexity,
847                fingerprints,
848                read_started_ns,
849                cancellation,
850            )
851        {
852            return parsed;
853        }
854
855        let (modules, metrics, has_complexity, modules_reused, problems) = if let Some(warm) = self
856            .warm_parse(
857                need_complexity,
858                fingerprints.as_deref(),
859                read_started_ns,
860                cancellation,
861            ) {
862            let reused = if warm.reused { warm.modules.len() } else { 0 };
863            (warm.modules, warm.metrics, true, reused, warm.problems)
864        } else {
865            let ParsedModules {
866                modules,
867                metrics,
868                read_failures,
869                parse_degradations,
870            } = parse_files_with_config(&self.config, self.files(), need_complexity, cancellation);
871            let problems = SourceProblems {
872                read_failures,
873                parse_degradations,
874            };
875            (modules.into(), metrics, need_complexity, 0, problems)
876        };
877        self.parse_counts.record(SessionParseCounts {
878            modules_parsed: metrics.cache_misses,
879            disk_cache_hits: metrics.cache_hits,
880            modules_reused,
881        });
882        // A cancelled parse returns a truncated module set. Storing it would
883        // serve that truncation to the next call as a warm cache hit, long
884        // after the cancellation itself is forgotten.
885        if !token_is_set(cancellation)
886            && let Some(fingerprints) = fingerprints
887            && let Ok(mut cache) = self.parsed_cache.lock()
888        {
889            *cache = Some(ParsedModuleCache {
890                need_complexity: has_complexity,
891                fingerprints,
892                read_started_ns,
893                modules: Arc::clone(&modules),
894                read_failures: problems.read_failures,
895                parse_degradations: problems.parse_degradations,
896            });
897            // The full parse wrote the persisted cache for these modules.
898            self.disk_cache_stale.store(false, Ordering::SeqCst);
899            self.clear_styling_cache();
900        }
901        SharedParsedModules { modules, metrics }
902    }
903
904    /// Parse through the store of parsed modules across sessions.
905    ///
906    /// Returns `None` when the session has no store, when caching is off, or
907    /// when a fingerprint cannot stand in for the file content. The caller
908    /// then parses through the persisted cache only.
909    ///
910    /// The parse always computes complexity. The cost is
911    /// about the same, and a later `health` session can then use the modules.
912    /// The persisted cache and the in-session cache already serve modules with
913    /// complexity to callers that need none. One case costs more: a persisted
914    /// cache without complexity, from a CLI `dead-code` run, gives no hits, so
915    /// the first parse through the store parses each file from source.
916    fn warm_parse(
917        &self,
918        need_complexity: bool,
919        fingerprints: Option<&[SourceFingerprint]>,
920        read_started_ns: u64,
921        cancellation: Option<&AtomicBool>,
922    ) -> Option<WarmParsedModules> {
923        let store = self.warm_parse.as_deref()?;
924        if self.config.no_cache {
925            return None;
926        }
927        let key = WarmParseKey {
928            root: &self.config.root,
929            cache_config_hash: self.config.cache_config_hash,
930            files: self.files(),
931            fingerprints: fingerprints?,
932            read_started_ns,
933        };
934        if !key.is_reusable() {
935            return None;
936        }
937        if let Some(parse) = store.get(&key, parse_needs(&self.config, need_complexity)) {
938            // A parse records its read failures and parse degradations for the
939            // project, and the session reads them back as workspace
940            // diagnostics. Record the kept ones again, so the diagnostics of
941            // this run are the same as after a parse.
942            record_source_diagnostics(
943                &self.config,
944                &parse.read_failures,
945                &parse.parse_degradations,
946            );
947            return Some(WarmParsedModules {
948                modules: parse.modules,
949                metrics: reused_parse_metrics(),
950                reused: true,
951                problems: SourceProblems {
952                    read_failures: parse.read_failures.to_vec(),
953                    parse_degradations: parse.parse_degradations.to_vec(),
954                },
955            });
956        }
957
958        let parsed = parse_files_with_config(&self.config, self.files(), true, cancellation);
959        store.record_parse(parsed.metrics.cache_misses, parsed.metrics.cache_hits);
960        let modules: Arc<[ModuleInfo]> = parsed.modules.into();
961        if !token_is_set(cancellation) {
962            store.put(
963                &key,
964                parse_needs(&self.config, true),
965                WarmParse {
966                    modules: Arc::clone(&modules),
967                    read_failures: parsed.read_failures.clone().into(),
968                    parse_degradations: parsed.parse_degradations.clone().into(),
969                },
970            );
971        }
972        Some(WarmParsedModules {
973            modules,
974            metrics: parsed.metrics,
975            reused: false,
976            problems: SourceProblems {
977                read_failures: parsed.read_failures,
978                parse_degradations: parsed.parse_degradations,
979            },
980        })
981    }
982
983    /// The file positions that changed since the kept parse, with the read
984    /// start and the modules of that parse.
985    ///
986    /// The fingerprints are compared under the lock. The unsettled files are
987    /// read after it, so a concurrent caller does not wait on disk work.
988    /// Returns `None` when there is no kept parse, when it lacks the requested
989    /// complexity, or when the file set differs.
990    fn changed_since_kept_parse(
991        &self,
992        need_complexity: bool,
993        fingerprints: &[SourceFingerprint],
994    ) -> Option<(Vec<usize>, u64, Arc<[ModuleInfo]>)> {
995        let unsettled = std::cell::RefCell::new(Vec::new());
996        let guard = self.parsed_cache.lock().ok()?;
997        let cache = guard.as_ref()?;
998        if need_complexity && !cache.need_complexity {
999            return None;
1000        }
1001        let mut changed = changed_file_indices(
1002            &cache.fingerprints,
1003            cache.read_started_ns,
1004            fingerprints,
1005            &|index| {
1006                unsettled.borrow_mut().push(index);
1007                true
1008            },
1009        )?;
1010        let kept_read_started_ns = cache.read_started_ns;
1011        let kept_modules = Arc::clone(&cache.modules);
1012        drop(guard);
1013        changed.extend(unsettled.into_inner().into_iter().filter(|&index| {
1014            !self.files().get(index).is_some_and(|file| {
1015                crate::session_reuse::module_matches_source(&kept_modules, file.id, &file.path)
1016            })
1017        }));
1018        changed.sort_unstable();
1019        Some((changed, kept_read_started_ns, kept_modules))
1020    }
1021
1022    /// Parse only the files whose fingerprint changed since the cached parse,
1023    /// and keep the other cached modules. When no file changed, return the
1024    /// cached modules as they are.
1025    ///
1026    /// Returns `None` when the cache cannot serve the request: no cached
1027    /// parse, a cache without the requested complexity, a different file set,
1028    /// or more changed files than [`MAX_INCREMENTAL_REPARSE_FILES`]. The
1029    /// caller then parses every file through the persisted cache.
1030    fn reparse_changed_modules(
1031        &self,
1032        need_complexity: bool,
1033        fingerprints: &[SourceFingerprint],
1034        read_started_ns: u64,
1035        cancellation: Option<&AtomicBool>,
1036    ) -> Option<SharedParsedModules> {
1037        let (changed, kept_read_started_ns, kept_modules) =
1038            self.changed_since_kept_parse(need_complexity, fingerprints)?;
1039        let mut guard = self.parsed_cache.lock().ok()?;
1040        let cache = guard.as_mut()?;
1041        // A concurrent cache change during the reads falls back to a full
1042        // parse. This is rare and accepted.
1043        if !Arc::ptr_eq(&cache.modules, &kept_modules)
1044            || cache.read_started_ns != kept_read_started_ns
1045        {
1046            return None;
1047        }
1048        // Release the extra reference, so the merge below can update the
1049        // modules in place.
1050        drop(kept_modules);
1051        if changed.is_empty() {
1052            // Each recent file had the kept content, and the content was read
1053            // after `read_started_ns`, so the fingerprints now prove it from
1054            // that time on.
1055            cache.read_started_ns = read_started_ns;
1056            let modules = Arc::clone(&cache.modules);
1057            drop(guard);
1058            self.parse_counts.record(SessionParseCounts {
1059                modules_reused: modules.len(),
1060                ..SessionParseCounts::default()
1061            });
1062            return Some(SharedParsedModules {
1063                modules,
1064                metrics: reused_parse_metrics(),
1065            });
1066        }
1067        if changed.len() > MAX_INCREMENTAL_REPARSE_FILES {
1068            return None;
1069        }
1070        let files: Vec<DiscoveredFile> = changed
1071            .iter()
1072            .filter_map(|&index| self.files().get(index).cloned())
1073            .collect();
1074        let parse_start = Instant::now();
1075        let parsed = crate::source::parse_all_files(
1076            &files,
1077            None,
1078            parse_needs(&self.config, cache.need_complexity),
1079            cancellation,
1080            &self.config.flags.patterns(),
1081            self.config.extraction_mode,
1082        );
1083        // The caller turns a set token into an error. The cache keeps the
1084        // earlier complete modules, because the parse above may be truncated.
1085        if token_is_set(cancellation) {
1086            return Some(SharedParsedModules {
1087                modules: Arc::clone(&cache.modules),
1088                metrics: reused_parse_metrics(),
1089            });
1090        }
1091        let mut fresh = parsed.modules;
1092        for module in &mut fresh {
1093            module.prepare_analysis_facts();
1094        }
1095        let fresh_count = fresh.len();
1096        let reparsed: Vec<_> = files.iter().map(|file| file.id).collect();
1097        merge_reparsed_modules(&mut cache.modules, &reparsed, fresh);
1098        cache.fingerprints = fingerprints.to_vec();
1099        cache.read_started_ns = read_started_ns;
1100        cache
1101            .read_failures
1102            .retain(|failure| !reparsed.contains(&failure.file_id));
1103        cache.read_failures.extend(parsed.read_failures);
1104        cache
1105            .parse_degradations
1106            .retain(|degradation| !reparsed.contains(&degradation.file_id));
1107        cache.parse_degradations.extend(parsed.parse_degradations);
1108        record_source_diagnostics(
1109            &self.config,
1110            &cache.read_failures,
1111            &cache.parse_degradations,
1112        );
1113        self.parse_counts.record(SessionParseCounts {
1114            modules_parsed: parsed.cache_misses,
1115            disk_cache_hits: 0,
1116            modules_reused: cache.modules.len().saturating_sub(fresh_count),
1117        });
1118        let modules = Arc::clone(&cache.modules);
1119        drop(guard);
1120        self.disk_cache_stale.store(true, Ordering::SeqCst);
1121        self.clear_styling_cache();
1122        Some(SharedParsedModules {
1123            modules,
1124            metrics: core_backend::ParseMetrics {
1125                parse_ms: parse_start.elapsed().as_secs_f64() * 1000.0,
1126                cache_ms: 0.0,
1127                cache_hits: 0,
1128                cache_misses: parsed.cache_misses,
1129                parse_cpu_ms: parsed.parse_cpu_ms,
1130                cache_rejection: None,
1131                files_read: parsed.files_read,
1132                source_bytes_read: parsed.source_bytes_read,
1133                parse_cache_bytes_read: 0,
1134                css_masked_bytes: parsed.css_masked_bytes,
1135                parse_cache_load_ms: 0.0,
1136            },
1137        })
1138    }
1139}
1140
1141struct ParsedModules {
1142    modules: Vec<ModuleInfo>,
1143    metrics: core_backend::ParseMetrics,
1144    read_failures: Vec<SourceReadFailure>,
1145    parse_degradations: Vec<SourceParseDegradation>,
1146}
1147
1148pub(crate) struct SharedParsedModules {
1149    pub(crate) modules: Arc<[ModuleInfo]>,
1150    pub(crate) metrics: core_backend::ParseMetrics,
1151}
1152
1153/// Modules from [`AnalysisSession::warm_parse`]. They always have complexity.
1154struct WarmParsedModules {
1155    modules: Arc<[ModuleInfo]>,
1156    metrics: core_backend::ParseMetrics,
1157    /// The modules came from the store without parse work.
1158    reused: bool,
1159    problems: SourceProblems,
1160}
1161
1162/// The files of a parse that did not read or that parsed with errors.
1163struct SourceProblems {
1164    read_failures: Vec<SourceReadFailure>,
1165    parse_degradations: Vec<SourceParseDegradation>,
1166}
1167
1168#[path = "session_duplication.rs"]
1169mod duplication;
1170#[path = "session_parse.rs"]
1171mod parsing;
1172use parsing::{ParseCacheWrite, parse_files_with_config, parse_needs, write_parse_cache};
1173fn token_is_set(cancellation: Option<&AtomicBool>) -> bool {
1174    cancellation.is_some_and(|cancelled| cancelled.load(Ordering::SeqCst))
1175}
1176
1177/// Record the read failures and parse degradations of a parse for the
1178/// project, and return them as workspace diagnostics.
1179fn record_source_diagnostics(
1180    config: &ResolvedConfig,
1181    read_failures: &[SourceReadFailure],
1182    parse_degradations: &[SourceParseDegradation],
1183) -> Vec<WorkspaceDiagnostic> {
1184    let mut diagnostics = fallow_config::record_source_read_failures(&config.root, read_failures);
1185    diagnostics.extend(fallow_config::record_source_parse_degradations(
1186        config,
1187        parse_degradations,
1188    ));
1189    diagnostics
1190}
1191
1192fn reused_parse_metrics() -> core_backend::ParseMetrics {
1193    core_backend::ParseMetrics {
1194        parse_ms: 0.0,
1195        cache_ms: 0.0,
1196        cache_hits: 0,
1197        cache_misses: 0,
1198        parse_cpu_ms: 0.0,
1199        cache_rejection: None,
1200        files_read: 0,
1201        source_bytes_read: 0,
1202        parse_cache_bytes_read: 0,
1203        css_masked_bytes: 0,
1204        parse_cache_load_ms: 0.0,
1205    }
1206}
1207
1208fn source_fingerprints_for_files(files: &[DiscoveredFile]) -> Option<Vec<SourceFingerprint>> {
1209    files
1210        .iter()
1211        .map(|file| {
1212            std::fs::metadata(&file.path)
1213                .ok()
1214                .map(|metadata| SourceFingerprint::from_metadata(&metadata))
1215                .filter(|fingerprint| fingerprint.has_known_mtime())
1216        })
1217        .collect()
1218}
1219
1220struct EngineDeadCodePipelineInput<'a> {
1221    config: &'a ResolvedConfig,
1222    discovery: &'a crate::discover::AnalysisDiscovery,
1223    modules: Arc<[ModuleInfo]>,
1224    metrics: core_backend::ParseMetrics,
1225    collect_usages: bool,
1226    graph: crate::session_graph::GraphChoice,
1227    retain_modules: bool,
1228    retain_files: bool,
1229    cancellation: Option<&'a AtomicBool>,
1230}
1231
1232fn run_engine_owned_dead_code_pipeline(
1233    input: EngineDeadCodePipelineInput<'_>,
1234) -> EngineResult<SharedDeadCodeAnalysisArtifacts> {
1235    let EngineDeadCodePipelineInput {
1236        config,
1237        discovery,
1238        modules,
1239        metrics,
1240        collect_usages,
1241        graph: retention,
1242        retain_modules,
1243        retain_files,
1244        cancellation,
1245    } = input;
1246    let stopped = |stage: &str| -> EngineResult<()> {
1247        if token_is_set(cancellation) {
1248            return Err(crate::EngineError::cancelled(stage));
1249        }
1250        Ok(())
1251    };
1252    stopped("the dead-code prelude")?;
1253    let prelude = core_backend::prepare_dead_code_backend_prelude(config, discovery)?;
1254    let prelude_timings = prelude.timings();
1255    stopped("dead-code entry-point discovery")?;
1256    let entry_points = core_backend::discover_dead_code_entry_points(&prelude);
1257    stopped("import resolution and graph construction")?;
1258    let (resolved, graph, graph_cache_rejection) =
1259        crate::session_graph::resolve_or_build_dead_code_graph(&prelude, &entry_points, &modules);
1260    stopped("the dead-code detectors")?;
1261
1262    let mut detector = core_backend::run_dead_code_detectors(
1263        &prelude,
1264        &graph.graph,
1265        &resolved.project.modules,
1266        &modules,
1267        collect_usages,
1268        &entry_points,
1269    );
1270    detector.results.shared_state = crate::shared_state::inventory(
1271        config,
1272        &modules,
1273        &resolved.project.modules,
1274        graph.graph.as_graph(),
1275    );
1276    if let Some(inventory) = &mut detector.results.shared_state {
1277        inventory.complete &= modules.len() == discovery.files().len()
1278            && crate::shared_state::sources_complete(config, discovery);
1279    }
1280    // Stamp ids on the full set, before any filter removes a finding. The
1281    // tiebreak suffix depends on the other findings with the same identity.
1282    crate::dead_code::stamp_finding_ids(&mut detector.results, &config.root);
1283    // Security ids too, so every surface reads the id this pipeline set.
1284    crate::security::stamp_security_finding_ids(&mut detector.results, &config.root);
1285    crate::dead_code::filter_configured_ignored_findings(&mut detector.results, config);
1286    if config.production {
1287        stopped("the test-side import scan")?;
1288        crate::test_side_imports::attach_test_importers(&mut detector.results, config)?;
1289    }
1290    // The detectors are the longest uninterruptible stage. Without this a
1291    // token set inside them yields a complete report, so the same request
1292    // would be answered with results or with `cancelled` depending only on
1293    // which side of the stage the flip landed.
1294    stopped("assembling the dead-code report")?;
1295    let profile =
1296        core_backend::dead_code_pipeline_profile(core_backend::DeadCodePipelineProfileInput {
1297            retain_timings: retention.traces(),
1298            prelude: &prelude,
1299            prelude_timings,
1300            parse_metrics: metrics,
1301            module_count: modules.len(),
1302            entry_points: &entry_points,
1303            resolved: &resolved,
1304            graph: &graph,
1305            detector: &detector,
1306            file_count: discovery.files().len(),
1307            workspace_count: discovery.workspaces().len(),
1308            graph_cache_rejection,
1309        });
1310    let script_used_packages = prelude.script_used_packages();
1311    let mut trace_provenance =
1312        prelude.trace_provenance(&modules, retention.traces(), &entry_points);
1313    trace_provenance.push_signature_backed_types(
1314        &config.root,
1315        std::mem::take(&mut detector.results.signature_backed_types),
1316    );
1317    prelude.finish();
1318    let file_hashes = crate::session_graph::collect_file_hashes(&modules, discovery.files());
1319
1320    Ok(SharedDeadCodeAnalysisArtifacts {
1321        results: detector.results,
1322        timings: profile.timings,
1323        graph: retention.keeps_graph().then_some(graph.graph),
1324        modules: retain_modules.then_some(modules),
1325        files: retain_files.then(|| discovery.files().to_vec()),
1326        script_used_packages,
1327        trace_provenance,
1328        file_hashes,
1329    })
1330}
1331
1332pub(crate) fn analyze_dead_code_with_parse_result_from_config(
1333    config: &ResolvedConfig,
1334    modules: &[ModuleInfo],
1335) -> EngineResult<DeadCodeAnalysisArtifacts> {
1336    let (workspaces, _diagnostics, workspaces_ms) =
1337        crate::project_config::collect_workspace_metadata(config)?;
1338    let discovery = crate::discover::prepare_analysis_discovery_with_workspaces(
1339        config,
1340        &workspaces,
1341        workspaces_ms,
1342    );
1343    run_engine_owned_dead_code_pipeline(EngineDeadCodePipelineInput {
1344        config,
1345        discovery: &discovery,
1346        modules: Arc::from(modules),
1347        metrics: reused_parse_metrics(),
1348        collect_usages: true,
1349        graph: crate::session_graph::GraphChoice::WithTrace,
1350        retain_modules: false,
1351        retain_files: false,
1352        cancellation: None,
1353    })
1354    .map(SharedDeadCodeAnalysisArtifacts::into_owned)
1355}
1356
1357#[cfg(test)]
1358mod tests {
1359    use std::fmt::Write as _;
1360    use std::time::Duration;
1361
1362    use super::*;
1363    use fallow_types::cache_rejection::CacheRejection;
1364
1365    fn session_with_source(source: &str) -> (tempfile::TempDir, AnalysisSession) {
1366        let project = tempfile::tempdir().expect("project");
1367        let root = project.path();
1368        std::fs::create_dir(root.join("src")).expect("create source directory");
1369        std::fs::write(root.join("src/index.ts"), source).expect("write source");
1370        let session = AnalysisSession::load_default(root);
1371        (project, session)
1372    }
1373
1374    fn class_projection_session(root: &Path) -> AnalysisSession {
1375        AnalysisSession::load_default_with_config(root, |config| {
1376            config.rules.unused_class_members = fallow_config::Severity::Error;
1377        })
1378    }
1379
1380    fn session_class_projection(session: &AnalysisSession) -> Vec<String> {
1381        let analysis = session.analyze_dead_code().expect("class member analysis");
1382        assert!(analysis.results.unresolved_imports.is_empty());
1383        let mut members: Vec<_> = analysis
1384            .results
1385            .unused_class_members
1386            .iter()
1387            .filter(|finding| finding.member.parent_name == "C")
1388            .map(|finding| finding.member.member_name.clone())
1389            .collect();
1390        members.sort();
1391        members
1392    }
1393
1394    #[test]
1395    fn factory_property_proof_refresh_matches_fresh_sessions() {
1396        for (present, absent) in [
1397            (
1398                "import { C } from './classes'; const make = (): C => new C(); export const createUi = () => ({ page: make() });",
1399                "export const createUi = () => ({ page: { used() {} } });",
1400            ),
1401            (
1402                "import { Owner } from './owner'; export const createUi = () => { const owner = new Owner(); return { page: owner.widget }; };",
1403                "export const createUi = () => ({ page: { used() {} } });",
1404            ),
1405        ] {
1406            let project = tempfile::tempdir().expect("session fixture");
1407            let root = project.path();
1408            std::fs::write(
1409                root.join("package.json"),
1410                r#"{"name":"producer-refresh","type":"module","main":"index.ts"}"#,
1411            )
1412            .expect("package");
1413            std::fs::write(
1414                root.join("classes.ts"),
1415                "export class C { control() {} used() {} dead() {} }",
1416            )
1417            .expect("class");
1418            std::fs::write(
1419                root.join("owner.ts"),
1420                "import { C } from './classes'; export class Owner { widget: C = new C(); }",
1421            )
1422            .expect("owner");
1423            std::fs::write(root.join("index.ts"), "import { createUi } from './factory'; const ui = createUi(); ui.page.used(); import { C } from './classes'; new C().control();").expect("consumer");
1424            let path = root.join("factory.ts");
1425            std::fs::write(&path, present).expect("initial producer");
1426            let mut session = class_projection_session(root);
1427            assert_eq!(session_class_projection(&session), ["dead"]);
1428            for (source, expected) in [(absent, vec!["dead", "used"]), (present, vec!["dead"])] {
1429                std::fs::write(&path, source).expect("producer update");
1430                session.refresh_discovery();
1431                assert_eq!(session_class_projection(&session), expected);
1432                assert_eq!(
1433                    session_class_projection(&session),
1434                    session_class_projection(&class_projection_session(root))
1435                );
1436            }
1437        }
1438    }
1439
1440    #[test]
1441    fn callback_property_proof_refresh_matches_fresh_sessions() {
1442        for (present, absent) in [
1443            (
1444                "export function wrap<T>(callback: () => T) { return { value: callback() }; }",
1445                "export function wrap<T>(callback: () => T) { return { value: { used() {} } }; }",
1446            ),
1447            (
1448                "export { computed as wrap } from 'vue';",
1449                "export { computed as wrap } from 'foreign';",
1450            ),
1451        ] {
1452            let project = tempfile::tempdir().expect("callback session fixture");
1453            let root = project.path();
1454            std::fs::write(
1455                root.join("package.json"),
1456                r#"{"name":"callback-refresh","type":"module","main":"index.ts","dependencies":{"vue":"*","foreign":"*"}}"#,
1457            )
1458            .expect("package");
1459            std::fs::write(
1460                root.join("classes.ts"),
1461                "export class C { control() {} used() {} dead() {} }",
1462            )
1463            .expect("class");
1464            std::fs::write(root.join("index.ts"), "import { wrap } from './factory'; import { C } from './classes'; new C().control(); wrap(() => new C()).value.used();").expect("consumer");
1465            let path = root.join("factory.ts");
1466            std::fs::write(&path, present).expect("initial producer");
1467            let mut session = class_projection_session(root);
1468            assert_eq!(session_class_projection(&session), ["dead"]);
1469            for (source, expected) in [(absent, vec!["dead", "used"]), (present, vec!["dead"])] {
1470                std::fs::write(&path, source).expect("producer update");
1471                session.refresh_discovery();
1472                assert_eq!(session_class_projection(&session), expected);
1473                assert_eq!(
1474                    session_class_projection(&session),
1475                    session_class_projection(&class_projection_session(root))
1476                );
1477            }
1478        }
1479    }
1480
1481    #[test]
1482    fn callback_review_proof_refresh_matches_fresh_sessions() {
1483        for (present, absent) in [
1484            (
1485                "let current = new C(); wrap((ignored = 0) => current).value.used();",
1486                "let current = new C(); wrap((ignored = (current = { used() {} })) => current).value.used();",
1487            ),
1488            (
1489                "import { computed } from 'vue'; const getter = () => new C(); const alias = getter; const options = { get: alias, set: value => {} }; computed(options).value.used();",
1490                "import { computed } from 'vue'; const getter = () => new C(); const alias = getter; const options = { get: alias, set: value => {} }; options.get = () => ({ used() {} }); computed(options).value.used();",
1491            ),
1492            (
1493                "let current = new C(); wrap(() => current).value.used();",
1494                "let current = new C(); wrap(() => { current = { used() {} }; return current; }).value.used();",
1495            ),
1496            (
1497                "import { computed } from 'vue'; const options = { get: () => new C(), set: value => {} }; const alias = options; computed(alias).value.used();",
1498                "import { computed } from 'vue'; const options = { get: () => new C(), set: value => {} }; const alias = options; alias.get = () => ({ used() {} }); computed(options).value.used();",
1499            ),
1500        ] {
1501            let project = tempfile::tempdir().expect("callback review session fixture");
1502            let root = project.path();
1503            std::fs::write(root.join("package.json"), r#"{"name":"callback-review-refresh","type":"module","main":"index.ts","dependencies":{"vue":"*"}}"#).expect("package");
1504            std::fs::write(
1505                root.join("classes.ts"),
1506                "export class C { control() {} used() {} dead() {} }",
1507            )
1508            .expect("class");
1509            std::fs::write(
1510                root.join("helper.ts"),
1511                "export function wrap(fn) { return { value: fn() }; }",
1512            )
1513            .expect("helper");
1514            let path = root.join("index.ts");
1515            let source = |body: &str| {
1516                format!(
1517                    "import {{ C }} from './classes'; import {{ wrap }} from './helper'; new C().control(); {body}"
1518                )
1519            };
1520            std::fs::write(&path, source(present)).expect("initial source");
1521            let mut session = class_projection_session(root);
1522            assert_eq!(session_class_projection(&session), ["dead"]);
1523            for (body, expected) in [(absent, vec!["dead", "used"]), (present, vec!["dead"])] {
1524                std::fs::write(&path, source(body)).expect("source update");
1525                session.refresh_discovery();
1526                assert_eq!(session_class_projection(&session), expected);
1527                assert_eq!(
1528                    session_class_projection(&session),
1529                    session_class_projection(&class_projection_session(root))
1530                );
1531            }
1532        }
1533    }
1534
1535    #[test]
1536    fn indexed_source_proof_removal_and_restoration_matches_fresh_sessions() {
1537        for (label, present, absent, access) in [
1538            (
1539                "literal",
1540                "const items = [new C()];",
1541                "const items = [new Other()];",
1542                "items[0].used();",
1543            ),
1544            (
1545                "vue",
1546                "import { computed } from 'vue';const items = computed(() => [new C()]);",
1547                "import { computed } from 'foreign';const items = computed(() => [new C()]);",
1548                "items.value[0].used();",
1549            ),
1550        ] {
1551            let project = tempfile::tempdir().expect("session fixture");
1552            let root = project.path();
1553            std::fs::create_dir(root.join("src")).expect("source directory");
1554            std::fs::write(root.join("package.json"),
1555                r#"{"name":"session-array-proof","type":"module","main":"src/index.ts","dependencies":{"vue":"*","foreign":"*"}}"#)
1556                .expect("package manifest");
1557            std::fs::write(root.join("src/classes.ts"),
1558                "export class C { control() {} used() {} dead() {} } export class Other { used() {} }")
1559                .expect("classes");
1560            for provider in ["vue", "foreign"] {
1561                let directory = root.join("node_modules").join(provider);
1562                std::fs::create_dir_all(&directory).expect("provider directory");
1563                std::fs::write(
1564                    directory.join("package.json"),
1565                    format!(r#"{{"name":"{provider}","type":"module","main":"index.js"}}"#),
1566                )
1567                .expect("provider package");
1568                std::fs::write(
1569                    directory.join("index.js"),
1570                    "export const computed = getter => ({ get value() { return getter(); } });",
1571                )
1572                .expect("provider source");
1573            }
1574            let source = |producer: &str| {
1575                format!(
1576                    "import {{ C, Other }} from './classes';new C().control();\n{producer}\n{access}\n"
1577                )
1578            };
1579            let original = source(present);
1580            let path = root.join("src/index.ts");
1581            std::fs::write(&path, &original).expect("initial source");
1582            let mut retained = class_projection_session(root);
1583            for (phase, content, expected) in [
1584                ("initial", original.as_str(), vec!["dead"]),
1585                ("removed", source(absent).as_str(), vec!["dead", "used"]),
1586                ("restored", original.as_str(), vec!["dead"]),
1587            ] {
1588                std::fs::write(&path, content).expect("update proof source");
1589                retained.refresh_discovery();
1590                let actual = session_class_projection(&retained);
1591                assert_eq!(actual, expected, "{label}: {phase}");
1592                assert_eq!(
1593                    actual,
1594                    session_class_projection(&class_projection_session(root)),
1595                    "{label}: retained and fresh differ after {phase}"
1596                );
1597            }
1598        }
1599    }
1600
1601    /// A cancelled session reports the failure and names the boundary it
1602    /// stopped at, so a caller can tell a stopped run from a broken one.
1603    #[test]
1604    fn a_cancelled_session_returns_a_cancellation_error_not_an_empty_result() {
1605        let project = tempfile::tempdir().expect("project");
1606        let root = project.path();
1607        std::fs::create_dir(root.join("src")).expect("create source directory");
1608        std::fs::write(root.join("src/index.ts"), "export const entry = 1;\n").expect("entry");
1609        std::fs::write(root.join("src/orphan.ts"), "export const orphan = 1;\n").expect("orphan");
1610
1611        let baseline = AnalysisSession::load_default(root)
1612            .analyze_dead_code()
1613            .expect("an uncancelled session analyzes");
1614        assert!(
1615            !baseline.results.unused_files.is_empty(),
1616            "the fixture must have findings, so an empty result would be a plausible wrong answer"
1617        );
1618
1619        let error = AnalysisSession::load_default(root)
1620            .with_cancellation(Arc::new(AtomicBool::new(true)))
1621            .analyze_dead_code()
1622            .expect_err("a cancelled session must not return results");
1623        assert!(error.is_cancelled(), "unexpected error: {error}");
1624        assert!(error.message().contains("cancelled"));
1625    }
1626
1627    /// The engine pipeline is what every CLI command runs, and it reported no
1628    /// graph-cache reason at all: the loader produced one, the boundary threw
1629    /// it away, and the profile hardcoded `None`. A warm run that decoded a
1630    /// multi-megabyte graph and then rebuilt from scratch looked exactly like a
1631    /// first run, so the row that explains it could never print.
1632    #[test]
1633    fn a_refused_graph_cache_names_its_reason_in_the_engine_timings() {
1634        let project = tempfile::tempdir().expect("project");
1635        let root = project.path();
1636        std::fs::create_dir(root.join("src")).expect("create source directory");
1637        std::fs::write(root.join("src/index.ts"), "export const entry = 1;\n").expect("entry");
1638
1639        let cold = AnalysisSession::load_default(root)
1640            .analyze_dead_code_with_artifacts(false, true)
1641            .expect("cold run analyzes");
1642        assert_eq!(
1643            cold.timings
1644                .expect("cold timings retained")
1645                .graph_cache_rejection,
1646            Some(CacheRejection::Absent),
1647            "a first run has no persisted graph to refuse"
1648        );
1649
1650        std::fs::write(
1651            root.join("src/index.ts"),
1652            "export const entry = 1;\nexport const added = 2;\n",
1653        )
1654        .expect("edit the entry");
1655
1656        let warm = AnalysisSession::load_default(root)
1657            .analyze_dead_code_with_artifacts(false, true)
1658            .expect("warm run analyzes");
1659        assert_eq!(
1660            warm.timings
1661                .expect("warm timings retained")
1662                .graph_cache_rejection,
1663            Some(CacheRejection::FingerprintChanged),
1664            "the decoded graph was refused because a file changed, and the run must say so"
1665        );
1666    }
1667
1668    /// A session that is not given a token can never be cancelled, so every
1669    /// existing caller keeps its current behavior.
1670    #[test]
1671    fn a_session_without_a_token_is_never_cancelled() {
1672        let (_project, session) = session_with_source("export const unused = 1;\n");
1673        assert!(!session.is_cancelled());
1674        session
1675            .analyze_dead_code()
1676            .expect("a session without a token analyzes");
1677    }
1678
1679    /// Files per fixture for the parse-loop tests. Large enough that a parse
1680    /// takes long enough to be cancelled part way through, small enough to
1681    /// stay a unit test.
1682    const PARSE_LOOP_FILES: usize = 400;
1683
1684    fn parse_loop_project() -> tempfile::TempDir {
1685        let project = tempfile::tempdir().expect("project");
1686        let src = project.path().join("src");
1687        std::fs::create_dir_all(&src).expect("src dir");
1688        for module in 0..PARSE_LOOP_FILES {
1689            let mut source = String::new();
1690            for symbol in 0..20 {
1691                let _ = writeln!(
1692                    source,
1693                    "export const helper{symbol} = (input: number): number => {{\n  \
1694                     if (input > {symbol}) {{\n    return input * {symbol};\n  }}\n  \
1695                     return input - {symbol};\n}};"
1696                );
1697            }
1698            std::fs::write(src.join(format!("mod{module}.ts")), source).expect("module");
1699        }
1700        project
1701    }
1702
1703    /// A platform without ctime, such as Windows, gives fingerprints that
1704    /// can stand in for the content only after a content check. A kept
1705    /// session must not serve its modules to the next run on such a
1706    /// fingerprint, because a same-size edit with a restored mtime keeps it.
1707    // Unix only: other platforms expose no inode change time, so no
1708    // fingerprint is trustworthy and a refresh always drops the modules.
1709    #[cfg(unix)]
1710    #[test]
1711    fn a_refresh_drops_modules_whose_fingerprints_need_a_content_check() {
1712        let (_project, mut session) = session_with_source("export const kept = 1;\n");
1713        drop(session.parse_modules(false, None));
1714
1715        assert!(!session.refresh_discovery(), "the file set is the same");
1716        assert!(
1717            session.parsed_cache.lock().expect("parse cache").is_some(),
1718            "fingerprints with a known ctime keep the modules for the next run"
1719        );
1720
1721        if let Some(cache) = session
1722            .parsed_cache
1723            .get_mut()
1724            .expect("parse cache")
1725            .as_mut()
1726        {
1727            for fingerprint in &mut cache.fingerprints {
1728                fingerprint.ctime_ns = 0;
1729            }
1730        }
1731        assert!(!session.refresh_discovery(), "the file set is the same");
1732        assert!(
1733            session.parsed_cache.lock().expect("parse cache").is_none(),
1734            "the next run parses through the persisted cache, which checks the content"
1735        );
1736    }
1737
1738    /// A flush writes the kept modules to the persisted cache. A fingerprint
1739    /// that did not settle before the kept parse read the file must lose its
1740    /// ctime there, or the next run takes the metadata fast path on it.
1741    #[cfg(unix)]
1742    #[test]
1743    fn a_flush_stores_an_unsettled_fingerprint_without_its_ctime() {
1744        let (project, mut session) = session_with_source("export const kept = 1;\n");
1745        drop(session.parse_modules(false, None));
1746        let path = project.path().join("src/index.ts");
1747        let stored_ctime = |session: &AnalysisSession| {
1748            let _ = std::fs::remove_dir_all(&session.config.cache_dir);
1749            session.disk_cache_stale.store(true, Ordering::SeqCst);
1750            session.flush_parse_cache();
1751            let store = fallow_extract::cache::CacheStore::load(
1752                &session.config.cache_dir,
1753                &session.config.root,
1754                session.config.cache_config_hash,
1755                crate::project_config::resolve_cache_max_size_bytes(&session.config),
1756            )
1757            .expect("flush writes the parse cache");
1758            store
1759                .get_by_path_only(&path)
1760                .expect("flushed module")
1761                .ctime_ns
1762        };
1763
1764        // Set the read start relative to the file's own ctime, so the test
1765        // does not depend on how much time passed since the write.
1766        let set_read_started = |session: &mut AnalysisSession, offset: u64| {
1767            if let Some(cache) = session
1768                .parsed_cache
1769                .get_mut()
1770                .expect("parse cache")
1771                .as_mut()
1772            {
1773                let ctime = cache.fingerprints[0].ctime_ns;
1774                assert!(ctime > 0, "the platform reports a ctime");
1775                cache.read_started_ns = ctime.saturating_add(offset);
1776            }
1777        };
1778
1779        set_read_started(&mut session, 0);
1780        assert_eq!(
1781            stored_ctime(&session),
1782            0,
1783            "a fingerprint inside the window is not settled"
1784        );
1785
1786        set_read_started(
1787            &mut session,
1788            fallow_types::source_fingerprint::TIMESTAMP_SETTLE_WINDOW_NS,
1789        );
1790        assert!(
1791            stored_ctime(&session) > 0,
1792            "a settled fingerprint keeps its ctime"
1793        );
1794    }
1795
1796    /// A same-length write in the same timestamp tick as the previous write
1797    /// keeps mtime, ctime and size. The kept modules must not stand in for
1798    /// the new content when the fingerprint is that recent.
1799    #[cfg(unix)]
1800    #[test]
1801    fn a_same_tick_rewrite_does_not_reuse_the_kept_module() {
1802        let (project, mut session) = session_with_source("export const alpha = 1;\n");
1803        drop(session.parse_modules(false, None));
1804
1805        let path = project.path().join("src/index.ts");
1806        std::fs::write(&path, "export const bravo = 1;\n").expect("rewrite source");
1807        let same_tick = SourceFingerprint::from_metadata(
1808            &std::fs::metadata(&path).expect("metadata after rewrite"),
1809        );
1810        if let Some(cache) = session
1811            .parsed_cache
1812            .get_mut()
1813            .expect("parse cache")
1814            .as_mut()
1815        {
1816            cache.fingerprints = vec![same_tick];
1817        }
1818
1819        let modules = session.parse_modules(false, None).modules;
1820        let exports: Vec<String> = modules
1821            .iter()
1822            .flat_map(|module| module.exports.iter())
1823            .map(|export| export.name.to_string())
1824            .collect();
1825        assert_eq!(exports, vec!["bravo".to_string()]);
1826    }
1827
1828    /// A session over `root` that never reads or writes the on-disk parse
1829    /// cache, so repeated parses in one test all do the same work.
1830    fn uncached_session(root: &Path) -> AnalysisSession {
1831        let mut project_config = crate::project_config::default_project_config(root);
1832        project_config.config.no_cache = true;
1833        AnalysisSession::from_config(project_config)
1834    }
1835
1836    /// The parse loop is the one place cancellation stops work per item rather
1837    /// than at a stage boundary, so it is the one place the stop can be
1838    /// asserted from what was parsed instead of from how long the call took.
1839    ///
1840    /// A truncated parse is also the most dangerous thing cancellation
1841    /// produces: served from a cache it would read as a project with fewer
1842    /// modules long after the cancellation was forgotten. The first half
1843    /// asserts it is not retained.
1844    #[test]
1845    fn a_cancelled_parse_stops_partway_and_leaves_no_truncated_cache_behind() {
1846        let project = parse_loop_project();
1847        let root = project.path();
1848
1849        // A token set before the call must stop every item. This half has no
1850        // timing, so it proves on any runner that the loop reads the token.
1851        let token = Arc::new(AtomicBool::new(true));
1852        let session = uncached_session(root).with_cancellation(Arc::clone(&token));
1853        let stopped = session.parse_modules(false, Some(&token));
1854        assert!(stopped.modules.is_empty(), "the loop never read the token");
1855        assert!(
1856            session.parsed_cache.lock().expect("parse cache").is_none(),
1857            "a truncated parse must not be retained as this session's warm cache"
1858        );
1859
1860        // Warm the page cache, then time only the parse, as the attempts do.
1861        drop(uncached_session(root).parse_modules(false, None));
1862        let session = uncached_session(root);
1863        let started = Instant::now();
1864        let full_count = session.parse_modules(false, None).modules.len();
1865        let full_parse = started.elapsed();
1866        assert_eq!(
1867            full_count, PARSE_LOOP_FILES,
1868            "the fixture must parse every generated module"
1869        );
1870
1871        // Where the flip lands is a scheduling outcome, and a later parse can
1872        // run faster or slower than the timed one. So a bisection finds the
1873        // delay: a parse that finished shortens it, a parse that stopped at
1874        // once makes it longer, and a parse that stopped part way ends it.
1875        let mut shorter_than = None::<Duration>;
1876        let mut longer_than = Duration::ZERO;
1877        let mut delay = full_parse / 2;
1878        let mut stopped_part_way = false;
1879        for _ in 0..16 {
1880            let token = Arc::new(AtomicBool::new(false));
1881            // Discovery runs in the constructor, so build the session before
1882            // the watchdog starts its delay.
1883            let session = uncached_session(root).with_cancellation(Arc::clone(&token));
1884            let watchdog = {
1885                let token = Arc::clone(&token);
1886                std::thread::spawn(move || {
1887                    std::thread::sleep(delay);
1888                    token.store(true, Ordering::SeqCst);
1889                })
1890            };
1891            let cancelled = session.parse_modules(false, Some(&token));
1892            watchdog.join().expect("watchdog thread");
1893
1894            let parsed = cancelled.modules.len();
1895            if parsed == full_count {
1896                shorter_than = Some(delay);
1897            } else if parsed == 0 {
1898                longer_than = delay;
1899            } else {
1900                stopped_part_way = true;
1901                break;
1902            }
1903            delay = match shorter_than {
1904                Some(upper) => (longer_than + upper) / 2,
1905                None => delay * 2,
1906            };
1907        }
1908        assert!(
1909            stopped_part_way,
1910            "no attempt in 16 stopped the parse part way through"
1911        );
1912
1913        let recovered = uncached_session(root).parse_modules(false, None);
1914        assert_eq!(
1915            recovered.modules.len(),
1916            full_count,
1917            "a later uncancelled parse must still see the whole project"
1918        );
1919    }
1920
1921    #[test]
1922    fn session_retains_workspace_metadata_from_config_load() {
1923        let project = tempfile::tempdir().expect("project");
1924        let root = project.path();
1925        std::fs::write(
1926            root.join("package.json"),
1927            r#"{"name":"root","workspaces":["packages/*"]}"#,
1928        )
1929        .expect("write root package");
1930        std::fs::create_dir_all(root.join("packages/a")).expect("create workspace");
1931        std::fs::write(
1932            root.join("packages/a/package.json"),
1933            r#"{"name":"pkg-a","type":"module"}"#,
1934        )
1935        .expect("write workspace package");
1936
1937        let session = AnalysisSession::load(root, None).expect("session loads");
1938
1939        assert!(
1940            session
1941                .workspaces()
1942                .iter()
1943                .any(|workspace| workspace.name == "pkg-a"),
1944            "session must retain workspace metadata discovered during config load"
1945        );
1946    }
1947
1948    #[test]
1949    fn finding_ignore_filters_results_without_removing_graph_inputs() {
1950        let project = tempfile::tempdir().expect("project");
1951        let root = project.path();
1952        std::fs::create_dir(root.join("src")).expect("create source directory");
1953        std::fs::write(
1954            root.join("package.json"),
1955            r#"{"name":"finding-ignore","devDependencies":{"vitest":"latest"}}"#,
1956        )
1957        .expect("write package manifest");
1958        std::fs::write(
1959            root.join("vitest.config.ts"),
1960            "import './src/feature';\nexport default {};\n",
1961        )
1962        .expect("write vitest config");
1963        std::fs::write(
1964            root.join("src/feature.ts"),
1965            "export const feature = true;\n",
1966        )
1967        .expect("write reachable source");
1968        std::fs::write(root.join("src/hidden.ts"), "export const hidden = true;\n")
1969            .expect("write hidden source");
1970
1971        let unfiltered = AnalysisSession::load(root, None)
1972            .expect("unfiltered session loads")
1973            .analyze_dead_code()
1974            .expect("unfiltered analysis succeeds");
1975        assert!(
1976            unfiltered
1977                .results
1978                .unused_files
1979                .iter()
1980                .any(|finding| finding.file.path.ends_with("src/hidden.ts"))
1981        );
1982
1983        std::fs::write(
1984            root.join(".fallowrc.json"),
1985            r#"{"ignoreFindings":["src/hidden.ts"]}"#,
1986        )
1987        .expect("write fallow config");
1988        let session = AnalysisSession::load(root, None).expect("filtered session loads");
1989        let hidden_path = root.join("src/hidden.ts");
1990        assert!(session.files().iter().any(|file| file.path == hidden_path));
1991
1992        let filtered = session
1993            .analyze_dead_code_with_artifacts(false, true)
1994            .expect("filtered analysis succeeds");
1995        assert!(
1996            filtered
1997                .results
1998                .unused_files
1999                .iter()
2000                .all(|finding| finding.file.path != hidden_path)
2001        );
2002        assert!(
2003            filtered
2004                .graph
2005                .as_ref()
2006                .is_some_and(|graph| graph.module_count() == session.files().len())
2007        );
2008    }
2009
2010    #[test]
2011    fn finding_ignore_normalizes_separators_and_rejects_outside_paths() {
2012        use fallow_types::output_dead_code::UnusedFileFinding;
2013        use fallow_types::results::UnusedFile;
2014
2015        let project = tempfile::tempdir().expect("project");
2016        let config = serde_json::from_str::<fallow_config::FallowConfig>(
2017            r#"{"ignoreFindings":["**/*.ts"]}"#,
2018        )
2019        .expect("config parses")
2020        .resolve(
2021            project.path().to_path_buf(),
2022            fallow_config::OutputFormat::Human,
2023            1,
2024            true,
2025            true,
2026            None,
2027        );
2028        let outside = project
2029            .path()
2030            .parent()
2031            .expect("project has parent")
2032            .join("outside.ts");
2033        let mut results = AnalysisResults {
2034            unused_files: vec![
2035                UnusedFileFinding::with_actions(UnusedFile {
2036                    path: PathBuf::from(r"src\hidden.ts"),
2037                }),
2038                UnusedFileFinding::with_actions(UnusedFile {
2039                    path: outside.clone(),
2040                }),
2041            ],
2042            ..AnalysisResults::default()
2043        };
2044
2045        crate::dead_code::filter_configured_ignored_findings(&mut results, &config);
2046
2047        assert_eq!(results.unused_files.len(), 1);
2048        assert_eq!(results.unused_files[0].file.path, outside);
2049    }
2050
2051    /// Two files under `src/`, with the default config, so the persisted
2052    /// parse cache is on.
2053    #[cfg(unix)]
2054    fn warm_store_project() -> tempfile::TempDir {
2055        let project = tempfile::tempdir().expect("project");
2056        let root = project.path();
2057        std::fs::create_dir(root.join("src")).expect("create source directory");
2058        std::fs::write(root.join("src/index.ts"), "export const entry = 1;\n").expect("entry");
2059        std::fs::write(root.join("src/other.ts"), "export const other = 2;\n").expect("other");
2060        project
2061    }
2062
2063    #[cfg(unix)]
2064    fn warm_session(root: &Path, store: &Arc<WarmParseStore>) -> AnalysisSession {
2065        AnalysisSession::load_default(root).with_warm_parse(Some(Arc::clone(store)))
2066    }
2067
2068    #[cfg(unix)]
2069    fn exported_names(modules: &[ModuleInfo]) -> Vec<String> {
2070        let mut names: Vec<String> = modules
2071            .iter()
2072            .flat_map(|module| module.exports.iter().map(|export| export.name.to_string()))
2073            .collect();
2074        names.sort();
2075        names
2076    }
2077
2078    #[cfg(unix)]
2079    #[test]
2080    fn a_warm_store_serves_a_new_session_without_parse_work() {
2081        let project = warm_store_project();
2082        let store = Arc::new(WarmParseStore::new(
2083            crate::warm_parse::WarmParseLimits::default(),
2084        ));
2085
2086        let first = warm_session(project.path(), &store).parse_modules(false, None);
2087        let second = warm_session(project.path(), &store).parse_modules(false, None);
2088
2089        assert!(Arc::ptr_eq(&first.modules, &second.modules));
2090        assert_eq!(second.metrics.cache_hits + second.metrics.cache_misses, 0);
2091        let counts = store.counts();
2092        assert_eq!(counts.parse_runs, 1);
2093        assert_eq!(counts.modules_parsed, 2);
2094        assert_eq!(counts.modules_reused, 2);
2095    }
2096
2097    #[cfg(unix)]
2098    #[test]
2099    fn a_warm_store_serves_the_health_parse_of_a_new_session() {
2100        let project = warm_store_project();
2101        let store = Arc::new(WarmParseStore::new(
2102            crate::warm_parse::WarmParseLimits::default(),
2103        ));
2104
2105        drop(warm_session(project.path(), &store).parse_modules(false, None));
2106        let health = warm_session(project.path(), &store).parsed_parts_uncached(true);
2107
2108        assert_eq!(health.modules.len(), 2);
2109        assert_eq!(health.cache_hits + health.cache_misses, 0);
2110        assert_eq!(
2111            store.counts().parse_runs,
2112            1,
2113            "the first parse computed complexity"
2114        );
2115    }
2116
2117    #[cfg(unix)]
2118    #[test]
2119    fn an_edit_or_a_new_file_makes_the_next_session_parse_again() {
2120        let project = warm_store_project();
2121        let root = project.path();
2122        let store = Arc::new(WarmParseStore::new(
2123            crate::warm_parse::WarmParseLimits::default(),
2124        ));
2125        drop(warm_session(root, &store).parse_modules(false, None));
2126
2127        std::fs::write(root.join("src/other.ts"), "export const renamed = 22;\n").expect("edit");
2128        let edited = warm_session(root, &store).parse_modules(false, None);
2129        assert_eq!(exported_names(&edited.modules), ["entry", "renamed"]);
2130        assert_eq!(
2131            edited.metrics.cache_misses, 1,
2132            "only the edited file is parsed"
2133        );
2134
2135        std::fs::write(root.join("src/added.ts"), "export const added = 3;\n").expect("add");
2136        let added = warm_session(root, &store).parse_modules(false, None);
2137        assert_eq!(
2138            exported_names(&added.modules),
2139            ["added", "entry", "renamed"]
2140        );
2141
2142        let counts = store.counts();
2143        assert_eq!(counts.parse_runs, 3);
2144        assert_eq!(counts.modules_reused, 0);
2145        assert_eq!(store.len(), 2, "each file list keeps its latest parse only");
2146    }
2147
2148    #[cfg(unix)]
2149    #[test]
2150    fn a_session_without_the_persisted_cache_does_not_use_the_store() {
2151        let project = warm_store_project();
2152        let store = Arc::new(WarmParseStore::new(
2153            crate::warm_parse::WarmParseLimits::default(),
2154        ));
2155
2156        drop(
2157            uncached_session(project.path())
2158                .with_warm_parse(Some(Arc::clone(&store)))
2159                .parse_modules(false, None),
2160        );
2161
2162        assert_eq!(
2163            store.counts(),
2164            crate::warm_parse::WarmParseCounts::default()
2165        );
2166        assert!(store.is_empty());
2167    }
2168
2169    /// A parse records its read failures for the project. A session that
2170    /// takes kept modules must record them again, or a run between the two
2171    /// that cleared them would hide the failure.
2172    #[cfg(unix)]
2173    #[test]
2174    fn a_kept_parse_records_its_read_failures_again() {
2175        let project = warm_store_project();
2176        let root = project.path();
2177        std::fs::write(root.join("src/broken.ts"), [0xff, 0xfe, 0x00]).expect("invalid UTF-8");
2178        let store = Arc::new(WarmParseStore::new(
2179            crate::warm_parse::WarmParseLimits::default(),
2180        ));
2181        let read_failures = |session: &AnalysisSession| {
2182            session
2183                .current_workspace_diagnostics()
2184                .into_iter()
2185                .filter(|diagnostic| {
2186                    matches!(
2187                        diagnostic.kind,
2188                        fallow_types::workspace::WorkspaceDiagnosticKind::SourceReadFailure { .. }
2189                    )
2190                })
2191                .count()
2192        };
2193
2194        let first = warm_session(root, &store);
2195        drop(first.parse_modules(false, None));
2196        assert_eq!(read_failures(&first), 1);
2197
2198        drop(fallow_config::record_source_read_failures(root, &[]));
2199        let second = warm_session(root, &store);
2200        drop(second.parse_modules(false, None));
2201        assert_eq!(store.counts().modules_reused, 2);
2202        assert_eq!(read_failures(&second), 1);
2203    }
2204
2205    #[test]
2206    fn warm_parse_cache_reuses_module_storage() {
2207        let (_project, session) = session_with_source("export function value() { return 1; }\n");
2208        let first = session.parse_modules(true, None);
2209        let second = session.parse_modules(false, None);
2210
2211        assert!(
2212            Arc::ptr_eq(&first.modules, &second.modules),
2213            "warm session queries must share parsed module storage"
2214        );
2215    }
2216
2217    #[test]
2218    fn warm_styling_cache_reuses_artifact_allocation() {
2219        let project = tempfile::tempdir().expect("project");
2220        let root = project.path();
2221        std::fs::write(root.join("styles.css"), ".button { color: red; }\n")
2222            .expect("write stylesheet");
2223        let session = AnalysisSession::load_default(root);
2224
2225        let first = session.styling_analysis_artifacts();
2226        let second = session.styling_analysis_artifacts();
2227
2228        assert!(
2229            Arc::ptr_eq(&first, &second),
2230            "warm styling queries must share the cached artifact allocation"
2231        );
2232    }
2233
2234    #[test]
2235    fn shared_parsed_modules_reuse_public_session_storage() {
2236        let (_project, session) = session_with_source("export const value = 1;\n");
2237        let first = session.shared_parsed_modules(true);
2238        let second = session.shared_parsed_modules(false);
2239
2240        assert!(Arc::ptr_eq(&first, &second));
2241    }
2242
2243    #[test]
2244    fn shared_parsed_parts_reuse_public_session_storage() {
2245        let (_project, session) = session_with_source("export const value = 1;\n");
2246        let cached = session.shared_parsed_modules(true);
2247        let parts = session.shared_parsed_parts(false);
2248
2249        assert!(Arc::ptr_eq(&cached, &parts.modules));
2250    }
2251
2252    #[test]
2253    fn warm_complexity_artifacts_reuse_cached_module_storage() {
2254        let (_project, session) = session_with_source("export function value() { return 1; }\n");
2255        let cached = session.parse_modules(true, None);
2256        let artifacts = session
2257            .analyze_dead_code_with_reuse_artifacts(true, true, false)
2258            .expect("analysis succeeds");
2259        let retained = artifacts.modules.expect("complexity modules retained");
2260
2261        assert!(
2262            Arc::ptr_eq(&cached.modules, &retained),
2263            "warm complexity artifacts must share parsed module storage"
2264        );
2265    }
2266
2267    #[test]
2268    fn shared_and_owned_artifacts_preserve_output_bytes() {
2269        let (_project, session) = session_with_source(
2270            "export const used = 1;\nexport const unused = 2;\nconsole.log(used);\n",
2271        );
2272        let owned = session
2273            .analyze_dead_code_with_artifacts(true, true)
2274            .expect("owned analysis succeeds");
2275        let shared = session
2276            .analyze_dead_code_with_shared_artifacts(true, true)
2277            .expect("shared analysis succeeds");
2278
2279        assert_eq!(
2280            serde_json::to_vec(&owned.results).expect("serialize owned results"),
2281            serde_json::to_vec(&shared.results).expect("serialize shared results")
2282        );
2283        assert_eq!(owned.file_hashes, shared.file_hashes);
2284        assert_eq!(
2285            owned
2286                .modules
2287                .as_deref()
2288                .unwrap_or_default()
2289                .iter()
2290                .map(|module| module.content_hash)
2291                .collect::<Vec<_>>(),
2292            shared
2293                .modules
2294                .as_deref()
2295                .unwrap_or_default()
2296                .iter()
2297                .map(|module| module.content_hash)
2298                .collect::<Vec<_>>()
2299        );
2300    }
2301
2302    #[test]
2303    fn route_loader_whole_use_matches_across_cold_and_warm_sessions() {
2304        let project = tempfile::tempdir().expect("project");
2305        let root = project.path();
2306        std::fs::create_dir_all(root.join("app/routes")).expect("create route directory");
2307        std::fs::write(
2308            root.join("package.json"),
2309            r#"{"name":"route-cache-parity","dependencies":{"react-router":"latest"}}"#,
2310        )
2311        .expect("write package manifest");
2312        std::fs::write(
2313            root.join("app/routes/home.tsx"),
2314            r#"
2315import { useLoaderData } from "react-router";
2316export function loader() { return { opaque: "value" }; }
2317export default function Home() {
2318  const data = useLoaderData<typeof loader>();
2319  const copy = { ...data };
2320  return JSON.stringify(copy);
2321}
2322"#,
2323        )
2324        .expect("write route module");
2325
2326        let cold_session = AnalysisSession::load(root, None).expect("cold session loads");
2327        let cold_parse = cold_session.parsed_parts(false);
2328        assert_eq!(cold_parse.cache_hits, 0, "first parse must be cold");
2329        let cold = cold_session
2330            .analyze_dead_code()
2331            .expect("cold analysis succeeds");
2332
2333        let warm_session = AnalysisSession::load(root, None).expect("warm session loads");
2334        let warm_parse = warm_session.parsed_parts(false);
2335        assert!(
2336            warm_parse.cache_hits > 0,
2337            "second session must use disk cache"
2338        );
2339        let warm = warm_session
2340            .analyze_dead_code()
2341            .expect("warm analysis succeeds");
2342
2343        assert!(
2344            cold.results.unused_load_data_keys.is_empty(),
2345            "cold analysis must abstain for an opaque route-loader use"
2346        );
2347        assert_eq!(
2348            serde_json::to_vec(&cold.results).expect("serialize cold results"),
2349            serde_json::to_vec(&warm.results).expect("serialize warm results"),
2350            "warm route-loader analysis must match cold analysis"
2351        );
2352    }
2353
2354    #[test]
2355    fn replaced_module_coverage_matches_across_cold_and_warm_graph_cache() {
2356        let project = tempfile::tempdir().expect("project");
2357        let root = project.path();
2358        std::fs::create_dir(root.join("src")).expect("create source directory");
2359        std::fs::write(
2360            root.join("package.json"),
2361            r#"{"name":"mock-cache-parity","main":"src/index.ts","devDependencies":{"vitest":"latest"}}"#,
2362        )
2363        .expect("write package manifest");
2364        std::fs::write(
2365            root.join("src/dependency.ts"),
2366            "export function dependency() { return 'real'; }\n",
2367        )
2368        .expect("write dependency");
2369        std::fs::write(
2370            root.join("src/wrapper.ts"),
2371            "import { dependency } from './dependency';\nexport function wrapper() { return dependency(); }\n",
2372        )
2373        .expect("write wrapper");
2374        std::fs::write(
2375            root.join("src/index.ts"),
2376            "export { wrapper } from './wrapper';\n",
2377        )
2378        .expect("write entry point");
2379        std::fs::write(
2380            root.join("src/wrapper.test.ts"),
2381            r#"
2382import { vi } from "vitest";
2383vi.mock("./dependency", () => ({ dependency: () => "mock" }));
2384import { wrapper } from "./wrapper";
2385wrapper();
2386"#,
2387        )
2388        .expect("write test");
2389
2390        let cold_session = AnalysisSession::load(root, None).expect("cold session loads");
2391        let dependency_id = cold_session
2392            .files()
2393            .iter()
2394            .find(|file| file.path == root.join("src/dependency.ts"))
2395            .expect("dependency discovered")
2396            .id;
2397        let cold = cold_session
2398            .analyze_dead_code_with_artifacts(false, true)
2399            .expect("cold analysis succeeds");
2400        let cold_exports = crate::module_graph::module_value_exports(
2401            cold.graph.as_ref().expect("cold graph retained"),
2402        );
2403        assert!(
2404            fallow_graph::cache::GraphCacheStore::load(&cold_session.config().cache_dir).is_ok(),
2405            "cold analysis must persist the graph cache"
2406        );
2407
2408        let warm_session = AnalysisSession::load(root, None).expect("warm session loads");
2409        let warm = warm_session
2410            .analyze_dead_code_with_artifacts(false, true)
2411            .expect("warm analysis succeeds");
2412        let warm_exports = crate::module_graph::module_value_exports(
2413            warm.graph.as_ref().expect("warm graph retained"),
2414        );
2415
2416        let dependency = cold_exports
2417            .iter()
2418            .find(|export| export.file_id == dependency_id && export.name == "dependency")
2419            .expect("dependency export retained");
2420        assert!(!dependency.test_referenced);
2421        assert_eq!(warm_exports, cold_exports);
2422    }
2423
2424    #[test]
2425    fn session_parse_surfaces_removed_source_with_sparse_file_ids() {
2426        let project = tempfile::tempdir().expect("project");
2427        let root = project.path();
2428        std::fs::create_dir(root.join("src")).expect("create source directory");
2429        std::fs::write(root.join("package.json"), r#"{"name":"read-failure"}"#)
2430            .expect("write package manifest");
2431        for name in ["a.ts", "b.ts", "c.ts"] {
2432            std::fs::write(
2433                root.join("src").join(name),
2434                format!("export const {} = 1;\n", name.replace('.', "_")),
2435            )
2436            .expect("write source");
2437        }
2438        let session = AnalysisSession::load(root, None).expect("session loads");
2439        let removed_path = root.join("src/b.ts");
2440        let removed_id = session
2441            .files()
2442            .iter()
2443            .find(|file| file.path == removed_path)
2444            .expect("removed source discovered")
2445            .id;
2446        std::fs::remove_file(&removed_path).expect("remove source after discovery");
2447
2448        let parts = session.parsed_parts(false);
2449
2450        assert!(
2451            parts
2452                .modules
2453                .iter()
2454                .all(|module| module.file_id != removed_id),
2455            "unreadable file must not receive a placeholder module"
2456        );
2457        let diagnostic = parts
2458            .workspace_diagnostics
2459            .iter()
2460            .find(|diagnostic| diagnostic.kind.id() == "source-read-failure")
2461            .expect("parsed session parts carry source read failure");
2462        assert_eq!(diagnostic.path, removed_path);
2463        assert!(
2464            session
2465                .current_workspace_diagnostics()
2466                .iter()
2467                .any(|diagnostic| {
2468                    diagnostic.kind.id() == "source-read-failure" && diagnostic.path == removed_path
2469                }),
2470            "session output carries parse-time source diagnostics"
2471        );
2472    }
2473
2474    const MALFORMED_PNPM_WORKSPACE_YAML: &str =
2475        "catalog:\n  react: ^18.2.0\n{this is\nnot: valid: yaml: at: all\n";
2476    const VALID_PNPM_WORKSPACE_YAML: &str = "catalog:\n  react: ^18.2.0\n";
2477
2478    fn has_diagnostic_kind(diagnostics: &[WorkspaceDiagnostic], id: &str) -> bool {
2479        diagnostics
2480            .iter()
2481            .any(|diagnostic| diagnostic.kind.id() == id)
2482    }
2483
2484    fn write_single_source_project(root: &Path, manifest: &str) {
2485        std::fs::create_dir(root.join("src")).expect("create source directory");
2486        std::fs::write(root.join("package.json"), manifest).expect("write package manifest");
2487        std::fs::write(root.join("src/index.ts"), "export const value = 1;\n")
2488            .expect("write source");
2489    }
2490
2491    /// Issue #2366: engine sessions (the MCP and LSP path) never re-stash the
2492    /// registry, so a session created after an earlier analysis in the same
2493    /// process must not keep that analysis's analysis-stage diagnostic once
2494    /// the cause is fixed: the analyze pass refreshes the entry and the
2495    /// session snapshot must not pin it.
2496    #[test]
2497    fn later_session_drops_stale_analysis_stage_diagnostic_after_cause_is_fixed() {
2498        let project = tempfile::tempdir().expect("project");
2499        let root = project.path();
2500        write_single_source_project(
2501            root,
2502            r#"{"name":"issue-2366-engine-session","private":true}"#,
2503        );
2504        std::fs::write(
2505            root.join("pnpm-workspace.yaml"),
2506            MALFORMED_PNPM_WORKSPACE_YAML,
2507        )
2508        .expect("write malformed workspace yaml");
2509
2510        let broken = AnalysisSession::load(root, None).expect("session loads");
2511        broken
2512            .analyze_dead_code()
2513            .expect("analysis on the malformed yaml succeeds");
2514        assert!(
2515            has_diagnostic_kind(
2516                &broken.current_workspace_diagnostics(),
2517                "malformed-pnpm-workspace-yaml"
2518            ),
2519            "the first session surfaces the malformed yaml: {:?}",
2520            broken.current_workspace_diagnostics()
2521        );
2522
2523        std::fs::write(root.join("pnpm-workspace.yaml"), VALID_PNPM_WORKSPACE_YAML)
2524            .expect("fix workspace yaml");
2525
2526        let fixed = AnalysisSession::load(root, None).expect("session loads");
2527        fixed
2528            .analyze_dead_code()
2529            .expect("analysis on the fixed yaml succeeds");
2530        let current = fixed.current_workspace_diagnostics();
2531        assert!(
2532            !has_diagnostic_kind(&current, "malformed-pnpm-workspace-yaml"),
2533            "a later session must not keep the stale analysis-stage entry (#2366): {current:?}"
2534        );
2535    }
2536
2537    /// Watch-mode rerun shape (issue #2366): the CLI reloads config, which
2538    /// re-stashes the workspace-discovery set, and builds a fresh session from
2539    /// the resolved config before re-analyzing. Once a text `bun.lock` exists
2540    /// the rerun must drop the bun.lockb skip diagnostic. Regression pin: the
2541    /// old stash wiped analysis-stage entries instead of preserving them, so
2542    /// this passes before and after the fix.
2543    #[test]
2544    fn watch_style_rerun_drops_bun_lockb_skip_once_text_lockfile_exists() {
2545        let project = tempfile::tempdir().expect("project");
2546        let root = project.path();
2547        write_single_source_project(
2548            root,
2549            r#"{"name":"issue-2366-watch-rerun","private":true,"overrides":{"ws":"^8.21.0"}}"#,
2550        );
2551        std::fs::write(root.join("bun.lockb"), b"placeholder binary lockfile")
2552            .expect("write bun.lockb placeholder");
2553        let config = fallow_config::FallowConfig::default().resolve(
2554            root.to_path_buf(),
2555            fallow_config::OutputFormat::Json,
2556            1,
2557            true,
2558            true,
2559            None,
2560        );
2561        let reload_config = || {
2562            let (_, diagnostics) =
2563                fallow_config::discover_workspaces_with_diagnostics(root, &config.ignore_patterns)
2564                    .expect("workspace discovery succeeds");
2565            fallow_config::stash_workspace_diagnostics(root, diagnostics);
2566        };
2567
2568        reload_config();
2569        let first =
2570            AnalysisSession::from_resolved_config(config.clone()).expect("first session loads");
2571        first
2572            .analyze_dead_code()
2573            .expect("analysis with bun.lockb only succeeds");
2574        assert!(
2575            has_diagnostic_kind(
2576                &first.current_workspace_diagnostics(),
2577                "bun-lockb-override-resolution-skipped"
2578            ),
2579            "the first run surfaces the bun.lockb skip: {:?}",
2580            first.current_workspace_diagnostics()
2581        );
2582
2583        std::fs::write(
2584            root.join("bun.lock"),
2585            r#"{"lockfileVersion":1,"workspaces":{"":{"name":"issue-2366-watch-rerun"}},"packages":{"ws":["ws@8.21.3","",{},"sha512-20"]}}"#,
2586        )
2587        .expect("write text bun.lock");
2588
2589        reload_config();
2590        let rerun =
2591            AnalysisSession::from_resolved_config(config.clone()).expect("rerun session loads");
2592        rerun
2593            .analyze_dead_code()
2594            .expect("analysis with the text bun.lock succeeds");
2595        let current = rerun.current_workspace_diagnostics();
2596        assert!(
2597            !has_diagnostic_kind(&current, "bun-lockb-override-resolution-skipped"),
2598            "the rerun drops the skip once a text bun.lock exists (#2366): {current:?}"
2599        );
2600    }
2601
2602    /// Issue #2366: `current_workspace_diagnostics` reads the registry live so
2603    /// the parse-stage and analyze-stage entries that land after the session
2604    /// was created still reach the envelope, but it must not import another
2605    /// walk's skips along with them.
2606    ///
2607    /// Combined mode runs the dead-code and duplication walks on the same root
2608    /// under `rayon::join` whenever a per-analysis `production` split stops
2609    /// them from sharing a file list, and each walk replaces the registry's
2610    /// source-discovery set. A session that read that set back would answer
2611    /// "whichever walk wrote last", which decides where the other walk's skip
2612    /// lands in the combined root's union and made the array come out in a
2613    /// different ORDER between runs of the same command.
2614    #[test]
2615    fn session_keeps_its_own_walk_skips_and_ignores_another_walks_registry_write() {
2616        let project = tempfile::tempdir().expect("project");
2617        let root = project.path();
2618        write_single_source_project(
2619            root,
2620            r#"{"name":"issue-2366-parallel-walks","private":true}"#,
2621        );
2622        std::fs::write(root.join("src/huge.ts"), "// filler\n".repeat(400))
2623            .expect("write oversized source");
2624        let mut config = fallow_config::FallowConfig::default().resolve(
2625            root.to_path_buf(),
2626            fallow_config::OutputFormat::Json,
2627            1,
2628            true,
2629            true,
2630            None,
2631        );
2632        config.max_file_size_bytes = Some(1024);
2633
2634        let session = AnalysisSession::from_resolved_config(config).expect("session loads");
2635
2636        // The state a concurrent walk leaves behind: its own skip in this
2637        // root's registry entry. It writes that through the registry's
2638        // replace-in-one-operation call, which an architecture guard reserves
2639        // for the walk itself, so the append is the stand-in here.
2640        fallow_config::append_workspace_diagnostics(
2641            root,
2642            vec![WorkspaceDiagnostic::new(
2643                root,
2644                root.join("src/other-walk-only.ts"),
2645                fallow_types::workspace::WorkspaceDiagnosticKind::SkippedLargeFile {
2646                    size_bytes: 4096,
2647                },
2648            )],
2649        );
2650
2651        let current = session.current_workspace_diagnostics();
2652        let skipped: Vec<&Path> = current
2653            .iter()
2654            .filter(|diagnostic| diagnostic.kind.id() == "skipped-large-file")
2655            .map(|diagnostic| diagnostic.path.as_path())
2656            .collect();
2657        assert_eq!(
2658            skipped.len(),
2659            1,
2660            "the session reports its own walk's skips only: {skipped:?}"
2661        );
2662        assert!(
2663            skipped[0].ends_with("src/huge.ts"),
2664            "the surviving skip is this walk's own: {skipped:?}"
2665        );
2666    }
2667
2668    /// Issue #2366: a config reload that happens AFTER the analyze pass, with
2669    /// no further pass to re-record, must not wipe the analysis-stage entry
2670    /// from the process registry. This is the long-lived-server shape: an MCP
2671    /// or LSP process analyzes once, a later request reloads config for a
2672    /// different analysis family, and a session built after that reload still
2673    /// reads the registry live. Pins the analysis-stage preserve in
2674    /// `stash_workspace_diagnostics`; without it this session reports nothing.
2675    #[test]
2676    fn config_reload_after_the_analyze_pass_keeps_the_bun_lockb_skip_readable() {
2677        let project = tempfile::tempdir().expect("project");
2678        let root = project.path();
2679        write_single_source_project(
2680            root,
2681            r#"{"name":"issue-2366-reload-preserve","private":true,"overrides":{"ws":"^8.21.0"}}"#,
2682        );
2683        std::fs::write(root.join("bun.lockb"), b"placeholder binary lockfile")
2684            .expect("write bun.lockb placeholder");
2685        let config = fallow_config::FallowConfig::default().resolve(
2686            root.to_path_buf(),
2687            fallow_config::OutputFormat::Json,
2688            1,
2689            true,
2690            true,
2691            None,
2692        );
2693        let reload_config = || {
2694            let (_, diagnostics) =
2695                fallow_config::discover_workspaces_with_diagnostics(root, &config.ignore_patterns)
2696                    .expect("workspace discovery succeeds");
2697            fallow_config::stash_workspace_diagnostics(root, diagnostics);
2698        };
2699
2700        reload_config();
2701        let analyzing =
2702            AnalysisSession::from_resolved_config(config.clone()).expect("session loads");
2703        analyzing
2704            .analyze_dead_code()
2705            .expect("analysis with bun.lockb only succeeds");
2706
2707        // A later request reloads config for another analysis family and never
2708        // runs a second dead-code pass.
2709        reload_config();
2710
2711        let later = AnalysisSession::from_resolved_config(config.clone()).expect("session loads");
2712        let current = later.current_workspace_diagnostics();
2713        assert!(
2714            has_diagnostic_kind(&current, "bun-lockb-override-resolution-skipped"),
2715            "the reload must preserve the analysis-stage entry the pass recorded (#2366): \
2716             {current:?}"
2717        );
2718    }
2719}
2720
2721#[cfg(any(test, feature = "testing"))]
2722#[path = "session_direct_load.rs"]
2723mod direct_load;
2724
2725#[cfg(all(test, unix, not(miri)))]
2726#[path = "session_shared_state_tests.rs"]
2727mod shared_state_tests;
2728
2729#[cfg(test)]
2730#[path = "session_shared_state_load_tests.rs"]
2731mod shared_state_load_tests;
2732
2733#[cfg(all(test, unix, not(miri)))]
2734#[path = "session_call_facts_tests.rs"]
2735mod call_facts_tests;
2736
2737#[cfg(test)]
2738#[path = "session_duplication_tests.rs"]
2739mod duplication_tests;