1use 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#[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 preloaded_workspaces: bool,
52 parse_counts: ParseCountCells,
53 disk_cache_stale: AtomicBool,
56 duplication: duplication::DuplicationFiles,
57}
58
59#[derive(Debug)]
60struct ParsedModuleCache {
61 need_complexity: bool,
62 fingerprints: Vec<SourceFingerprint>,
63 read_started_ns: u64,
68 modules: Arc<[ModuleInfo]>,
69 read_failures: Vec<SourceReadFailure>,
72 parse_degradations: Vec<SourceParseDegradation>,
74}
75
76#[derive(Debug)]
78pub struct AnalysisSessionParts {
79 pub config: ResolvedConfig,
81 pub config_path: Option<PathBuf>,
83 pub files: Vec<DiscoveredFile>,
85 pub workspaces: Vec<WorkspaceInfo>,
87 pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
89}
90
91#[derive(Debug)]
93pub struct ParsedAnalysisSessionParts {
94 pub config: ResolvedConfig,
96 pub config_path: Option<PathBuf>,
98 pub files: Vec<DiscoveredFile>,
100 pub modules: Vec<ModuleInfo>,
102 pub workspaces: Vec<WorkspaceInfo>,
104 pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
106 pub parse_ms: f64,
108 pub cache_update_ms: f64,
110 pub cache_hits: usize,
112 pub cache_misses: usize,
114 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#[derive(Debug)]
131pub struct AnalysisSessionArtifacts {
132 pub analysis: DeadCodeAnalysisArtifacts,
134 pub changed_files: Option<FxHashSet<PathBuf>>,
136 pub source_fingerprints: FxHashMap<PathBuf, SourceFingerprint>,
138}
139
140impl AnalysisSession {
141 #[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 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 #[must_use]
209 pub fn with_cancellation(mut self, cancellation: Arc<AtomicBool>) -> Self {
210 self.cancellation = Some(cancellation);
211 self
212 }
213
214 #[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 pub fn set_cancellation(&mut self, cancellation: Arc<AtomicBool>) {
228 self.cancellation = Some(cancellation);
229 }
230
231 #[must_use]
233 pub fn parse_counts(&self) -> SessionParseCounts {
234 self.parse_counts.snapshot()
235 }
236
237 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 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 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 needs: parse_needs(&self.config, cache.need_complexity),
348 metadata_hits: &[],
349 fingerprint_of: &|file: &DiscoveredFile| {
350 cache.fingerprints.get(file.id.0 as usize).map_or_else(
351 || SourceFingerprint::new(0, 0),
352 |fingerprint| fingerprint.for_content_read_at(cache.read_started_ns),
353 )
354 },
355 },
356 );
357 }
358
359 pub fn prewarm_parsed_modules(&self, need_complexity: bool) -> EngineResult<()> {
368 self.shared_parsed_modules_cancellable(need_complexity, "prewarm")
369 .map(drop)
370 }
371
372 fn clear_styling_cache(&self) {
373 if let Ok(mut cache) = self.styling_cache.lock() {
374 *cache = None;
375 }
376 }
377
378 #[must_use]
380 pub fn is_cancelled(&self) -> bool {
381 self.cancellation
382 .as_ref()
383 .is_some_and(|cancelled| cancelled.load(Ordering::SeqCst))
384 }
385
386 pub(crate) fn ensure_not_cancelled(&self, stage: &str) -> EngineResult<()> {
387 if self.is_cancelled() {
388 return Err(crate::EngineError::cancelled(stage));
389 }
390 Ok(())
391 }
392
393 pub fn from_resolved_config(config: ResolvedConfig) -> EngineResult<Self> {
403 let (workspaces, workspace_diagnostics, workspace_discovery_ms) =
404 crate::project_config::collect_workspace_metadata(&config)?;
405 Ok(Self::from_project_config(ProjectConfig {
406 inputs: fallow_config::ConfigInputs::default(),
407 inputs_before_resolve: fallow_config::ConfigInputsSnapshot::default(),
408 config,
409 path: None,
410 workspaces,
411 workspace_diagnostics,
412 workspace_discovery_ms: Some(workspace_discovery_ms),
413 duplication: DuplicationScope::SameAsSession,
414 }))
415 }
416
417 #[must_use]
419 pub fn root(&self) -> &Path {
420 &self.config.root
421 }
422
423 #[must_use]
425 pub fn config(&self) -> &ResolvedConfig {
426 &self.config
427 }
428
429 #[must_use]
431 pub fn config_path(&self) -> Option<&Path> {
432 self.config_path.as_deref()
433 }
434
435 #[must_use]
439 pub const fn config_inputs(&self) -> &fallow_config::ConfigInputs {
440 &self.config_inputs
441 }
442
443 #[must_use]
447 pub const fn config_inputs_before_resolve(&self) -> &fallow_config::ConfigInputsSnapshot {
448 &self.config_inputs_before_resolve
449 }
450
451 #[must_use]
456 pub fn retained_bytes_estimate(&self) -> u64 {
457 self.parsed_cache
458 .lock()
459 .ok()
460 .and_then(|cache| {
461 cache
462 .as_ref()
463 .map(|cache| crate::warm_parse::estimated_retained_bytes(&cache.fingerprints))
464 })
465 .unwrap_or(0)
466 }
467
468 #[must_use]
470 pub fn files(&self) -> &[DiscoveredFile] {
471 self.discovery.files()
472 }
473
474 #[must_use]
476 pub fn workspaces(&self) -> &[WorkspaceInfo] {
477 &self.workspaces
478 }
479
480 #[must_use]
482 fn source_fingerprints(&self) -> FxHashMap<PathBuf, SourceFingerprint> {
483 self.discovery
484 .files()
485 .iter()
486 .map(|file| {
487 let fingerprint = std::fs::metadata(&file.path).map_or_else(
488 |_| SourceFingerprint::new(0, file.size_bytes),
489 |metadata| SourceFingerprint::from_metadata(&metadata),
490 );
491 (file.path.clone(), fingerprint)
492 })
493 .collect()
494 }
495
496 pub(crate) fn changed_files_since(
503 &self,
504 git_ref: &str,
505 ) -> Result<FxHashSet<PathBuf>, crate::changed_files::ChangedFilesError> {
506 crate::changed_files::changed_files(&self.config.root, git_ref)
507 }
508
509 pub(crate) const fn discovery(&self) -> &crate::discover::AnalysisDiscovery {
511 &self.discovery
512 }
513
514 #[must_use]
516 pub fn workspace_diagnostics(&self) -> &[WorkspaceDiagnostic] {
517 &self.workspace_diagnostics
518 }
519
520 #[must_use]
528 pub fn current_workspace_diagnostics(&self) -> Vec<WorkspaceDiagnostic> {
529 merge_workspace_diagnostics(
530 self.workspace_diagnostics.clone(),
531 fallow_config::registry_diagnostics_to_fold(&self.config.root),
532 )
533 }
534
535 pub(crate) fn styling_analysis_artifacts(
536 &self,
537 ) -> Arc<crate::health::StylingAnalysisArtifacts> {
538 if let Ok(cache) = self.styling_cache.lock()
539 && let Some(artifacts) = cache.as_ref()
540 {
541 return Arc::clone(artifacts);
542 }
543
544 let modules = self.shared_parsed_modules(false);
545 let artifacts = Arc::new(crate::health::build_styling_analysis_artifacts(
546 self.files(),
547 &modules,
548 self.config(),
549 ));
550 if let Ok(mut cache) = self.styling_cache.lock() {
551 *cache = Some(Arc::clone(&artifacts));
552 }
553 artifacts
554 }
555
556 #[must_use]
558 pub fn into_parts(self) -> AnalysisSessionParts {
559 let workspace_diagnostics = self.current_workspace_diagnostics();
560 AnalysisSessionParts {
561 config: self.config,
562 config_path: self.config_path,
563 files: self.discovery.into_files(),
564 workspaces: self.workspaces,
565 workspace_diagnostics,
566 }
567 }
568
569 #[must_use]
571 pub fn parsed_parts(&self, need_complexity: bool) -> ParsedAnalysisSessionParts {
572 let SharedParsedModules { modules, metrics } = self.parse_modules(need_complexity, None);
573 self.parsed_parts_from_modules(modules.to_vec(), metrics)
574 }
575
576 #[must_use]
578 pub(crate) fn shared_parsed_parts(
579 &self,
580 need_complexity: bool,
581 ) -> SharedParsedAnalysisSessionParts {
582 let SharedParsedModules { modules, metrics } = self.parse_modules(need_complexity, None);
583 SharedParsedAnalysisSessionParts {
584 config: self.config.clone(),
585 files: self.discovery.files().to_vec(),
586 modules,
587 workspaces: self.workspaces.clone(),
588 workspace_diagnostics: self.current_workspace_diagnostics(),
589 parse_ms: metrics.parse_ms,
590 parse_cpu_ms: metrics.parse_cpu_ms,
591 }
592 }
593
594 #[doc(hidden)]
600 #[must_use]
601 pub(crate) fn shared_parsed_modules(&self, need_complexity: bool) -> Arc<[ModuleInfo]> {
602 self.parse_modules(need_complexity, None).modules
603 }
604
605 pub(crate) fn shared_parsed_modules_cancellable(
616 &self,
617 need_complexity: bool,
618 stage: &str,
619 ) -> EngineResult<Arc<[ModuleInfo]>> {
620 self.ensure_not_cancelled("parsing")?;
621 let modules = self
622 .parse_modules(need_complexity, self.cancellation.as_deref())
623 .modules;
624 self.ensure_not_cancelled(stage)?;
625 Ok(modules)
626 }
627
628 #[must_use]
631 pub fn parsed_parts_uncached(&self, need_complexity: bool) -> ParsedAnalysisSessionParts {
632 let read_started_ns = now_ns();
633 let fingerprints = self
634 .warm_parse
635 .as_ref()
636 .and_then(|_| source_fingerprints_for_files(self.files()));
637 if let Some(warm) = self.warm_parse(
638 need_complexity,
639 fingerprints.as_deref(),
640 read_started_ns,
641 None,
642 ) {
643 return self.parsed_parts_from_modules(warm.modules.to_vec(), warm.metrics);
644 }
645 let ParsedModules {
646 modules, metrics, ..
647 } = parse_files_with_config(&self.config, self.files(), need_complexity, None);
648 self.parsed_parts_from_modules(modules, metrics)
649 }
650
651 fn parsed_parts_from_modules(
652 &self,
653 modules: Vec<ModuleInfo>,
654 metrics: core_backend::ParseMetrics,
655 ) -> ParsedAnalysisSessionParts {
656 ParsedAnalysisSessionParts {
657 config: self.config.clone(),
658 config_path: self.config_path.clone(),
659 files: self.discovery.files().to_vec(),
660 modules,
661 workspaces: self.workspaces.clone(),
662 workspace_diagnostics: self.current_workspace_diagnostics(),
663 parse_ms: metrics.parse_ms,
664 cache_update_ms: metrics.cache_ms,
665 cache_hits: metrics.cache_hits,
666 cache_misses: metrics.cache_misses,
667 parse_cpu_ms: metrics.parse_cpu_ms,
668 }
669 }
670
671 pub fn analyze_dead_code(&self) -> EngineResult<DeadCodeAnalysis> {
677 self.analyze_dead_code_with_artifacts(false, false)
678 .map(|output| DeadCodeAnalysis {
679 results: output.results,
680 })
681 }
682
683 pub fn analyze_dead_code_with_complexity(&self) -> EngineResult<DeadCodeAnalysisOutput> {
689 self.analyze_dead_code_with_artifacts(true, false)
690 .map(|output| DeadCodeAnalysisOutput {
691 results: output.results,
692 modules: output.modules,
693 files: output.files,
694 })
695 }
696
697 pub fn analyze_dead_code_with_artifacts(
703 &self,
704 need_complexity: bool,
705 retain_graph: bool,
706 ) -> EngineResult<DeadCodeAnalysisArtifacts> {
707 self.analyze_dead_code_with_shared_artifacts(need_complexity, retain_graph)
708 .map(SharedDeadCodeAnalysisArtifacts::into_owned)
709 }
710
711 #[doc(hidden)]
721 pub fn analyze_dead_code_with_shared_artifacts(
722 &self,
723 need_complexity: bool,
724 retain_graph: bool,
725 ) -> EngineResult<SharedDeadCodeAnalysisArtifacts> {
726 self.analyze_dead_code_with_reuse_artifacts(need_complexity, retain_graph, need_complexity)
727 }
728
729 pub fn analyze_dead_code_retaining_files(
736 &self,
737 need_complexity: bool,
738 retain_graph: bool,
739 ) -> EngineResult<DeadCodeAnalysisArtifacts> {
740 self.analyze_dead_code_with_reuse_artifacts(need_complexity, retain_graph, true)
741 .map(SharedDeadCodeAnalysisArtifacts::into_owned)
742 }
743
744 pub fn analyze_dead_code_with_parsed_modules(
753 &self,
754 modules: &[ModuleInfo],
755 ) -> EngineResult<DeadCodeAnalysisArtifacts> {
756 self.analyze_dead_code_with_shared_modules(Arc::from(modules))
757 }
758
759 #[doc(hidden)]
765 pub(crate) fn analyze_dead_code_with_shared_modules(
766 &self,
767 modules: Arc<[ModuleInfo]>,
768 ) -> EngineResult<DeadCodeAnalysisArtifacts> {
769 run_engine_owned_dead_code_pipeline(EngineDeadCodePipelineInput {
770 config: &self.config,
771 discovery: &self.discovery,
772 modules,
773 metrics: reused_parse_metrics(),
774 collect_usages: true,
775 graph: crate::session_graph::GraphChoice::WithTrace,
776 retain_modules: false,
777 retain_files: false,
778 cancellation: self.cancellation.as_deref(),
779 })
780 .map(SharedDeadCodeAnalysisArtifacts::into_owned)
781 }
782
783 pub(crate) fn analyze_dead_code_with_reuse_artifacts(
784 &self,
785 need_complexity: bool,
786 graph: impl Into<crate::session_graph::GraphChoice>,
787 retain_files: bool,
788 ) -> EngineResult<SharedDeadCodeAnalysisArtifacts> {
789 self.ensure_not_cancelled("parsing")?;
790 let SharedParsedModules { modules, metrics } =
791 self.parse_modules(need_complexity, self.cancellation.as_deref());
792 self.ensure_not_cancelled("the dead-code pipeline")?;
796 run_engine_owned_dead_code_pipeline(EngineDeadCodePipelineInput {
797 config: &self.config,
798 discovery: &self.discovery,
799 modules,
800 metrics,
801 collect_usages: true,
802 graph: graph.into(),
803 retain_modules: need_complexity,
804 retain_files,
805 cancellation: self.cancellation.as_deref(),
806 })
807 }
808
809 pub fn analyze_dead_code_with_session_artifacts(
820 &self,
821 need_complexity: bool,
822 retain_graph: bool,
823 changed_files: Option<FxHashSet<PathBuf>>,
824 ) -> EngineResult<AnalysisSessionArtifacts> {
825 Ok(AnalysisSessionArtifacts {
826 analysis: self.analyze_dead_code_with_artifacts(need_complexity, retain_graph)?,
827 changed_files,
828 source_fingerprints: self.source_fingerprints(),
829 })
830 }
831
832 pub(crate) fn parse_modules(
838 &self,
839 need_complexity: bool,
840 cancellation: Option<&AtomicBool>,
841 ) -> SharedParsedModules {
842 let read_started_ns = now_ns();
843 let fingerprints = source_fingerprints_for_files(self.files());
844 if let Some(fingerprints) = fingerprints.as_ref()
845 && let Some(parsed) = self.reparse_changed_modules(
846 need_complexity,
847 fingerprints,
848 read_started_ns,
849 cancellation,
850 )
851 {
852 return parsed;
853 }
854
855 let (modules, metrics, has_complexity, modules_reused, problems) = if let Some(warm) = self
856 .warm_parse(
857 need_complexity,
858 fingerprints.as_deref(),
859 read_started_ns,
860 cancellation,
861 ) {
862 let reused = if warm.reused { warm.modules.len() } else { 0 };
863 (warm.modules, warm.metrics, true, reused, warm.problems)
864 } else {
865 let ParsedModules {
866 modules,
867 metrics,
868 read_failures,
869 parse_degradations,
870 } = parse_files_with_config(&self.config, self.files(), need_complexity, cancellation);
871 let problems = SourceProblems {
872 read_failures,
873 parse_degradations,
874 };
875 (modules.into(), metrics, need_complexity, 0, problems)
876 };
877 self.parse_counts.record(SessionParseCounts {
878 modules_parsed: metrics.cache_misses,
879 disk_cache_hits: metrics.cache_hits,
880 modules_reused,
881 });
882 if !token_is_set(cancellation)
886 && let Some(fingerprints) = fingerprints
887 && let Ok(mut cache) = self.parsed_cache.lock()
888 {
889 *cache = Some(ParsedModuleCache {
890 need_complexity: has_complexity,
891 fingerprints,
892 read_started_ns,
893 modules: Arc::clone(&modules),
894 read_failures: problems.read_failures,
895 parse_degradations: problems.parse_degradations,
896 });
897 self.disk_cache_stale.store(false, Ordering::SeqCst);
899 self.clear_styling_cache();
900 }
901 SharedParsedModules { modules, metrics }
902 }
903
904 fn warm_parse(
917 &self,
918 need_complexity: bool,
919 fingerprints: Option<&[SourceFingerprint]>,
920 read_started_ns: u64,
921 cancellation: Option<&AtomicBool>,
922 ) -> Option<WarmParsedModules> {
923 let store = self.warm_parse.as_deref()?;
924 if self.config.no_cache {
925 return None;
926 }
927 let key = WarmParseKey {
928 root: &self.config.root,
929 cache_config_hash: self.config.cache_config_hash,
930 files: self.files(),
931 fingerprints: fingerprints?,
932 read_started_ns,
933 };
934 if !key.is_reusable() {
935 return None;
936 }
937 if let Some(parse) = store.get(&key, parse_needs(&self.config, need_complexity)) {
938 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 parse_needs(&self.config, true),
965 WarmParse {
966 modules: Arc::clone(&modules),
967 read_failures: parsed.read_failures.clone().into(),
968 parse_degradations: parsed.parse_degradations.clone().into(),
969 },
970 );
971 }
972 Some(WarmParsedModules {
973 modules,
974 metrics: parsed.metrics,
975 reused: false,
976 problems: SourceProblems {
977 read_failures: parsed.read_failures,
978 parse_degradations: parsed.parse_degradations,
979 },
980 })
981 }
982
983 fn changed_since_kept_parse(
991 &self,
992 need_complexity: bool,
993 fingerprints: &[SourceFingerprint],
994 ) -> Option<(Vec<usize>, u64, Arc<[ModuleInfo]>)> {
995 let unsettled = std::cell::RefCell::new(Vec::new());
996 let guard = self.parsed_cache.lock().ok()?;
997 let cache = guard.as_ref()?;
998 if need_complexity && !cache.need_complexity {
999 return None;
1000 }
1001 let mut changed = changed_file_indices(
1002 &cache.fingerprints,
1003 cache.read_started_ns,
1004 fingerprints,
1005 &|index| {
1006 unsettled.borrow_mut().push(index);
1007 true
1008 },
1009 )?;
1010 let kept_read_started_ns = cache.read_started_ns;
1011 let kept_modules = Arc::clone(&cache.modules);
1012 drop(guard);
1013 changed.extend(unsettled.into_inner().into_iter().filter(|&index| {
1014 !self.files().get(index).is_some_and(|file| {
1015 crate::session_reuse::module_matches_source(&kept_modules, file.id, &file.path)
1016 })
1017 }));
1018 changed.sort_unstable();
1019 Some((changed, kept_read_started_ns, kept_modules))
1020 }
1021
1022 fn reparse_changed_modules(
1031 &self,
1032 need_complexity: bool,
1033 fingerprints: &[SourceFingerprint],
1034 read_started_ns: u64,
1035 cancellation: Option<&AtomicBool>,
1036 ) -> Option<SharedParsedModules> {
1037 let (changed, kept_read_started_ns, kept_modules) =
1038 self.changed_since_kept_parse(need_complexity, fingerprints)?;
1039 let mut guard = self.parsed_cache.lock().ok()?;
1040 let cache = guard.as_mut()?;
1041 if !Arc::ptr_eq(&cache.modules, &kept_modules)
1044 || cache.read_started_ns != kept_read_started_ns
1045 {
1046 return None;
1047 }
1048 drop(kept_modules);
1051 if changed.is_empty() {
1052 cache.read_started_ns = read_started_ns;
1056 let modules = Arc::clone(&cache.modules);
1057 drop(guard);
1058 self.parse_counts.record(SessionParseCounts {
1059 modules_reused: modules.len(),
1060 ..SessionParseCounts::default()
1061 });
1062 return Some(SharedParsedModules {
1063 modules,
1064 metrics: reused_parse_metrics(),
1065 });
1066 }
1067 if changed.len() > MAX_INCREMENTAL_REPARSE_FILES {
1068 return None;
1069 }
1070 let files: Vec<DiscoveredFile> = changed
1071 .iter()
1072 .filter_map(|&index| self.files().get(index).cloned())
1073 .collect();
1074 let parse_start = Instant::now();
1075 let parsed = crate::source::parse_all_files(
1076 &files,
1077 None,
1078 parse_needs(&self.config, cache.need_complexity),
1079 cancellation,
1080 &self.config.flags.patterns(),
1081 self.config.extraction_mode,
1082 );
1083 if token_is_set(cancellation) {
1086 return Some(SharedParsedModules {
1087 modules: Arc::clone(&cache.modules),
1088 metrics: reused_parse_metrics(),
1089 });
1090 }
1091 let mut fresh = parsed.modules;
1092 for module in &mut fresh {
1093 module.prepare_analysis_facts();
1094 }
1095 let fresh_count = fresh.len();
1096 let reparsed: Vec<_> = files.iter().map(|file| file.id).collect();
1097 merge_reparsed_modules(&mut cache.modules, &reparsed, fresh);
1098 cache.fingerprints = fingerprints.to_vec();
1099 cache.read_started_ns = read_started_ns;
1100 cache
1101 .read_failures
1102 .retain(|failure| !reparsed.contains(&failure.file_id));
1103 cache.read_failures.extend(parsed.read_failures);
1104 cache
1105 .parse_degradations
1106 .retain(|degradation| !reparsed.contains(°radation.file_id));
1107 cache.parse_degradations.extend(parsed.parse_degradations);
1108 record_source_diagnostics(
1109 &self.config,
1110 &cache.read_failures,
1111 &cache.parse_degradations,
1112 );
1113 self.parse_counts.record(SessionParseCounts {
1114 modules_parsed: parsed.cache_misses,
1115 disk_cache_hits: 0,
1116 modules_reused: cache.modules.len().saturating_sub(fresh_count),
1117 });
1118 let modules = Arc::clone(&cache.modules);
1119 drop(guard);
1120 self.disk_cache_stale.store(true, Ordering::SeqCst);
1121 self.clear_styling_cache();
1122 Some(SharedParsedModules {
1123 modules,
1124 metrics: core_backend::ParseMetrics {
1125 parse_ms: parse_start.elapsed().as_secs_f64() * 1000.0,
1126 cache_ms: 0.0,
1127 cache_hits: 0,
1128 cache_misses: parsed.cache_misses,
1129 parse_cpu_ms: parsed.parse_cpu_ms,
1130 cache_rejection: None,
1131 files_read: parsed.files_read,
1132 source_bytes_read: parsed.source_bytes_read,
1133 parse_cache_bytes_read: 0,
1134 css_masked_bytes: parsed.css_masked_bytes,
1135 parse_cache_load_ms: 0.0,
1136 },
1137 })
1138 }
1139}
1140
1141struct ParsedModules {
1142 modules: Vec<ModuleInfo>,
1143 metrics: core_backend::ParseMetrics,
1144 read_failures: Vec<SourceReadFailure>,
1145 parse_degradations: Vec<SourceParseDegradation>,
1146}
1147
1148pub(crate) struct SharedParsedModules {
1149 pub(crate) modules: Arc<[ModuleInfo]>,
1150 pub(crate) metrics: core_backend::ParseMetrics,
1151}
1152
1153struct WarmParsedModules {
1155 modules: Arc<[ModuleInfo]>,
1156 metrics: core_backend::ParseMetrics,
1157 reused: bool,
1159 problems: SourceProblems,
1160}
1161
1162struct SourceProblems {
1164 read_failures: Vec<SourceReadFailure>,
1165 parse_degradations: Vec<SourceParseDegradation>,
1166}
1167
1168#[path = "session_duplication.rs"]
1169mod duplication;
1170#[path = "session_parse.rs"]
1171mod parsing;
1172use parsing::{ParseCacheWrite, parse_files_with_config, parse_needs, write_parse_cache};
1173fn token_is_set(cancellation: Option<&AtomicBool>) -> bool {
1174 cancellation.is_some_and(|cancelled| cancelled.load(Ordering::SeqCst))
1175}
1176
1177fn record_source_diagnostics(
1180 config: &ResolvedConfig,
1181 read_failures: &[SourceReadFailure],
1182 parse_degradations: &[SourceParseDegradation],
1183) -> Vec<WorkspaceDiagnostic> {
1184 let mut diagnostics = fallow_config::record_source_read_failures(&config.root, read_failures);
1185 diagnostics.extend(fallow_config::record_source_parse_degradations(
1186 config,
1187 parse_degradations,
1188 ));
1189 diagnostics
1190}
1191
1192fn reused_parse_metrics() -> core_backend::ParseMetrics {
1193 core_backend::ParseMetrics {
1194 parse_ms: 0.0,
1195 cache_ms: 0.0,
1196 cache_hits: 0,
1197 cache_misses: 0,
1198 parse_cpu_ms: 0.0,
1199 cache_rejection: None,
1200 files_read: 0,
1201 source_bytes_read: 0,
1202 parse_cache_bytes_read: 0,
1203 css_masked_bytes: 0,
1204 parse_cache_load_ms: 0.0,
1205 }
1206}
1207
1208fn source_fingerprints_for_files(files: &[DiscoveredFile]) -> Option<Vec<SourceFingerprint>> {
1209 files
1210 .iter()
1211 .map(|file| {
1212 std::fs::metadata(&file.path)
1213 .ok()
1214 .map(|metadata| SourceFingerprint::from_metadata(&metadata))
1215 .filter(|fingerprint| fingerprint.has_known_mtime())
1216 })
1217 .collect()
1218}
1219
1220struct EngineDeadCodePipelineInput<'a> {
1221 config: &'a ResolvedConfig,
1222 discovery: &'a crate::discover::AnalysisDiscovery,
1223 modules: Arc<[ModuleInfo]>,
1224 metrics: core_backend::ParseMetrics,
1225 collect_usages: bool,
1226 graph: crate::session_graph::GraphChoice,
1227 retain_modules: bool,
1228 retain_files: bool,
1229 cancellation: Option<&'a AtomicBool>,
1230}
1231
1232fn run_engine_owned_dead_code_pipeline(
1233 input: EngineDeadCodePipelineInput<'_>,
1234) -> EngineResult<SharedDeadCodeAnalysisArtifacts> {
1235 let EngineDeadCodePipelineInput {
1236 config,
1237 discovery,
1238 modules,
1239 metrics,
1240 collect_usages,
1241 graph: retention,
1242 retain_modules,
1243 retain_files,
1244 cancellation,
1245 } = input;
1246 let stopped = |stage: &str| -> EngineResult<()> {
1247 if token_is_set(cancellation) {
1248 return Err(crate::EngineError::cancelled(stage));
1249 }
1250 Ok(())
1251 };
1252 stopped("the dead-code prelude")?;
1253 let prelude = core_backend::prepare_dead_code_backend_prelude(config, discovery)?;
1254 let prelude_timings = prelude.timings();
1255 stopped("dead-code entry-point discovery")?;
1256 let entry_points = core_backend::discover_dead_code_entry_points(&prelude);
1257 stopped("import resolution and graph construction")?;
1258 let (resolved, graph, graph_cache_rejection) =
1259 crate::session_graph::resolve_or_build_dead_code_graph(&prelude, &entry_points, &modules);
1260 stopped("the dead-code detectors")?;
1261
1262 let mut detector = core_backend::run_dead_code_detectors(
1263 &prelude,
1264 &graph.graph,
1265 &resolved.project.modules,
1266 &modules,
1267 collect_usages,
1268 &entry_points,
1269 );
1270 detector.results.shared_state = crate::shared_state::inventory(
1271 config,
1272 &modules,
1273 &resolved.project.modules,
1274 graph.graph.as_graph(),
1275 );
1276 if let Some(inventory) = &mut detector.results.shared_state {
1277 inventory.complete &= modules.len() == discovery.files().len()
1278 && crate::shared_state::sources_complete(config, discovery);
1279 }
1280 crate::dead_code::stamp_finding_ids(&mut detector.results, &config.root);
1283 crate::security::stamp_security_finding_ids(&mut detector.results, &config.root);
1285 crate::dead_code::filter_configured_ignored_findings(&mut detector.results, config);
1286 if config.production {
1287 stopped("the test-side import scan")?;
1288 crate::test_side_imports::attach_test_importers(&mut detector.results, config)?;
1289 }
1290 stopped("assembling the dead-code report")?;
1295 let profile =
1296 core_backend::dead_code_pipeline_profile(core_backend::DeadCodePipelineProfileInput {
1297 retain_timings: retention.traces(),
1298 prelude: &prelude,
1299 prelude_timings,
1300 parse_metrics: metrics,
1301 module_count: modules.len(),
1302 entry_points: &entry_points,
1303 resolved: &resolved,
1304 graph: &graph,
1305 detector: &detector,
1306 file_count: discovery.files().len(),
1307 workspace_count: discovery.workspaces().len(),
1308 graph_cache_rejection,
1309 });
1310 let script_used_packages = prelude.script_used_packages();
1311 let mut trace_provenance =
1312 prelude.trace_provenance(&modules, retention.traces(), &entry_points);
1313 trace_provenance.push_signature_backed_types(
1314 &config.root,
1315 std::mem::take(&mut detector.results.signature_backed_types),
1316 );
1317 prelude.finish();
1318 let file_hashes = crate::session_graph::collect_file_hashes(&modules, discovery.files());
1319
1320 Ok(SharedDeadCodeAnalysisArtifacts {
1321 results: detector.results,
1322 timings: profile.timings,
1323 graph: retention.keeps_graph().then_some(graph.graph),
1324 modules: retain_modules.then_some(modules),
1325 files: retain_files.then(|| discovery.files().to_vec()),
1326 script_used_packages,
1327 trace_provenance,
1328 file_hashes,
1329 })
1330}
1331
1332pub(crate) fn analyze_dead_code_with_parse_result_from_config(
1333 config: &ResolvedConfig,
1334 modules: &[ModuleInfo],
1335) -> EngineResult<DeadCodeAnalysisArtifacts> {
1336 let (workspaces, _diagnostics, workspaces_ms) =
1337 crate::project_config::collect_workspace_metadata(config)?;
1338 let discovery = crate::discover::prepare_analysis_discovery_with_workspaces(
1339 config,
1340 &workspaces,
1341 workspaces_ms,
1342 );
1343 run_engine_owned_dead_code_pipeline(EngineDeadCodePipelineInput {
1344 config,
1345 discovery: &discovery,
1346 modules: Arc::from(modules),
1347 metrics: reused_parse_metrics(),
1348 collect_usages: true,
1349 graph: crate::session_graph::GraphChoice::WithTrace,
1350 retain_modules: false,
1351 retain_files: false,
1352 cancellation: None,
1353 })
1354 .map(SharedDeadCodeAnalysisArtifacts::into_owned)
1355}
1356
1357#[cfg(test)]
1358mod tests {
1359 use std::fmt::Write as _;
1360 use std::time::Duration;
1361
1362 use super::*;
1363 use fallow_types::cache_rejection::CacheRejection;
1364
1365 fn session_with_source(source: &str) -> (tempfile::TempDir, AnalysisSession) {
1366 let project = tempfile::tempdir().expect("project");
1367 let root = project.path();
1368 std::fs::create_dir(root.join("src")).expect("create source directory");
1369 std::fs::write(root.join("src/index.ts"), source).expect("write source");
1370 let session = AnalysisSession::load_default(root);
1371 (project, session)
1372 }
1373
1374 fn class_projection_session(root: &Path) -> AnalysisSession {
1375 AnalysisSession::load_default_with_config(root, |config| {
1376 config.rules.unused_class_members = fallow_config::Severity::Error;
1377 })
1378 }
1379
1380 fn session_class_projection(session: &AnalysisSession) -> Vec<String> {
1381 let analysis = session.analyze_dead_code().expect("class member analysis");
1382 assert!(analysis.results.unresolved_imports.is_empty());
1383 let mut members: Vec<_> = analysis
1384 .results
1385 .unused_class_members
1386 .iter()
1387 .filter(|finding| finding.member.parent_name == "C")
1388 .map(|finding| finding.member.member_name.clone())
1389 .collect();
1390 members.sort();
1391 members
1392 }
1393
1394 #[test]
1395 fn factory_property_proof_refresh_matches_fresh_sessions() {
1396 for (present, absent) in [
1397 (
1398 "import { C } from './classes'; const make = (): C => new C(); export const createUi = () => ({ page: make() });",
1399 "export const createUi = () => ({ page: { used() {} } });",
1400 ),
1401 (
1402 "import { Owner } from './owner'; export const createUi = () => { const owner = new Owner(); return { page: owner.widget }; };",
1403 "export const createUi = () => ({ page: { used() {} } });",
1404 ),
1405 ] {
1406 let project = tempfile::tempdir().expect("session fixture");
1407 let root = project.path();
1408 std::fs::write(
1409 root.join("package.json"),
1410 r#"{"name":"producer-refresh","type":"module","main":"index.ts"}"#,
1411 )
1412 .expect("package");
1413 std::fs::write(
1414 root.join("classes.ts"),
1415 "export class C { control() {} used() {} dead() {} }",
1416 )
1417 .expect("class");
1418 std::fs::write(
1419 root.join("owner.ts"),
1420 "import { C } from './classes'; export class Owner { widget: C = new C(); }",
1421 )
1422 .expect("owner");
1423 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");
1424 let path = root.join("factory.ts");
1425 std::fs::write(&path, present).expect("initial producer");
1426 let mut session = class_projection_session(root);
1427 assert_eq!(session_class_projection(&session), ["dead"]);
1428 for (source, expected) in [(absent, vec!["dead", "used"]), (present, vec!["dead"])] {
1429 std::fs::write(&path, source).expect("producer update");
1430 session.refresh_discovery();
1431 assert_eq!(session_class_projection(&session), expected);
1432 assert_eq!(
1433 session_class_projection(&session),
1434 session_class_projection(&class_projection_session(root))
1435 );
1436 }
1437 }
1438 }
1439
1440 #[test]
1441 fn callback_property_proof_refresh_matches_fresh_sessions() {
1442 for (present, absent) in [
1443 (
1444 "export function wrap<T>(callback: () => T) { return { value: callback() }; }",
1445 "export function wrap<T>(callback: () => T) { return { value: { used() {} } }; }",
1446 ),
1447 (
1448 "export { computed as wrap } from 'vue';",
1449 "export { computed as wrap } from 'foreign';",
1450 ),
1451 ] {
1452 let project = tempfile::tempdir().expect("callback session fixture");
1453 let root = project.path();
1454 std::fs::write(
1455 root.join("package.json"),
1456 r#"{"name":"callback-refresh","type":"module","main":"index.ts","dependencies":{"vue":"*","foreign":"*"}}"#,
1457 )
1458 .expect("package");
1459 std::fs::write(
1460 root.join("classes.ts"),
1461 "export class C { control() {} used() {} dead() {} }",
1462 )
1463 .expect("class");
1464 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");
1465 let path = root.join("factory.ts");
1466 std::fs::write(&path, present).expect("initial producer");
1467 let mut session = class_projection_session(root);
1468 assert_eq!(session_class_projection(&session), ["dead"]);
1469 for (source, expected) in [(absent, vec!["dead", "used"]), (present, vec!["dead"])] {
1470 std::fs::write(&path, source).expect("producer update");
1471 session.refresh_discovery();
1472 assert_eq!(session_class_projection(&session), expected);
1473 assert_eq!(
1474 session_class_projection(&session),
1475 session_class_projection(&class_projection_session(root))
1476 );
1477 }
1478 }
1479 }
1480
1481 #[test]
1482 fn callback_review_proof_refresh_matches_fresh_sessions() {
1483 for (present, absent) in [
1484 (
1485 "let current = new C(); wrap((ignored = 0) => current).value.used();",
1486 "let current = new C(); wrap((ignored = (current = { used() {} })) => current).value.used();",
1487 ),
1488 (
1489 "import { computed } from 'vue'; const getter = () => new C(); const alias = getter; const options = { get: alias, set: value => {} }; computed(options).value.used();",
1490 "import { computed } from 'vue'; const getter = () => new C(); const alias = getter; const options = { get: alias, set: value => {} }; options.get = () => ({ used() {} }); computed(options).value.used();",
1491 ),
1492 (
1493 "let current = new C(); wrap(() => current).value.used();",
1494 "let current = new C(); wrap(() => { current = { used() {} }; return current; }).value.used();",
1495 ),
1496 (
1497 "import { computed } from 'vue'; const options = { get: () => new C(), set: value => {} }; const alias = options; computed(alias).value.used();",
1498 "import { computed } from 'vue'; const options = { get: () => new C(), set: value => {} }; const alias = options; alias.get = () => ({ used() {} }); computed(options).value.used();",
1499 ),
1500 ] {
1501 let project = tempfile::tempdir().expect("callback review session fixture");
1502 let root = project.path();
1503 std::fs::write(root.join("package.json"), r#"{"name":"callback-review-refresh","type":"module","main":"index.ts","dependencies":{"vue":"*"}}"#).expect("package");
1504 std::fs::write(
1505 root.join("classes.ts"),
1506 "export class C { control() {} used() {} dead() {} }",
1507 )
1508 .expect("class");
1509 std::fs::write(
1510 root.join("helper.ts"),
1511 "export function wrap(fn) { return { value: fn() }; }",
1512 )
1513 .expect("helper");
1514 let path = root.join("index.ts");
1515 let source = |body: &str| {
1516 format!(
1517 "import {{ C }} from './classes'; import {{ wrap }} from './helper'; new C().control(); {body}"
1518 )
1519 };
1520 std::fs::write(&path, source(present)).expect("initial source");
1521 let mut session = class_projection_session(root);
1522 assert_eq!(session_class_projection(&session), ["dead"]);
1523 for (body, expected) in [(absent, vec!["dead", "used"]), (present, vec!["dead"])] {
1524 std::fs::write(&path, source(body)).expect("source update");
1525 session.refresh_discovery();
1526 assert_eq!(session_class_projection(&session), expected);
1527 assert_eq!(
1528 session_class_projection(&session),
1529 session_class_projection(&class_projection_session(root))
1530 );
1531 }
1532 }
1533 }
1534
1535 #[test]
1536 fn indexed_source_proof_removal_and_restoration_matches_fresh_sessions() {
1537 for (label, present, absent, access) in [
1538 (
1539 "literal",
1540 "const items = [new C()];",
1541 "const items = [new Other()];",
1542 "items[0].used();",
1543 ),
1544 (
1545 "vue",
1546 "import { computed } from 'vue';const items = computed(() => [new C()]);",
1547 "import { computed } from 'foreign';const items = computed(() => [new C()]);",
1548 "items.value[0].used();",
1549 ),
1550 ] {
1551 let project = tempfile::tempdir().expect("session fixture");
1552 let root = project.path();
1553 std::fs::create_dir(root.join("src")).expect("source directory");
1554 std::fs::write(root.join("package.json"),
1555 r#"{"name":"session-array-proof","type":"module","main":"src/index.ts","dependencies":{"vue":"*","foreign":"*"}}"#)
1556 .expect("package manifest");
1557 std::fs::write(root.join("src/classes.ts"),
1558 "export class C { control() {} used() {} dead() {} } export class Other { used() {} }")
1559 .expect("classes");
1560 for provider in ["vue", "foreign"] {
1561 let directory = root.join("node_modules").join(provider);
1562 std::fs::create_dir_all(&directory).expect("provider directory");
1563 std::fs::write(
1564 directory.join("package.json"),
1565 format!(r#"{{"name":"{provider}","type":"module","main":"index.js"}}"#),
1566 )
1567 .expect("provider package");
1568 std::fs::write(
1569 directory.join("index.js"),
1570 "export const computed = getter => ({ get value() { return getter(); } });",
1571 )
1572 .expect("provider source");
1573 }
1574 let source = |producer: &str| {
1575 format!(
1576 "import {{ C, Other }} from './classes';new C().control();\n{producer}\n{access}\n"
1577 )
1578 };
1579 let original = source(present);
1580 let path = root.join("src/index.ts");
1581 std::fs::write(&path, &original).expect("initial source");
1582 let mut retained = class_projection_session(root);
1583 for (phase, content, expected) in [
1584 ("initial", original.as_str(), vec!["dead"]),
1585 ("removed", source(absent).as_str(), vec!["dead", "used"]),
1586 ("restored", original.as_str(), vec!["dead"]),
1587 ] {
1588 std::fs::write(&path, content).expect("update proof source");
1589 retained.refresh_discovery();
1590 let actual = session_class_projection(&retained);
1591 assert_eq!(actual, expected, "{label}: {phase}");
1592 assert_eq!(
1593 actual,
1594 session_class_projection(&class_projection_session(root)),
1595 "{label}: retained and fresh differ after {phase}"
1596 );
1597 }
1598 }
1599 }
1600
1601 #[test]
1604 fn a_cancelled_session_returns_a_cancellation_error_not_an_empty_result() {
1605 let project = tempfile::tempdir().expect("project");
1606 let root = project.path();
1607 std::fs::create_dir(root.join("src")).expect("create source directory");
1608 std::fs::write(root.join("src/index.ts"), "export const entry = 1;\n").expect("entry");
1609 std::fs::write(root.join("src/orphan.ts"), "export const orphan = 1;\n").expect("orphan");
1610
1611 let baseline = AnalysisSession::load_default(root)
1612 .analyze_dead_code()
1613 .expect("an uncancelled session analyzes");
1614 assert!(
1615 !baseline.results.unused_files.is_empty(),
1616 "the fixture must have findings, so an empty result would be a plausible wrong answer"
1617 );
1618
1619 let error = AnalysisSession::load_default(root)
1620 .with_cancellation(Arc::new(AtomicBool::new(true)))
1621 .analyze_dead_code()
1622 .expect_err("a cancelled session must not return results");
1623 assert!(error.is_cancelled(), "unexpected error: {error}");
1624 assert!(error.message().contains("cancelled"));
1625 }
1626
1627 #[test]
1633 fn a_refused_graph_cache_names_its_reason_in_the_engine_timings() {
1634 let project = tempfile::tempdir().expect("project");
1635 let root = project.path();
1636 std::fs::create_dir(root.join("src")).expect("create source directory");
1637 std::fs::write(root.join("src/index.ts"), "export const entry = 1;\n").expect("entry");
1638
1639 let cold = AnalysisSession::load_default(root)
1640 .analyze_dead_code_with_artifacts(false, true)
1641 .expect("cold run analyzes");
1642 assert_eq!(
1643 cold.timings
1644 .expect("cold timings retained")
1645 .graph_cache_rejection,
1646 Some(CacheRejection::Absent),
1647 "a first run has no persisted graph to refuse"
1648 );
1649
1650 std::fs::write(
1651 root.join("src/index.ts"),
1652 "export const entry = 1;\nexport const added = 2;\n",
1653 )
1654 .expect("edit the entry");
1655
1656 let warm = AnalysisSession::load_default(root)
1657 .analyze_dead_code_with_artifacts(false, true)
1658 .expect("warm run analyzes");
1659 assert_eq!(
1660 warm.timings
1661 .expect("warm timings retained")
1662 .graph_cache_rejection,
1663 Some(CacheRejection::FingerprintChanged),
1664 "the decoded graph was refused because a file changed, and the run must say so"
1665 );
1666 }
1667
1668 #[test]
1671 fn a_session_without_a_token_is_never_cancelled() {
1672 let (_project, session) = session_with_source("export const unused = 1;\n");
1673 assert!(!session.is_cancelled());
1674 session
1675 .analyze_dead_code()
1676 .expect("a session without a token analyzes");
1677 }
1678
1679 const PARSE_LOOP_FILES: usize = 400;
1683
1684 fn parse_loop_project() -> tempfile::TempDir {
1685 let project = tempfile::tempdir().expect("project");
1686 let src = project.path().join("src");
1687 std::fs::create_dir_all(&src).expect("src dir");
1688 for module in 0..PARSE_LOOP_FILES {
1689 let mut source = String::new();
1690 for symbol in 0..20 {
1691 let _ = writeln!(
1692 source,
1693 "export const helper{symbol} = (input: number): number => {{\n \
1694 if (input > {symbol}) {{\n return input * {symbol};\n }}\n \
1695 return input - {symbol};\n}};"
1696 );
1697 }
1698 std::fs::write(src.join(format!("mod{module}.ts")), source).expect("module");
1699 }
1700 project
1701 }
1702
1703 #[cfg(unix)]
1710 #[test]
1711 fn a_refresh_drops_modules_whose_fingerprints_need_a_content_check() {
1712 let (_project, mut session) = session_with_source("export const kept = 1;\n");
1713 drop(session.parse_modules(false, None));
1714
1715 assert!(!session.refresh_discovery(), "the file set is the same");
1716 assert!(
1717 session.parsed_cache.lock().expect("parse cache").is_some(),
1718 "fingerprints with a known ctime keep the modules for the next run"
1719 );
1720
1721 if let Some(cache) = session
1722 .parsed_cache
1723 .get_mut()
1724 .expect("parse cache")
1725 .as_mut()
1726 {
1727 for fingerprint in &mut cache.fingerprints {
1728 fingerprint.ctime_ns = 0;
1729 }
1730 }
1731 assert!(!session.refresh_discovery(), "the file set is the same");
1732 assert!(
1733 session.parsed_cache.lock().expect("parse cache").is_none(),
1734 "the next run parses through the persisted cache, which checks the content"
1735 );
1736 }
1737
1738 #[cfg(unix)]
1742 #[test]
1743 fn a_flush_stores_an_unsettled_fingerprint_without_its_ctime() {
1744 let (project, mut session) = session_with_source("export const kept = 1;\n");
1745 drop(session.parse_modules(false, None));
1746 let path = project.path().join("src/index.ts");
1747 let stored_ctime = |session: &AnalysisSession| {
1748 let _ = std::fs::remove_dir_all(&session.config.cache_dir);
1749 session.disk_cache_stale.store(true, Ordering::SeqCst);
1750 session.flush_parse_cache();
1751 let store = fallow_extract::cache::CacheStore::load(
1752 &session.config.cache_dir,
1753 &session.config.root,
1754 session.config.cache_config_hash,
1755 crate::project_config::resolve_cache_max_size_bytes(&session.config),
1756 )
1757 .expect("flush writes the parse cache");
1758 store
1759 .get_by_path_only(&path)
1760 .expect("flushed module")
1761 .ctime_ns
1762 };
1763
1764 let set_read_started = |session: &mut AnalysisSession, offset: u64| {
1767 if let Some(cache) = session
1768 .parsed_cache
1769 .get_mut()
1770 .expect("parse cache")
1771 .as_mut()
1772 {
1773 let ctime = cache.fingerprints[0].ctime_ns;
1774 assert!(ctime > 0, "the platform reports a ctime");
1775 cache.read_started_ns = ctime.saturating_add(offset);
1776 }
1777 };
1778
1779 set_read_started(&mut session, 0);
1780 assert_eq!(
1781 stored_ctime(&session),
1782 0,
1783 "a fingerprint inside the window is not settled"
1784 );
1785
1786 set_read_started(
1787 &mut session,
1788 fallow_types::source_fingerprint::TIMESTAMP_SETTLE_WINDOW_NS,
1789 );
1790 assert!(
1791 stored_ctime(&session) > 0,
1792 "a settled fingerprint keeps its ctime"
1793 );
1794 }
1795
1796 #[cfg(unix)]
1800 #[test]
1801 fn a_same_tick_rewrite_does_not_reuse_the_kept_module() {
1802 let (project, mut session) = session_with_source("export const alpha = 1;\n");
1803 drop(session.parse_modules(false, None));
1804
1805 let path = project.path().join("src/index.ts");
1806 std::fs::write(&path, "export const bravo = 1;\n").expect("rewrite source");
1807 let same_tick = SourceFingerprint::from_metadata(
1808 &std::fs::metadata(&path).expect("metadata after rewrite"),
1809 );
1810 if let Some(cache) = session
1811 .parsed_cache
1812 .get_mut()
1813 .expect("parse cache")
1814 .as_mut()
1815 {
1816 cache.fingerprints = vec![same_tick];
1817 }
1818
1819 let modules = session.parse_modules(false, None).modules;
1820 let exports: Vec<String> = modules
1821 .iter()
1822 .flat_map(|module| module.exports.iter())
1823 .map(|export| export.name.to_string())
1824 .collect();
1825 assert_eq!(exports, vec!["bravo".to_string()]);
1826 }
1827
1828 fn uncached_session(root: &Path) -> AnalysisSession {
1831 let mut project_config = crate::project_config::default_project_config(root);
1832 project_config.config.no_cache = true;
1833 AnalysisSession::from_config(project_config)
1834 }
1835
1836 #[test]
1845 fn a_cancelled_parse_stops_partway_and_leaves_no_truncated_cache_behind() {
1846 let project = parse_loop_project();
1847 let root = project.path();
1848
1849 let token = Arc::new(AtomicBool::new(true));
1852 let session = uncached_session(root).with_cancellation(Arc::clone(&token));
1853 let stopped = session.parse_modules(false, Some(&token));
1854 assert!(stopped.modules.is_empty(), "the loop never read the token");
1855 assert!(
1856 session.parsed_cache.lock().expect("parse cache").is_none(),
1857 "a truncated parse must not be retained as this session's warm cache"
1858 );
1859
1860 drop(uncached_session(root).parse_modules(false, None));
1862 let session = uncached_session(root);
1863 let started = Instant::now();
1864 let full_count = session.parse_modules(false, None).modules.len();
1865 let full_parse = started.elapsed();
1866 assert_eq!(
1867 full_count, PARSE_LOOP_FILES,
1868 "the fixture must parse every generated module"
1869 );
1870
1871 let mut shorter_than = None::<Duration>;
1876 let mut longer_than = Duration::ZERO;
1877 let mut delay = full_parse / 2;
1878 let mut stopped_part_way = false;
1879 for _ in 0..16 {
1880 let token = Arc::new(AtomicBool::new(false));
1881 let session = uncached_session(root).with_cancellation(Arc::clone(&token));
1884 let watchdog = {
1885 let token = Arc::clone(&token);
1886 std::thread::spawn(move || {
1887 std::thread::sleep(delay);
1888 token.store(true, Ordering::SeqCst);
1889 })
1890 };
1891 let cancelled = session.parse_modules(false, Some(&token));
1892 watchdog.join().expect("watchdog thread");
1893
1894 let parsed = cancelled.modules.len();
1895 if parsed == full_count {
1896 shorter_than = Some(delay);
1897 } else if parsed == 0 {
1898 longer_than = delay;
1899 } else {
1900 stopped_part_way = true;
1901 break;
1902 }
1903 delay = match shorter_than {
1904 Some(upper) => (longer_than + upper) / 2,
1905 None => delay * 2,
1906 };
1907 }
1908 assert!(
1909 stopped_part_way,
1910 "no attempt in 16 stopped the parse part way through"
1911 );
1912
1913 let recovered = uncached_session(root).parse_modules(false, None);
1914 assert_eq!(
1915 recovered.modules.len(),
1916 full_count,
1917 "a later uncancelled parse must still see the whole project"
1918 );
1919 }
1920
1921 #[test]
1922 fn session_retains_workspace_metadata_from_config_load() {
1923 let project = tempfile::tempdir().expect("project");
1924 let root = project.path();
1925 std::fs::write(
1926 root.join("package.json"),
1927 r#"{"name":"root","workspaces":["packages/*"]}"#,
1928 )
1929 .expect("write root package");
1930 std::fs::create_dir_all(root.join("packages/a")).expect("create workspace");
1931 std::fs::write(
1932 root.join("packages/a/package.json"),
1933 r#"{"name":"pkg-a","type":"module"}"#,
1934 )
1935 .expect("write workspace package");
1936
1937 let session = AnalysisSession::load(root, None).expect("session loads");
1938
1939 assert!(
1940 session
1941 .workspaces()
1942 .iter()
1943 .any(|workspace| workspace.name == "pkg-a"),
1944 "session must retain workspace metadata discovered during config load"
1945 );
1946 }
1947
1948 #[test]
1949 fn finding_ignore_filters_results_without_removing_graph_inputs() {
1950 let project = tempfile::tempdir().expect("project");
1951 let root = project.path();
1952 std::fs::create_dir(root.join("src")).expect("create source directory");
1953 std::fs::write(
1954 root.join("package.json"),
1955 r#"{"name":"finding-ignore","devDependencies":{"vitest":"latest"}}"#,
1956 )
1957 .expect("write package manifest");
1958 std::fs::write(
1959 root.join("vitest.config.ts"),
1960 "import './src/feature';\nexport default {};\n",
1961 )
1962 .expect("write vitest config");
1963 std::fs::write(
1964 root.join("src/feature.ts"),
1965 "export const feature = true;\n",
1966 )
1967 .expect("write reachable source");
1968 std::fs::write(root.join("src/hidden.ts"), "export const hidden = true;\n")
1969 .expect("write hidden source");
1970
1971 let unfiltered = AnalysisSession::load(root, None)
1972 .expect("unfiltered session loads")
1973 .analyze_dead_code()
1974 .expect("unfiltered analysis succeeds");
1975 assert!(
1976 unfiltered
1977 .results
1978 .unused_files
1979 .iter()
1980 .any(|finding| finding.file.path.ends_with("src/hidden.ts"))
1981 );
1982
1983 std::fs::write(
1984 root.join(".fallowrc.json"),
1985 r#"{"ignoreFindings":["src/hidden.ts"]}"#,
1986 )
1987 .expect("write fallow config");
1988 let session = AnalysisSession::load(root, None).expect("filtered session loads");
1989 let hidden_path = root.join("src/hidden.ts");
1990 assert!(session.files().iter().any(|file| file.path == hidden_path));
1991
1992 let filtered = session
1993 .analyze_dead_code_with_artifacts(false, true)
1994 .expect("filtered analysis succeeds");
1995 assert!(
1996 filtered
1997 .results
1998 .unused_files
1999 .iter()
2000 .all(|finding| finding.file.path != hidden_path)
2001 );
2002 assert!(
2003 filtered
2004 .graph
2005 .as_ref()
2006 .is_some_and(|graph| graph.module_count() == session.files().len())
2007 );
2008 }
2009
2010 #[test]
2011 fn finding_ignore_normalizes_separators_and_rejects_outside_paths() {
2012 use fallow_types::output_dead_code::UnusedFileFinding;
2013 use fallow_types::results::UnusedFile;
2014
2015 let project = tempfile::tempdir().expect("project");
2016 let config = serde_json::from_str::<fallow_config::FallowConfig>(
2017 r#"{"ignoreFindings":["**/*.ts"]}"#,
2018 )
2019 .expect("config parses")
2020 .resolve(
2021 project.path().to_path_buf(),
2022 fallow_config::OutputFormat::Human,
2023 1,
2024 true,
2025 true,
2026 None,
2027 );
2028 let outside = project
2029 .path()
2030 .parent()
2031 .expect("project has parent")
2032 .join("outside.ts");
2033 let mut results = AnalysisResults {
2034 unused_files: vec![
2035 UnusedFileFinding::with_actions(UnusedFile {
2036 path: PathBuf::from(r"src\hidden.ts"),
2037 }),
2038 UnusedFileFinding::with_actions(UnusedFile {
2039 path: outside.clone(),
2040 }),
2041 ],
2042 ..AnalysisResults::default()
2043 };
2044
2045 crate::dead_code::filter_configured_ignored_findings(&mut results, &config);
2046
2047 assert_eq!(results.unused_files.len(), 1);
2048 assert_eq!(results.unused_files[0].file.path, outside);
2049 }
2050
2051 #[cfg(unix)]
2054 fn warm_store_project() -> tempfile::TempDir {
2055 let project = tempfile::tempdir().expect("project");
2056 let root = project.path();
2057 std::fs::create_dir(root.join("src")).expect("create source directory");
2058 std::fs::write(root.join("src/index.ts"), "export const entry = 1;\n").expect("entry");
2059 std::fs::write(root.join("src/other.ts"), "export const other = 2;\n").expect("other");
2060 project
2061 }
2062
2063 #[cfg(unix)]
2064 fn warm_session(root: &Path, store: &Arc<WarmParseStore>) -> AnalysisSession {
2065 AnalysisSession::load_default(root).with_warm_parse(Some(Arc::clone(store)))
2066 }
2067
2068 #[cfg(unix)]
2069 fn exported_names(modules: &[ModuleInfo]) -> Vec<String> {
2070 let mut names: Vec<String> = modules
2071 .iter()
2072 .flat_map(|module| module.exports.iter().map(|export| export.name.to_string()))
2073 .collect();
2074 names.sort();
2075 names
2076 }
2077
2078 #[cfg(unix)]
2079 #[test]
2080 fn a_warm_store_serves_a_new_session_without_parse_work() {
2081 let project = warm_store_project();
2082 let store = Arc::new(WarmParseStore::new(
2083 crate::warm_parse::WarmParseLimits::default(),
2084 ));
2085
2086 let first = warm_session(project.path(), &store).parse_modules(false, None);
2087 let second = warm_session(project.path(), &store).parse_modules(false, None);
2088
2089 assert!(Arc::ptr_eq(&first.modules, &second.modules));
2090 assert_eq!(second.metrics.cache_hits + second.metrics.cache_misses, 0);
2091 let counts = store.counts();
2092 assert_eq!(counts.parse_runs, 1);
2093 assert_eq!(counts.modules_parsed, 2);
2094 assert_eq!(counts.modules_reused, 2);
2095 }
2096
2097 #[cfg(unix)]
2098 #[test]
2099 fn a_warm_store_serves_the_health_parse_of_a_new_session() {
2100 let project = warm_store_project();
2101 let store = Arc::new(WarmParseStore::new(
2102 crate::warm_parse::WarmParseLimits::default(),
2103 ));
2104
2105 drop(warm_session(project.path(), &store).parse_modules(false, None));
2106 let health = warm_session(project.path(), &store).parsed_parts_uncached(true);
2107
2108 assert_eq!(health.modules.len(), 2);
2109 assert_eq!(health.cache_hits + health.cache_misses, 0);
2110 assert_eq!(
2111 store.counts().parse_runs,
2112 1,
2113 "the first parse computed complexity"
2114 );
2115 }
2116
2117 #[cfg(unix)]
2118 #[test]
2119 fn an_edit_or_a_new_file_makes_the_next_session_parse_again() {
2120 let project = warm_store_project();
2121 let root = project.path();
2122 let store = Arc::new(WarmParseStore::new(
2123 crate::warm_parse::WarmParseLimits::default(),
2124 ));
2125 drop(warm_session(root, &store).parse_modules(false, None));
2126
2127 std::fs::write(root.join("src/other.ts"), "export const renamed = 22;\n").expect("edit");
2128 let edited = warm_session(root, &store).parse_modules(false, None);
2129 assert_eq!(exported_names(&edited.modules), ["entry", "renamed"]);
2130 assert_eq!(
2131 edited.metrics.cache_misses, 1,
2132 "only the edited file is parsed"
2133 );
2134
2135 std::fs::write(root.join("src/added.ts"), "export const added = 3;\n").expect("add");
2136 let added = warm_session(root, &store).parse_modules(false, None);
2137 assert_eq!(
2138 exported_names(&added.modules),
2139 ["added", "entry", "renamed"]
2140 );
2141
2142 let counts = store.counts();
2143 assert_eq!(counts.parse_runs, 3);
2144 assert_eq!(counts.modules_reused, 0);
2145 assert_eq!(store.len(), 2, "each file list keeps its latest parse only");
2146 }
2147
2148 #[cfg(unix)]
2149 #[test]
2150 fn a_session_without_the_persisted_cache_does_not_use_the_store() {
2151 let project = warm_store_project();
2152 let store = Arc::new(WarmParseStore::new(
2153 crate::warm_parse::WarmParseLimits::default(),
2154 ));
2155
2156 drop(
2157 uncached_session(project.path())
2158 .with_warm_parse(Some(Arc::clone(&store)))
2159 .parse_modules(false, None),
2160 );
2161
2162 assert_eq!(
2163 store.counts(),
2164 crate::warm_parse::WarmParseCounts::default()
2165 );
2166 assert!(store.is_empty());
2167 }
2168
2169 #[cfg(unix)]
2173 #[test]
2174 fn a_kept_parse_records_its_read_failures_again() {
2175 let project = warm_store_project();
2176 let root = project.path();
2177 std::fs::write(root.join("src/broken.ts"), [0xff, 0xfe, 0x00]).expect("invalid UTF-8");
2178 let store = Arc::new(WarmParseStore::new(
2179 crate::warm_parse::WarmParseLimits::default(),
2180 ));
2181 let read_failures = |session: &AnalysisSession| {
2182 session
2183 .current_workspace_diagnostics()
2184 .into_iter()
2185 .filter(|diagnostic| {
2186 matches!(
2187 diagnostic.kind,
2188 fallow_types::workspace::WorkspaceDiagnosticKind::SourceReadFailure { .. }
2189 )
2190 })
2191 .count()
2192 };
2193
2194 let first = warm_session(root, &store);
2195 drop(first.parse_modules(false, None));
2196 assert_eq!(read_failures(&first), 1);
2197
2198 drop(fallow_config::record_source_read_failures(root, &[]));
2199 let second = warm_session(root, &store);
2200 drop(second.parse_modules(false, None));
2201 assert_eq!(store.counts().modules_reused, 2);
2202 assert_eq!(read_failures(&second), 1);
2203 }
2204
2205 #[test]
2206 fn warm_parse_cache_reuses_module_storage() {
2207 let (_project, session) = session_with_source("export function value() { return 1; }\n");
2208 let first = session.parse_modules(true, None);
2209 let second = session.parse_modules(false, None);
2210
2211 assert!(
2212 Arc::ptr_eq(&first.modules, &second.modules),
2213 "warm session queries must share parsed module storage"
2214 );
2215 }
2216
2217 #[test]
2218 fn warm_styling_cache_reuses_artifact_allocation() {
2219 let project = tempfile::tempdir().expect("project");
2220 let root = project.path();
2221 std::fs::write(root.join("styles.css"), ".button { color: red; }\n")
2222 .expect("write stylesheet");
2223 let session = AnalysisSession::load_default(root);
2224
2225 let first = session.styling_analysis_artifacts();
2226 let second = session.styling_analysis_artifacts();
2227
2228 assert!(
2229 Arc::ptr_eq(&first, &second),
2230 "warm styling queries must share the cached artifact allocation"
2231 );
2232 }
2233
2234 #[test]
2235 fn shared_parsed_modules_reuse_public_session_storage() {
2236 let (_project, session) = session_with_source("export const value = 1;\n");
2237 let first = session.shared_parsed_modules(true);
2238 let second = session.shared_parsed_modules(false);
2239
2240 assert!(Arc::ptr_eq(&first, &second));
2241 }
2242
2243 #[test]
2244 fn shared_parsed_parts_reuse_public_session_storage() {
2245 let (_project, session) = session_with_source("export const value = 1;\n");
2246 let cached = session.shared_parsed_modules(true);
2247 let parts = session.shared_parsed_parts(false);
2248
2249 assert!(Arc::ptr_eq(&cached, &parts.modules));
2250 }
2251
2252 #[test]
2253 fn warm_complexity_artifacts_reuse_cached_module_storage() {
2254 let (_project, session) = session_with_source("export function value() { return 1; }\n");
2255 let cached = session.parse_modules(true, None);
2256 let artifacts = session
2257 .analyze_dead_code_with_reuse_artifacts(true, true, false)
2258 .expect("analysis succeeds");
2259 let retained = artifacts.modules.expect("complexity modules retained");
2260
2261 assert!(
2262 Arc::ptr_eq(&cached.modules, &retained),
2263 "warm complexity artifacts must share parsed module storage"
2264 );
2265 }
2266
2267 #[test]
2268 fn shared_and_owned_artifacts_preserve_output_bytes() {
2269 let (_project, session) = session_with_source(
2270 "export const used = 1;\nexport const unused = 2;\nconsole.log(used);\n",
2271 );
2272 let owned = session
2273 .analyze_dead_code_with_artifacts(true, true)
2274 .expect("owned analysis succeeds");
2275 let shared = session
2276 .analyze_dead_code_with_shared_artifacts(true, true)
2277 .expect("shared analysis succeeds");
2278
2279 assert_eq!(
2280 serde_json::to_vec(&owned.results).expect("serialize owned results"),
2281 serde_json::to_vec(&shared.results).expect("serialize shared results")
2282 );
2283 assert_eq!(owned.file_hashes, shared.file_hashes);
2284 assert_eq!(
2285 owned
2286 .modules
2287 .as_deref()
2288 .unwrap_or_default()
2289 .iter()
2290 .map(|module| module.content_hash)
2291 .collect::<Vec<_>>(),
2292 shared
2293 .modules
2294 .as_deref()
2295 .unwrap_or_default()
2296 .iter()
2297 .map(|module| module.content_hash)
2298 .collect::<Vec<_>>()
2299 );
2300 }
2301
2302 #[test]
2303 fn route_loader_whole_use_matches_across_cold_and_warm_sessions() {
2304 let project = tempfile::tempdir().expect("project");
2305 let root = project.path();
2306 std::fs::create_dir_all(root.join("app/routes")).expect("create route directory");
2307 std::fs::write(
2308 root.join("package.json"),
2309 r#"{"name":"route-cache-parity","dependencies":{"react-router":"latest"}}"#,
2310 )
2311 .expect("write package manifest");
2312 std::fs::write(
2313 root.join("app/routes/home.tsx"),
2314 r#"
2315import { useLoaderData } from "react-router";
2316export function loader() { return { opaque: "value" }; }
2317export default function Home() {
2318 const data = useLoaderData<typeof loader>();
2319 const copy = { ...data };
2320 return JSON.stringify(copy);
2321}
2322"#,
2323 )
2324 .expect("write route module");
2325
2326 let cold_session = AnalysisSession::load(root, None).expect("cold session loads");
2327 let cold_parse = cold_session.parsed_parts(false);
2328 assert_eq!(cold_parse.cache_hits, 0, "first parse must be cold");
2329 let cold = cold_session
2330 .analyze_dead_code()
2331 .expect("cold analysis succeeds");
2332
2333 let warm_session = AnalysisSession::load(root, None).expect("warm session loads");
2334 let warm_parse = warm_session.parsed_parts(false);
2335 assert!(
2336 warm_parse.cache_hits > 0,
2337 "second session must use disk cache"
2338 );
2339 let warm = warm_session
2340 .analyze_dead_code()
2341 .expect("warm analysis succeeds");
2342
2343 assert!(
2344 cold.results.unused_load_data_keys.is_empty(),
2345 "cold analysis must abstain for an opaque route-loader use"
2346 );
2347 assert_eq!(
2348 serde_json::to_vec(&cold.results).expect("serialize cold results"),
2349 serde_json::to_vec(&warm.results).expect("serialize warm results"),
2350 "warm route-loader analysis must match cold analysis"
2351 );
2352 }
2353
2354 #[test]
2355 fn replaced_module_coverage_matches_across_cold_and_warm_graph_cache() {
2356 let project = tempfile::tempdir().expect("project");
2357 let root = project.path();
2358 std::fs::create_dir(root.join("src")).expect("create source directory");
2359 std::fs::write(
2360 root.join("package.json"),
2361 r#"{"name":"mock-cache-parity","main":"src/index.ts","devDependencies":{"vitest":"latest"}}"#,
2362 )
2363 .expect("write package manifest");
2364 std::fs::write(
2365 root.join("src/dependency.ts"),
2366 "export function dependency() { return 'real'; }\n",
2367 )
2368 .expect("write dependency");
2369 std::fs::write(
2370 root.join("src/wrapper.ts"),
2371 "import { dependency } from './dependency';\nexport function wrapper() { return dependency(); }\n",
2372 )
2373 .expect("write wrapper");
2374 std::fs::write(
2375 root.join("src/index.ts"),
2376 "export { wrapper } from './wrapper';\n",
2377 )
2378 .expect("write entry point");
2379 std::fs::write(
2380 root.join("src/wrapper.test.ts"),
2381 r#"
2382import { vi } from "vitest";
2383vi.mock("./dependency", () => ({ dependency: () => "mock" }));
2384import { wrapper } from "./wrapper";
2385wrapper();
2386"#,
2387 )
2388 .expect("write test");
2389
2390 let cold_session = AnalysisSession::load(root, None).expect("cold session loads");
2391 let dependency_id = cold_session
2392 .files()
2393 .iter()
2394 .find(|file| file.path == root.join("src/dependency.ts"))
2395 .expect("dependency discovered")
2396 .id;
2397 let cold = cold_session
2398 .analyze_dead_code_with_artifacts(false, true)
2399 .expect("cold analysis succeeds");
2400 let cold_exports = crate::module_graph::module_value_exports(
2401 cold.graph.as_ref().expect("cold graph retained"),
2402 );
2403 assert!(
2404 fallow_graph::cache::GraphCacheStore::load(&cold_session.config().cache_dir).is_ok(),
2405 "cold analysis must persist the graph cache"
2406 );
2407
2408 let warm_session = AnalysisSession::load(root, None).expect("warm session loads");
2409 let warm = warm_session
2410 .analyze_dead_code_with_artifacts(false, true)
2411 .expect("warm analysis succeeds");
2412 let warm_exports = crate::module_graph::module_value_exports(
2413 warm.graph.as_ref().expect("warm graph retained"),
2414 );
2415
2416 let dependency = cold_exports
2417 .iter()
2418 .find(|export| export.file_id == dependency_id && export.name == "dependency")
2419 .expect("dependency export retained");
2420 assert!(!dependency.test_referenced);
2421 assert_eq!(warm_exports, cold_exports);
2422 }
2423
2424 #[test]
2425 fn session_parse_surfaces_removed_source_with_sparse_file_ids() {
2426 let project = tempfile::tempdir().expect("project");
2427 let root = project.path();
2428 std::fs::create_dir(root.join("src")).expect("create source directory");
2429 std::fs::write(root.join("package.json"), r#"{"name":"read-failure"}"#)
2430 .expect("write package manifest");
2431 for name in ["a.ts", "b.ts", "c.ts"] {
2432 std::fs::write(
2433 root.join("src").join(name),
2434 format!("export const {} = 1;\n", name.replace('.', "_")),
2435 )
2436 .expect("write source");
2437 }
2438 let session = AnalysisSession::load(root, None).expect("session loads");
2439 let removed_path = root.join("src/b.ts");
2440 let removed_id = session
2441 .files()
2442 .iter()
2443 .find(|file| file.path == removed_path)
2444 .expect("removed source discovered")
2445 .id;
2446 std::fs::remove_file(&removed_path).expect("remove source after discovery");
2447
2448 let parts = session.parsed_parts(false);
2449
2450 assert!(
2451 parts
2452 .modules
2453 .iter()
2454 .all(|module| module.file_id != removed_id),
2455 "unreadable file must not receive a placeholder module"
2456 );
2457 let diagnostic = parts
2458 .workspace_diagnostics
2459 .iter()
2460 .find(|diagnostic| diagnostic.kind.id() == "source-read-failure")
2461 .expect("parsed session parts carry source read failure");
2462 assert_eq!(diagnostic.path, removed_path);
2463 assert!(
2464 session
2465 .current_workspace_diagnostics()
2466 .iter()
2467 .any(|diagnostic| {
2468 diagnostic.kind.id() == "source-read-failure" && diagnostic.path == removed_path
2469 }),
2470 "session output carries parse-time source diagnostics"
2471 );
2472 }
2473
2474 const MALFORMED_PNPM_WORKSPACE_YAML: &str =
2475 "catalog:\n react: ^18.2.0\n{this is\nnot: valid: yaml: at: all\n";
2476 const VALID_PNPM_WORKSPACE_YAML: &str = "catalog:\n react: ^18.2.0\n";
2477
2478 fn has_diagnostic_kind(diagnostics: &[WorkspaceDiagnostic], id: &str) -> bool {
2479 diagnostics
2480 .iter()
2481 .any(|diagnostic| diagnostic.kind.id() == id)
2482 }
2483
2484 fn write_single_source_project(root: &Path, manifest: &str) {
2485 std::fs::create_dir(root.join("src")).expect("create source directory");
2486 std::fs::write(root.join("package.json"), manifest).expect("write package manifest");
2487 std::fs::write(root.join("src/index.ts"), "export const value = 1;\n")
2488 .expect("write source");
2489 }
2490
2491 #[test]
2497 fn later_session_drops_stale_analysis_stage_diagnostic_after_cause_is_fixed() {
2498 let project = tempfile::tempdir().expect("project");
2499 let root = project.path();
2500 write_single_source_project(
2501 root,
2502 r#"{"name":"issue-2366-engine-session","private":true}"#,
2503 );
2504 std::fs::write(
2505 root.join("pnpm-workspace.yaml"),
2506 MALFORMED_PNPM_WORKSPACE_YAML,
2507 )
2508 .expect("write malformed workspace yaml");
2509
2510 let broken = AnalysisSession::load(root, None).expect("session loads");
2511 broken
2512 .analyze_dead_code()
2513 .expect("analysis on the malformed yaml succeeds");
2514 assert!(
2515 has_diagnostic_kind(
2516 &broken.current_workspace_diagnostics(),
2517 "malformed-pnpm-workspace-yaml"
2518 ),
2519 "the first session surfaces the malformed yaml: {:?}",
2520 broken.current_workspace_diagnostics()
2521 );
2522
2523 std::fs::write(root.join("pnpm-workspace.yaml"), VALID_PNPM_WORKSPACE_YAML)
2524 .expect("fix workspace yaml");
2525
2526 let fixed = AnalysisSession::load(root, None).expect("session loads");
2527 fixed
2528 .analyze_dead_code()
2529 .expect("analysis on the fixed yaml succeeds");
2530 let current = fixed.current_workspace_diagnostics();
2531 assert!(
2532 !has_diagnostic_kind(¤t, "malformed-pnpm-workspace-yaml"),
2533 "a later session must not keep the stale analysis-stage entry (#2366): {current:?}"
2534 );
2535 }
2536
2537 #[test]
2544 fn watch_style_rerun_drops_bun_lockb_skip_once_text_lockfile_exists() {
2545 let project = tempfile::tempdir().expect("project");
2546 let root = project.path();
2547 write_single_source_project(
2548 root,
2549 r#"{"name":"issue-2366-watch-rerun","private":true,"overrides":{"ws":"^8.21.0"}}"#,
2550 );
2551 std::fs::write(root.join("bun.lockb"), b"placeholder binary lockfile")
2552 .expect("write bun.lockb placeholder");
2553 let config = fallow_config::FallowConfig::default().resolve(
2554 root.to_path_buf(),
2555 fallow_config::OutputFormat::Json,
2556 1,
2557 true,
2558 true,
2559 None,
2560 );
2561 let reload_config = || {
2562 let (_, diagnostics) =
2563 fallow_config::discover_workspaces_with_diagnostics(root, &config.ignore_patterns)
2564 .expect("workspace discovery succeeds");
2565 fallow_config::stash_workspace_diagnostics(root, diagnostics);
2566 };
2567
2568 reload_config();
2569 let first =
2570 AnalysisSession::from_resolved_config(config.clone()).expect("first session loads");
2571 first
2572 .analyze_dead_code()
2573 .expect("analysis with bun.lockb only succeeds");
2574 assert!(
2575 has_diagnostic_kind(
2576 &first.current_workspace_diagnostics(),
2577 "bun-lockb-override-resolution-skipped"
2578 ),
2579 "the first run surfaces the bun.lockb skip: {:?}",
2580 first.current_workspace_diagnostics()
2581 );
2582
2583 std::fs::write(
2584 root.join("bun.lock"),
2585 r#"{"lockfileVersion":1,"workspaces":{"":{"name":"issue-2366-watch-rerun"}},"packages":{"ws":["ws@8.21.3","",{},"sha512-20"]}}"#,
2586 )
2587 .expect("write text bun.lock");
2588
2589 reload_config();
2590 let rerun =
2591 AnalysisSession::from_resolved_config(config.clone()).expect("rerun session loads");
2592 rerun
2593 .analyze_dead_code()
2594 .expect("analysis with the text bun.lock succeeds");
2595 let current = rerun.current_workspace_diagnostics();
2596 assert!(
2597 !has_diagnostic_kind(¤t, "bun-lockb-override-resolution-skipped"),
2598 "the rerun drops the skip once a text bun.lock exists (#2366): {current:?}"
2599 );
2600 }
2601
2602 #[test]
2615 fn session_keeps_its_own_walk_skips_and_ignores_another_walks_registry_write() {
2616 let project = tempfile::tempdir().expect("project");
2617 let root = project.path();
2618 write_single_source_project(
2619 root,
2620 r#"{"name":"issue-2366-parallel-walks","private":true}"#,
2621 );
2622 std::fs::write(root.join("src/huge.ts"), "// filler\n".repeat(400))
2623 .expect("write oversized source");
2624 let mut config = fallow_config::FallowConfig::default().resolve(
2625 root.to_path_buf(),
2626 fallow_config::OutputFormat::Json,
2627 1,
2628 true,
2629 true,
2630 None,
2631 );
2632 config.max_file_size_bytes = Some(1024);
2633
2634 let session = AnalysisSession::from_resolved_config(config).expect("session loads");
2635
2636 fallow_config::append_workspace_diagnostics(
2641 root,
2642 vec![WorkspaceDiagnostic::new(
2643 root,
2644 root.join("src/other-walk-only.ts"),
2645 fallow_types::workspace::WorkspaceDiagnosticKind::SkippedLargeFile {
2646 size_bytes: 4096,
2647 },
2648 )],
2649 );
2650
2651 let current = session.current_workspace_diagnostics();
2652 let skipped: Vec<&Path> = current
2653 .iter()
2654 .filter(|diagnostic| diagnostic.kind.id() == "skipped-large-file")
2655 .map(|diagnostic| diagnostic.path.as_path())
2656 .collect();
2657 assert_eq!(
2658 skipped.len(),
2659 1,
2660 "the session reports its own walk's skips only: {skipped:?}"
2661 );
2662 assert!(
2663 skipped[0].ends_with("src/huge.ts"),
2664 "the surviving skip is this walk's own: {skipped:?}"
2665 );
2666 }
2667
2668 #[test]
2676 fn config_reload_after_the_analyze_pass_keeps_the_bun_lockb_skip_readable() {
2677 let project = tempfile::tempdir().expect("project");
2678 let root = project.path();
2679 write_single_source_project(
2680 root,
2681 r#"{"name":"issue-2366-reload-preserve","private":true,"overrides":{"ws":"^8.21.0"}}"#,
2682 );
2683 std::fs::write(root.join("bun.lockb"), b"placeholder binary lockfile")
2684 .expect("write bun.lockb placeholder");
2685 let config = fallow_config::FallowConfig::default().resolve(
2686 root.to_path_buf(),
2687 fallow_config::OutputFormat::Json,
2688 1,
2689 true,
2690 true,
2691 None,
2692 );
2693 let reload_config = || {
2694 let (_, diagnostics) =
2695 fallow_config::discover_workspaces_with_diagnostics(root, &config.ignore_patterns)
2696 .expect("workspace discovery succeeds");
2697 fallow_config::stash_workspace_diagnostics(root, diagnostics);
2698 };
2699
2700 reload_config();
2701 let analyzing =
2702 AnalysisSession::from_resolved_config(config.clone()).expect("session loads");
2703 analyzing
2704 .analyze_dead_code()
2705 .expect("analysis with bun.lockb only succeeds");
2706
2707 reload_config();
2710
2711 let later = AnalysisSession::from_resolved_config(config.clone()).expect("session loads");
2712 let current = later.current_workspace_diagnostics();
2713 assert!(
2714 has_diagnostic_kind(¤t, "bun-lockb-override-resolution-skipped"),
2715 "the reload must preserve the analysis-stage entry the pass recorded (#2366): \
2716 {current:?}"
2717 );
2718 }
2719}
2720
2721#[cfg(any(test, feature = "testing"))]
2722#[path = "session_direct_load.rs"]
2723mod direct_load;
2724
2725#[cfg(all(test, unix, not(miri)))]
2726#[path = "session_shared_state_tests.rs"]
2727mod shared_state_tests;
2728
2729#[cfg(test)]
2730#[path = "session_shared_state_load_tests.rs"]
2731mod shared_state_load_tests;
2732
2733#[cfg(all(test, unix, not(miri)))]
2734#[path = "session_call_facts_tests.rs"]
2735mod call_facts_tests;
2736
2737#[cfg(test)]
2738#[path = "session_duplication_tests.rs"]
2739mod duplication_tests;