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