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