Skip to main content

fallow_engine/
session.rs

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