Skip to main content

fallow_engine/
session.rs

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