Skip to main content

fallow_engine/
session.rs

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