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