Skip to main content

fallow_graph/cache/
mod.rs

1//! Persisted graph-cache identity contracts and on-disk store.
2//!
3//! The manifest types here define the invalidation surface a persisted graph
4//! cache must satisfy before a cached graph can be trusted. Exact manifest hits
5//! can reuse a previously-built `ModuleGraph`; stable-key resolver hits can
6//! reuse resolver output and rebuild the graph with current `FileId`s.
7
8use std::sync::Arc;
9
10use std::path::{Path, PathBuf};
11
12use fallow_types::cache_rejection::CacheRejection;
13use fallow_types::discover::{DiscoveredFile, FileId, StableFileKey};
14use fallow_types::extract::{ImportInfo, ReExportInfo, VisibilityTag};
15use oxc_span::Span;
16
17use crate::resolve::{
18    MissingExportTarget, ResolveResult, ResolvedImport, ResolvedModule, ResolvedProject,
19    ResolvedReExport, ResolvedReplacedModuleTarget,
20};
21
22mod store;
23
24pub use store::{GRAPH_CACHE_FILE, GraphCacheStore};
25
26/// Persisted graph cache schema version.
27///
28/// Bump this whenever the serialized shape of the persisted graph (any of the
29/// graph types that derive serde for the cache, the manifest types, or the
30/// store envelope) changes, so a stale `graph-cache.bin` written by an older
31/// binary is rejected rather than deserialized into the wrong shape.
32///
33/// Bump it for import-resolution semantics changes too, not only for wire-shape
34/// changes. The manifest compares this constant, the cache mode, and per-file
35/// fingerprints, and carries no binary version, so a cache written before a
36/// classification change replays the old classification verbatim on an
37/// unmodified tree and silently hides the new behaviour. The same applies to
38/// plugin config extraction, which seeds entry points and path aliases.
39///
40/// Never reuse a version number that a published build wrote, even from a
41/// development commit. Git history and the CHANGELOG record the reason for
42/// each bump.
43pub const GRAPH_CACHE_VERSION: u32 = 121;
44
45/// Cached form of a resolved target.
46///
47/// Internal targets are stored by stable file key, not by `FileId`, so resolver
48/// output can be reused across a future FileId assignment shift. The persisted
49/// `ModuleGraph` itself is still `FileId`-keyed; callers may only trust the
50/// cached graph when the manifest's `file_id` assignments match, but they may
51/// remap this resolver payload and rebuild the graph.
52#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
53pub enum CachedResolveResult {
54    /// Resolved to a file within the project.
55    InternalModule(StableFileKey),
56    /// Resolved from CommonJS to a file within the project.
57    CommonJsInternalModule(StableFileKey),
58    /// Resolved to a project file through a framework convention auto-import.
59    SyntheticAutoImport(StableFileKey),
60    /// Resolved to a workspace or self package source file.
61    InternalPackageModule {
62        /// Stable source file reached by the package map.
63        key: StableFileKey,
64        /// Package name that was used in the import specifier.
65        package_name: String,
66    },
67    /// Resolved from CommonJS to workspace or self-package source.
68    CommonJsInternalPackageModule {
69        /// Stable source file reached by the package map.
70        key: StableFileKey,
71        /// Package name used in the require specifier.
72        package_name: String,
73    },
74    /// Resolved to a file outside the project.
75    ExternalFile(PathBuf),
76    /// Bare specifier.
77    NpmPackage(String),
78    /// Bare specifier referenced through CommonJS `require()`.
79    CommonJsNpmPackage(String),
80    /// Could not resolve.
81    Unresolvable(String),
82}
83
84impl CachedResolveResult {
85    fn from_resolve_result(
86        target: &ResolveResult,
87        key_by_file_id: &rustc_hash::FxHashMap<FileId, StableFileKey>,
88    ) -> Option<Self> {
89        Some(match target {
90            ResolveResult::InternalModule(file_id) => {
91                Self::InternalModule(key_by_file_id.get(file_id)?.clone())
92            }
93            ResolveResult::CommonJsInternalModule(file_id) => {
94                Self::CommonJsInternalModule(key_by_file_id.get(file_id)?.clone())
95            }
96            ResolveResult::SyntheticAutoImport(file_id) => {
97                Self::SyntheticAutoImport(key_by_file_id.get(file_id)?.clone())
98            }
99            ResolveResult::InternalPackageModule {
100                file_id,
101                package_name,
102            } => Self::InternalPackageModule {
103                key: key_by_file_id.get(file_id)?.clone(),
104                package_name: package_name.clone(),
105            },
106            ResolveResult::CommonJsInternalPackageModule {
107                file_id,
108                package_name,
109            } => Self::CommonJsInternalPackageModule {
110                key: key_by_file_id.get(file_id)?.clone(),
111                package_name: package_name.clone(),
112            },
113            ResolveResult::ExternalFile(path) => Self::ExternalFile(path.clone()),
114            ResolveResult::NpmPackage(package_name) => Self::NpmPackage(package_name.clone()),
115            ResolveResult::CommonJsNpmPackage(package_name) => {
116                Self::CommonJsNpmPackage(package_name.clone())
117            }
118            ResolveResult::Unresolvable(specifier) => Self::Unresolvable(specifier.clone()),
119        })
120    }
121
122    fn into_resolve_result(
123        self,
124        id_by_key: &rustc_hash::FxHashMap<StableFileKey, FileId>,
125    ) -> Option<ResolveResult> {
126        Some(match self {
127            Self::InternalModule(key) => ResolveResult::InternalModule(*id_by_key.get(&key)?),
128            Self::CommonJsInternalModule(key) => {
129                ResolveResult::CommonJsInternalModule(*id_by_key.get(&key)?)
130            }
131            Self::SyntheticAutoImport(key) => {
132                ResolveResult::SyntheticAutoImport(*id_by_key.get(&key)?)
133            }
134            Self::InternalPackageModule { key, package_name } => {
135                ResolveResult::InternalPackageModule {
136                    file_id: *id_by_key.get(&key)?,
137                    package_name,
138                }
139            }
140            Self::CommonJsInternalPackageModule { key, package_name } => {
141                ResolveResult::CommonJsInternalPackageModule {
142                    file_id: *id_by_key.get(&key)?,
143                    package_name,
144                }
145            }
146            Self::ExternalFile(path) => ResolveResult::ExternalFile(path),
147            Self::NpmPackage(package_name) => ResolveResult::NpmPackage(package_name),
148            Self::CommonJsNpmPackage(package_name) => {
149                ResolveResult::CommonJsNpmPackage(package_name)
150            }
151            Self::Unresolvable(specifier) => ResolveResult::Unresolvable(specifier),
152        })
153    }
154}
155
156/// Cached import edge that can be restored without re-running resolution.
157#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
158pub struct CachedResolvedImport {
159    /// Import metadata mirrored from extraction or resolver synthesis.
160    info: CachedImportInfo,
161    /// Resolved target for this import edge.
162    target: CachedResolveResult,
163}
164
165impl CachedResolvedImport {
166    fn from_resolved(
167        import: &ResolvedImport,
168        key_by_file_id: &rustc_hash::FxHashMap<FileId, StableFileKey>,
169    ) -> Option<Self> {
170        Some(Self {
171            info: CachedImportInfo::from(&import.info),
172            target: CachedResolveResult::from_resolve_result(&import.target, key_by_file_id)?,
173        })
174    }
175
176    fn into_resolved(
177        self,
178        id_by_key: &rustc_hash::FxHashMap<StableFileKey, FileId>,
179    ) -> Option<ResolvedImport> {
180        Some(ResolvedImport {
181            info: self.info.into(),
182            target: self.target.into_resolve_result(id_by_key)?,
183        })
184    }
185}
186
187/// Cached re-export edge that can be restored without re-running resolution.
188#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
189pub struct CachedResolvedReExport {
190    /// Re-export metadata mirrored from extraction.
191    info: CachedReExportInfo,
192    /// Resolved target for this re-export source.
193    target: CachedResolveResult,
194}
195
196impl CachedResolvedReExport {
197    fn from_resolved(
198        re_export: &ResolvedReExport,
199        key_by_file_id: &rustc_hash::FxHashMap<FileId, StableFileKey>,
200    ) -> Option<Self> {
201        Some(Self {
202            info: CachedReExportInfo::from(&re_export.info),
203            target: CachedResolveResult::from_resolve_result(&re_export.target, key_by_file_id)?,
204        })
205    }
206
207    fn into_resolved(
208        self,
209        id_by_key: &rustc_hash::FxHashMap<StableFileKey, FileId>,
210    ) -> Option<ResolvedReExport> {
211        Some(ResolvedReExport {
212            info: self.info.into(),
213            target: self.target.into_resolve_result(id_by_key)?,
214        })
215    }
216}
217
218/// Cache-friendly mirror of [`ImportInfo`].
219#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
220pub struct CachedImportInfo {
221    /// Import source specifier.
222    source: String,
223    /// Imported binding shape.
224    imported_name: fallow_types::extract::ImportedName,
225    /// Local binding name.
226    local_name: String,
227    /// Whether this import is type-only.
228    is_type_only: bool,
229    /// Whether this whole-module import only carries the target's type meanings.
230    is_type_only_star: bool,
231    /// Whether this import originated from a style context.
232    from_style: bool,
233    /// Span of the full import declaration.
234    span: [u32; 2],
235    /// Span of the import source literal.
236    source_span: [u32; 2],
237}
238
239impl From<&ImportInfo> for CachedImportInfo {
240    fn from(info: &ImportInfo) -> Self {
241        Self {
242            source: info.source.clone(),
243            imported_name: info.imported_name.clone(),
244            local_name: info.local_name.clone(),
245            is_type_only: info.is_type_only,
246            is_type_only_star: info.is_type_only_star,
247            from_style: info.from_style,
248            span: span_to_pair(info.span),
249            source_span: span_to_pair(info.source_span),
250        }
251    }
252}
253
254impl From<CachedImportInfo> for ImportInfo {
255    fn from(info: CachedImportInfo) -> Self {
256        Self {
257            source: info.source,
258            imported_name: info.imported_name,
259            local_name: info.local_name,
260            is_type_only: info.is_type_only,
261            is_type_only_star: info.is_type_only_star,
262            from_style: info.from_style,
263            span: pair_to_span(info.span),
264            source_span: pair_to_span(info.source_span),
265        }
266    }
267}
268
269/// Cache-friendly mirror of [`ReExportInfo`].
270#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
271pub struct CachedReExportInfo {
272    /// Re-export source specifier.
273    source: String,
274    /// Imported name from the source module.
275    imported_name: String,
276    /// Exported name from this module.
277    exported_name: String,
278    /// Whether this re-export is type-only.
279    is_type_only: bool,
280    /// Span of the re-export declaration.
281    span: [u32; 2],
282    /// Span of the enclosing re-export statement.
283    statement_span: [u32; 2],
284    /// Span of the source string literal.
285    source_span: [u32; 2],
286    /// JSDoc visibility tag on the re-export statement.
287    visibility: VisibilityTag,
288    /// Reason text of an `@expected-unused` tag on the re-export statement.
289    expected_unused_reason: Option<String>,
290}
291
292impl From<&ReExportInfo> for CachedReExportInfo {
293    fn from(info: &ReExportInfo) -> Self {
294        Self {
295            source: info.source.clone(),
296            imported_name: info.imported_name.clone(),
297            exported_name: info.exported_name.clone(),
298            is_type_only: info.is_type_only,
299            span: span_to_pair(info.span),
300            statement_span: span_to_pair(info.statement_span),
301            source_span: span_to_pair(info.source_span),
302            visibility: info.visibility,
303            expected_unused_reason: info.expected_unused_reason.clone(),
304        }
305    }
306}
307
308impl From<CachedReExportInfo> for ReExportInfo {
309    fn from(info: CachedReExportInfo) -> Self {
310        Self {
311            source: info.source,
312            imported_name: info.imported_name,
313            exported_name: info.exported_name,
314            is_type_only: info.is_type_only,
315            span: pair_to_span(info.span),
316            statement_span: pair_to_span(info.statement_span),
317            source_span: pair_to_span(info.source_span),
318            visibility: info.visibility,
319            expected_unused_reason: info.expected_unused_reason,
320        }
321    }
322}
323
324/// Cached resolver output for one module.
325#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
326pub struct CachedResolvedModule {
327    /// Stable identity of the source module.
328    key: StableFileKey,
329    /// Static import and require edges after resolution.
330    resolved_imports: Vec<CachedResolvedImport>,
331    /// Literal dynamic import edges after resolution.
332    resolved_dynamic_imports: Vec<CachedResolvedImport>,
333    /// Re-export source edges after resolution.
334    re_exports: Vec<CachedResolvedReExport>,
335    /// Dynamic import pattern targets, aligned with current extracted patterns.
336    resolved_dynamic_pattern_targets: Vec<Vec<StableFileKey>>,
337    /// Missing `exports` paths of unresolved bare specifiers.
338    missing_export_targets: Vec<MissingExportTarget>,
339}
340
341impl CachedResolvedModule {
342    fn from_resolved(
343        module: &ResolvedModule,
344        key_by_file_id: &rustc_hash::FxHashMap<FileId, StableFileKey>,
345    ) -> Option<Self> {
346        Some(Self {
347            key: key_by_file_id.get(&module.file_id)?.clone(),
348            resolved_imports: module
349                .resolved_imports
350                .iter()
351                .map(|import| CachedResolvedImport::from_resolved(import, key_by_file_id))
352                .collect::<Option<Vec<_>>>()?,
353            resolved_dynamic_imports: module
354                .resolved_dynamic_imports
355                .iter()
356                .map(|import| CachedResolvedImport::from_resolved(import, key_by_file_id))
357                .collect::<Option<Vec<_>>>()?,
358            re_exports: module
359                .re_exports
360                .iter()
361                .map(|re_export| CachedResolvedReExport::from_resolved(re_export, key_by_file_id))
362                .collect::<Option<Vec<_>>>()?,
363            resolved_dynamic_pattern_targets: module
364                .resolved_dynamic_patterns
365                .iter()
366                .map(|(_, targets)| {
367                    targets
368                        .iter()
369                        .map(|target| key_by_file_id.get(target).cloned())
370                        .collect::<Option<Vec<_>>>()
371                })
372                .collect::<Option<Vec<_>>>()?,
373            missing_export_targets: module.missing_export_targets.clone(),
374        })
375    }
376}
377
378/// Stable-key cache form of one resolved project-internal replacement.
379#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
380struct CachedResolvedReplacedModuleTarget {
381    source_key: StableFileKey,
382    target_key: StableFileKey,
383}
384
385impl CachedResolvedReplacedModuleTarget {
386    fn from_resolved(
387        target: ResolvedReplacedModuleTarget,
388        key_by_file_id: &rustc_hash::FxHashMap<FileId, StableFileKey>,
389    ) -> Option<Self> {
390        Some(Self {
391            source_key: key_by_file_id.get(&target.source_file)?.clone(),
392            target_key: key_by_file_id.get(&target.target_file)?.clone(),
393        })
394    }
395
396    fn into_resolved(
397        self,
398        id_by_key: &rustc_hash::FxHashMap<StableFileKey, FileId>,
399    ) -> Option<ResolvedReplacedModuleTarget> {
400        Some(ResolvedReplacedModuleTarget {
401            source_file: *id_by_key.get(&self.source_key)?,
402            target_file: *id_by_key.get(&self.target_key)?,
403        })
404    }
405}
406
407/// Cache-friendly mirror of the complete resolver output.
408#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
409pub struct CachedResolvedProject {
410    modules: Vec<CachedResolvedModule>,
411    replaced_module_targets: Vec<CachedResolvedReplacedModuleTarget>,
412    /// The paths that the resolution checked and did not find (see
413    /// [`ResolvedProject::missed_probes`]).
414    missed_probes: crate::missed_probes::MissedProbes,
415    /// The resolved targets below the root that are not discovered files
416    /// and not below `node_modules`, root-relative and sorted.
417    external_targets: Vec<String>,
418    /// The versions of the hoisted Bun packages that the resolution read.
419    installed_versions: crate::installed_versions::InstalledVersions,
420}
421
422impl CachedResolvedProject {
423    /// True when the files that the cached resolution depends on, but that
424    /// discovery does not list, changed: a file now exists at a path that the
425    /// resolution checked and did not find, a resolved target outside the
426    /// discovered files is gone, or a read Bun package has another version.
427    /// Discovery does not list an extensionless file, a `.json` file, or a
428    /// file in an ignored directory, so the manifest cannot show these
429    /// changes.
430    #[must_use]
431    fn probed_paths_changed(&self, root: &Path) -> bool {
432        let start = std::time::Instant::now();
433        let changed = self.missed_probes.any_exists(root)
434            || crate::missed_probes::any_missing(root, &self.external_targets)
435            || self.installed_versions.any_changed(root);
436        tracing::debug!(
437            missed_probes = self.missed_probes.len(),
438            external_targets = self.external_targets.len(),
439            installed_versions = self.installed_versions.len(),
440            elapsed_ms = start.elapsed().as_secs_f64() * 1000.0,
441            changed,
442            "checked the probed paths of the graph cache"
443        );
444        changed
445    }
446}
447
448/// The root-relative paths of the [`ResolveResult::ExternalFile`] targets
449/// below `root` and not below `node_modules`.
450fn external_targets(root: &Path, resolved: &ResolvedProject) -> Vec<String> {
451    // The resolver can spell a target with the canonical root. Most projects
452    // have no external target, so the root is canonicalized only on demand.
453    let canonical_root = std::cell::OnceCell::new();
454    let mut targets: Vec<String> = resolved
455        .modules
456        .iter()
457        .flat_map(ResolvedModule::all_resolved_source_edges)
458        .filter_map(|edge| match edge.target() {
459            ResolveResult::ExternalFile(path) => crate::missed_probes::project_relative(root, path)
460                .or_else(|| {
461                    canonical_root
462                        .get_or_init(|| dunce::canonicalize(root).ok())
463                        .as_deref()
464                        .and_then(|canonical| {
465                            crate::missed_probes::project_relative(canonical, path)
466                        })
467                }),
468            _ => None,
469        })
470        .collect();
471    targets.sort_unstable();
472    targets.dedup();
473    targets
474}
475
476/// Convert a resolved project into the compact graph-cache resolver payload.
477#[must_use]
478pub fn cache_resolved_project(
479    root: &Path,
480    files: &[DiscoveredFile],
481    resolved: &ResolvedProject,
482) -> Option<CachedResolvedProject> {
483    let key_by_file_id = stable_key_by_file_id(root, files);
484    let modules = resolved
485        .modules
486        .iter()
487        .map(|module| CachedResolvedModule::from_resolved(module, &key_by_file_id))
488        .collect::<Option<Vec<_>>>()?;
489    let replaced_module_targets = resolved
490        .replaced_module_targets
491        .iter()
492        .copied()
493        .map(|target| CachedResolvedReplacedModuleTarget::from_resolved(target, &key_by_file_id))
494        .collect::<Option<Vec<_>>>()?;
495    Some(CachedResolvedProject {
496        modules,
497        replaced_module_targets,
498        missed_probes: resolved.missed_probes.clone(),
499        external_targets: external_targets(root, resolved),
500        installed_versions: crate::installed_versions::InstalledVersions::read(
501            root,
502            &resolved.package_manifests,
503        ),
504    })
505}
506
507/// Restore a resolved project from cached resolver payloads and current parsed modules.
508///
509/// Returns `None` if the payload no longer aligns with the current parse result.
510/// A normal graph-cache manifest hit should keep these aligned; this extra check
511/// keeps corrupt or hand-edited cache files on the safe miss path.
512///
513/// Also returns `None` when a file that the cached resolution probed, and that
514/// discovery does not list, appeared or was removed. The caller restores the
515/// payload only after the manifest compare, so a run that misses on the
516/// manifest pays no file system call for the probes.
517#[must_use]
518pub fn restore_resolved_project(
519    root: &Path,
520    modules: &[fallow_types::extract::ModuleInfo],
521    files: &[DiscoveredFile],
522    cached: &CachedResolvedProject,
523) -> Option<ResolvedProject> {
524    if modules.len() != cached.modules.len() || cached.probed_paths_changed(root) {
525        return None;
526    }
527
528    let mut indexes = RestoreResolvedModuleIndexes::new(root, modules, files);
529    let resolved_modules = cached
530        .modules
531        .iter()
532        .map(|entry| restore_cached_resolved_module(entry, &mut indexes))
533        .collect::<Option<Vec<_>>>()?;
534    let mut replaced_module_targets = cached
535        .replaced_module_targets
536        .iter()
537        .cloned()
538        .map(|target| target.into_resolved(&indexes.file_ids))
539        .collect::<Option<Vec<_>>>()?;
540    replaced_module_targets
541        .sort_unstable_by_key(|target| (target.source_file.0, target.target_file.0));
542    replaced_module_targets.dedup();
543    Some(ResolvedProject {
544        modules: resolved_modules,
545        replaced_module_targets,
546        work: crate::resolve::ResolveWork::default(),
547        missed_probes: cached.missed_probes.clone(),
548        package_manifests: Vec::new(),
549    })
550}
551
552struct RestoreResolvedModuleIndexes<'a> {
553    file_ids: rustc_hash::FxHashMap<StableFileKey, FileId>,
554    modules: rustc_hash::FxHashMap<StableFileKey, &'a fallow_types::extract::ModuleInfo>,
555    paths: rustc_hash::FxHashMap<StableFileKey, std::path::PathBuf>,
556}
557
558impl<'a> RestoreResolvedModuleIndexes<'a> {
559    fn new(
560        root: &Path,
561        modules: &'a [fallow_types::extract::ModuleInfo],
562        files: &[DiscoveredFile],
563    ) -> Self {
564        let key_by_file_id = stable_key_by_file_id(root, files);
565        let id_by_key: rustc_hash::FxHashMap<_, _> = key_by_file_id
566            .iter()
567            .map(|(file_id, key)| (key.clone(), *file_id))
568            .collect();
569        let by_key: rustc_hash::FxHashMap<_, _> = modules
570            .iter()
571            .filter_map(|module| {
572                key_by_file_id
573                    .get(&module.file_id)
574                    .map(|key| (key.clone(), module))
575            })
576            .collect();
577        let path_by_key: rustc_hash::FxHashMap<_, _> = files
578            .iter()
579            .map(|file| {
580                (
581                    StableFileKey::from_root_relative(root, &file.path),
582                    file.path.clone(),
583                )
584            })
585            .collect();
586
587        Self {
588            file_ids: id_by_key,
589            modules: by_key,
590            paths: path_by_key,
591        }
592    }
593}
594
595fn restore_cached_resolved_module(
596    entry: &CachedResolvedModule,
597    indexes: &mut RestoreResolvedModuleIndexes<'_>,
598) -> Option<ResolvedModule> {
599    let module = indexes.modules.remove(&entry.key)?;
600    let path = indexes.paths.get(&entry.key)?.clone();
601    let resolved_dynamic_pattern_targets =
602        restore_dynamic_pattern_targets(entry, module, &indexes.file_ids)?;
603
604    Some(ResolvedModule {
605        file_id: module.file_id,
606        path,
607        exports: Arc::clone(&module.exports),
608        re_exports: entry
609            .re_exports
610            .iter()
611            .cloned()
612            .map(|re_export| re_export.into_resolved(&indexes.file_ids))
613            .collect::<Option<Vec<_>>>()?,
614        resolved_imports: entry
615            .resolved_imports
616            .iter()
617            .cloned()
618            .map(|import| import.into_resolved(&indexes.file_ids))
619            .collect::<Option<Vec<_>>>()?,
620        resolved_dynamic_imports: entry
621            .resolved_dynamic_imports
622            .iter()
623            .cloned()
624            .map(|import| import.into_resolved(&indexes.file_ids))
625            .collect::<Option<Vec<_>>>()?,
626        resolved_dynamic_patterns: module
627            .dynamic_import_patterns
628            .iter()
629            .cloned()
630            .zip(resolved_dynamic_pattern_targets)
631            .collect(),
632        member_accesses: Arc::clone(&module.member_accesses),
633        semantic_facts: Arc::clone(&module.semantic_facts),
634        whole_object_uses: Arc::clone(&module.whole_object_uses),
635        has_cjs_exports: module.has_cjs_exports,
636        has_angular_component_template_url: module.has_angular_component_template_url,
637        unused_import_bindings: module.unused_import_bindings.iter().cloned().collect(),
638        type_referenced_import_bindings: module.type_referenced_import_bindings.clone(),
639        value_referenced_import_bindings: module.value_referenced_import_bindings.clone(),
640        namespace_object_aliases: module.namespace_object_aliases.clone(),
641        exported_factory_returns: Arc::clone(&module.exported_factory_returns),
642        exported_factory_return_object_shapes: Arc::clone(
643            &module.exported_factory_return_object_shapes,
644        ),
645        type_member_types: Arc::clone(&module.type_member_types),
646        missing_export_targets: entry.missing_export_targets.clone(),
647    })
648}
649
650fn restore_dynamic_pattern_targets(
651    entry: &CachedResolvedModule,
652    module: &fallow_types::extract::ModuleInfo,
653    id_by_key: &rustc_hash::FxHashMap<StableFileKey, FileId>,
654) -> Option<Vec<Vec<FileId>>> {
655    if entry.resolved_dynamic_pattern_targets.len() != module.dynamic_import_patterns.len() {
656        return None;
657    }
658    entry
659        .resolved_dynamic_pattern_targets
660        .iter()
661        .map(|targets| {
662            targets
663                .iter()
664                .map(|key| id_by_key.get(key).copied())
665                .collect::<Option<Vec<_>>>()
666        })
667        .collect()
668}
669
670fn stable_key_by_file_id(
671    root: &Path,
672    files: &[DiscoveredFile],
673) -> rustc_hash::FxHashMap<FileId, StableFileKey> {
674    files
675        .iter()
676        .map(|file| (file.id, StableFileKey::from_root_relative(root, &file.path)))
677        .collect()
678}
679
680fn span_to_pair(span: Span) -> [u32; 2] {
681    [span.start, span.end]
682}
683
684fn pair_to_span(pair: [u32; 2]) -> Span {
685    Span::new(pair[0], pair[1])
686}
687
688/// Serialize an [`oxc_span::Span`] as a `[start, end]` `u32` pair.
689///
690/// `oxc_span::Span` does not enable its own serde feature in this workspace, so
691/// the graph types that carry spans route them through this module via
692/// `#[serde(with = "crate::cache::span_serde")]`. A 2-element array keeps the
693/// postcard encoding compact (two varints) and is trivially lossless: a `Span`
694/// is fully described by its `start` / `end` offsets.
695pub(crate) mod span_serde {
696    use oxc_span::Span;
697    use serde::{Deserialize, Deserializer, Serialize, Serializer};
698
699    #[expect(
700        clippy::trivially_copy_pass_by_ref,
701        reason = "serde `serialize_with` / `with` requires a `&T` signature"
702    )]
703    pub fn serialize<S: Serializer>(span: &Span, serializer: S) -> Result<S::Ok, S::Error> {
704        [span.start, span.end].serialize(serializer)
705    }
706
707    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Span, D::Error> {
708        let [start, end] = <[u32; 2]>::deserialize(deserializer)?;
709        Ok(Span::new(start, end))
710    }
711}
712
713/// Lossless cache (de)serialization for `Vec<MemberInfo>`.
714///
715/// `fallow_types::extract::MemberInfo` derives only `serde::Serialize`, and its
716/// `span` field uses `serialize_with` with no matching deserializer, so it
717/// cannot be deserialized through a plain derive. Rather than change the shared
718/// type's serde shape (which would ripple into JSON output), the cache mirrors
719/// it field-for-field into a dedicated `CachedMemberInfo` and converts both
720/// ways. Every `MemberInfo` field is carried, so the round-trip is lossless.
721pub(crate) mod member_serde {
722    use fallow_types::extract::{MemberInfo, MemberKind};
723    use oxc_span::Span;
724    use serde::{Deserialize, Deserializer, Serialize, Serializer};
725
726    #[derive(Serialize, Deserialize)]
727    struct CachedMemberInfo {
728        name: String,
729        kind: MemberKind,
730        span: [u32; 2],
731        has_decorator: bool,
732        decorator_names: Vec<String>,
733        is_instance_returning_static: bool,
734        is_self_returning: bool,
735        #[serde(default)]
736        is_protected: bool,
737        #[serde(default)]
738        is_static: bool,
739    }
740
741    impl From<&MemberInfo> for CachedMemberInfo {
742        fn from(member: &MemberInfo) -> Self {
743            Self {
744                name: member.name.clone(),
745                kind: member.kind,
746                span: [member.span.start, member.span.end],
747                has_decorator: member.has_decorator,
748                decorator_names: member.decorator_names.clone(),
749                is_instance_returning_static: member.is_instance_returning_static,
750                is_self_returning: member.is_self_returning,
751                is_protected: member.is_protected,
752                is_static: member.is_static,
753            }
754        }
755    }
756
757    impl From<CachedMemberInfo> for MemberInfo {
758        fn from(cached: CachedMemberInfo) -> Self {
759            Self {
760                name: cached.name,
761                kind: cached.kind,
762                span: Span::new(cached.span[0], cached.span[1]),
763                has_decorator: cached.has_decorator,
764                decorator_names: cached.decorator_names,
765                is_instance_returning_static: cached.is_instance_returning_static,
766                is_self_returning: cached.is_self_returning,
767                override_base: None,
768                is_protected: cached.is_protected,
769                is_static: cached.is_static,
770            }
771        }
772    }
773
774    pub fn serialize<S: Serializer>(
775        members: &[MemberInfo],
776        serializer: S,
777    ) -> Result<S::Ok, S::Error> {
778        let mirror: Vec<CachedMemberInfo> = members.iter().map(CachedMemberInfo::from).collect();
779        mirror.serialize(serializer)
780    }
781
782    pub fn deserialize<'de, D: Deserializer<'de>>(
783        deserializer: D,
784    ) -> Result<Vec<MemberInfo>, D::Error> {
785        let mirror = Vec::<CachedMemberInfo>::deserialize(deserializer)?;
786        Ok(mirror.into_iter().map(MemberInfo::from).collect())
787    }
788}
789
790/// Option dimensions that affect graph construction.
791///
792/// The hashes are intentionally opaque to this crate. Callers decide which
793/// resolver/plugin/entry-point inputs feed each hash, while this contract keeps
794/// graph-cache validation explicit and typed.
795#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
796pub struct GraphCacheMode {
797    /// Import resolver and tsconfig-relevant options.
798    resolver_options: u64,
799    /// Entry point set and reachability root options.
800    entry_points: u64,
801    /// Plugin-derived graph-affecting configuration.
802    plugin_config: u64,
803}
804
805impl GraphCacheMode {
806    /// Build a mode from explicit hash dimensions.
807    #[must_use]
808    pub const fn new(
809        resolver_options_hash: u64,
810        entry_points_hash: u64,
811        plugin_config_hash: u64,
812    ) -> Self {
813        Self {
814            resolver_options: resolver_options_hash,
815            entry_points: entry_points_hash,
816            plugin_config: plugin_config_hash,
817        }
818    }
819}
820
821/// Source freshness for one file in a graph-cache manifest.
822#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
823pub struct GraphCacheFile {
824    /// Persistable identity for the file.
825    pub key: StableFileKey,
826    /// Current in-memory identifier for the file.
827    ///
828    /// The stable key is the durable identity, but the persisted `ModuleGraph`
829    /// is still `FileId`-keyed. Until a future graph-cache format remaps graph
830    /// edges through stable keys, a changed assignment must miss rather than
831    /// trust a graph whose `modules[file_id]` indexes point at different files.
832    pub file_id: FileId,
833    /// xxh3 hash of the parsed source content.
834    ///
835    /// Content, not `(mtime, size)`: the metadata pair is writer-controlled and
836    /// a same-length rewrite with a restored mtime leaves it unchanged, so a
837    /// metadata-keyed manifest can hand back the previous run's graph for a
838    /// tree that no longer matches it. The hash is free here because the parse
839    /// stage already computed it, and unlike a ctime it survives `cp -Rp` and
840    /// CI cache restores, which is what makes a warm graph reusable across
841    /// checkouts at all.
842    ///
843    /// `0` when the run produced no module for the file (an unreadable source).
844    pub content_hash: u64,
845}
846
847impl GraphCacheFile {
848    /// Build a graph-cache file row from a discovered file and content hash.
849    #[must_use]
850    fn from_discovered_file(root: &Path, file: &DiscoveredFile, content_hash: u64) -> Self {
851        Self {
852            key: StableFileKey::from_root_relative(root, &file.path),
853            file_id: file.id,
854            content_hash,
855        }
856    }
857}
858
859/// Manifest inputs required to trust a persisted graph cache entry.
860#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
861pub struct GraphCacheManifest {
862    /// Root anchoring the absolute paths retained in the graph and resolver payload.
863    pub root: PathBuf,
864    /// Schema version used by the persisted graph-cache entry.
865    pub version: u32,
866    /// Graph-affecting option dimensions.
867    pub mode: GraphCacheMode,
868    /// Stable file identities, current FileId assignments, and freshness metadata.
869    pub files: Vec<GraphCacheFile>,
870}
871
872impl GraphCacheManifest {
873    /// Build a manifest and sort files by stable key for deterministic compare.
874    #[must_use]
875    fn new(root: &Path, mode: GraphCacheMode, mut files: Vec<GraphCacheFile>) -> Self {
876        sort_files(&mut files);
877        Self {
878            root: root.to_path_buf(),
879            version: GRAPH_CACHE_VERSION,
880            mode,
881            files,
882        }
883    }
884
885    /// Build a manifest from discovered files plus a content-hash provider.
886    pub fn from_discovered_files(
887        root: &Path,
888        files: &[DiscoveredFile],
889        mode: GraphCacheMode,
890        mut content_hash_for_file: impl FnMut(&DiscoveredFile) -> u64,
891    ) -> Self {
892        let rows = files
893            .iter()
894            .map(|file| {
895                GraphCacheFile::from_discovered_file(root, file, content_hash_for_file(file))
896            })
897            .collect();
898        Self::new(root, mode, rows)
899    }
900
901    /// True when a persisted manifest matches the current graph inputs.
902    #[must_use]
903    pub fn matches_inputs(&self, current: &Self) -> bool {
904        self.version == GRAPH_CACHE_VERSION
905            && current.version == GRAPH_CACHE_VERSION
906            && self.root == current.root
907            && self.mode == current.mode
908            && self.files == current.files
909    }
910
911    /// Name the first input dimension that differs from the current run, for
912    /// a manifest whose resolution inputs may differ from the current run.
913    ///
914    /// The caller decides graph reuse after a successful, fully paid load, so
915    /// this is the most expensive refusal in the pipeline, and it must not be
916    /// silent. `None` means the resolution inputs actually match and
917    /// the caller should not be asking.
918    #[must_use]
919    pub fn classify_resolution_mismatch(&self, current: &Self) -> Option<CacheRejection> {
920        if self.version != GRAPH_CACHE_VERSION || current.version != GRAPH_CACHE_VERSION {
921            return Some(CacheRejection::VersionMismatch);
922        }
923        if self.root != current.root {
924            return Some(CacheRejection::RootMismatch);
925        }
926        if self.mode != current.mode {
927            return Some(CacheRejection::ModeMismatch);
928        }
929        if self.files.len() != current.files.len()
930            || self
931                .files
932                .iter()
933                .zip(current.files.iter())
934                .any(|(cached, current)| cached.key != current.key)
935        {
936            return Some(CacheRejection::FileSetChanged);
937        }
938        self.files
939            .iter()
940            .zip(current.files.iter())
941            .any(|(cached, current)| cached.content_hash != current.content_hash)
942            .then_some(CacheRejection::FingerprintChanged)
943    }
944}
945
946fn sort_files(files: &mut [GraphCacheFile]) {
947    files.sort_unstable_by(|a, b| a.key.cmp(&b.key));
948}
949
950#[cfg(test)]
951mod tests {
952    use std::path::{Path, PathBuf};
953
954    use fallow_types::discover::FileId;
955    use fallow_types::extract::{DynamicImportPattern, ModuleInfo, ModuleLoadMechanism};
956    use rustc_hash::FxHashMap;
957
958    use super::*;
959
960    fn file(id: u32, path: &str) -> DiscoveredFile {
961        DiscoveredFile {
962            id: FileId(id),
963            path: PathBuf::from(path),
964            size_bytes: 1,
965        }
966    }
967
968    fn mode() -> GraphCacheMode {
969        GraphCacheMode::new(1, 2, 3)
970    }
971
972    fn content_hashes(pairs: &[(&str, u64)]) -> FxHashMap<PathBuf, u64> {
973        pairs
974            .iter()
975            .map(|(path, hash)| (PathBuf::from(path), *hash))
976            .collect()
977    }
978
979    fn manifest(
980        files: &[DiscoveredFile],
981        mode: GraphCacheMode,
982        map: &FxHashMap<PathBuf, u64>,
983    ) -> GraphCacheManifest {
984        GraphCacheManifest::from_discovered_files(Path::new("/project"), files, mode, |file| {
985            *map.get(&file.path).unwrap()
986        })
987    }
988
989    fn import_info(source: &str) -> ImportInfo {
990        ImportInfo {
991            source: source.to_string(),
992            imported_name: fallow_types::extract::ImportedName::SideEffect,
993            local_name: String::new(),
994            is_type_only: false,
995            is_type_only_star: false,
996            from_style: false,
997            span: Span::new(0, 0),
998            source_span: Span::new(0, 0),
999        }
1000    }
1001
1002    #[test]
1003    fn cached_import_info_round_trip_keeps_every_field() {
1004        // The resolver payload is replayed into a fresh graph build, so any
1005        // field the mirror drops silently changes analysis behaviour behind a
1006        // cache hit. Compare the debug rendering so a future field that is not
1007        // mirrored fails here instead of in a warm-only output diff.
1008        let original = ImportInfo {
1009            source: "./impl".to_string(),
1010            imported_name: fallow_types::extract::ImportedName::Namespace,
1011            local_name: "ns".to_string(),
1012            is_type_only: true,
1013            is_type_only_star: true,
1014            from_style: true,
1015            span: Span::new(3, 41),
1016            source_span: Span::new(17, 25),
1017        };
1018
1019        let restored = ImportInfo::from(CachedImportInfo::from(&original));
1020
1021        assert_eq!(format!("{restored:?}"), format!("{original:?}"));
1022    }
1023
1024    #[test]
1025    fn cached_re_export_info_round_trip_keeps_every_field() {
1026        // A dropped field changes analysis behaviour only behind a cache hit,
1027        // so compare the debug rendering of every field.
1028        let original = ReExportInfo {
1029            source: "./impl".to_string(),
1030            imported_name: "a".to_string(),
1031            exported_name: "b".to_string(),
1032            is_type_only: true,
1033            span: Span::new(3, 41),
1034            statement_span: Span::new(0, 42),
1035            source_span: Span::new(30, 38),
1036            visibility: VisibilityTag::ExpectedUnused,
1037            expected_unused_reason: Some("kept for the next major".to_string()),
1038        };
1039
1040        let restored = ReExportInfo::from(CachedReExportInfo::from(&original));
1041
1042        assert_eq!(format!("{restored:?}"), format!("{original:?}"));
1043    }
1044
1045    #[test]
1046    fn manifest_sorts_by_stable_file_key() {
1047        let files = vec![file(0, "/project/src/z.ts"), file(1, "/project/src/a.ts")];
1048        let map = content_hashes(&[("/project/src/z.ts", 10), ("/project/src/a.ts", 20)]);
1049
1050        let manifest = manifest(&files, mode(), &map);
1051
1052        let keys: Vec<&str> = manifest
1053            .files
1054            .iter()
1055            .map(|file| file.key.as_str())
1056            .collect();
1057        assert_eq!(keys, vec!["src/a.ts", "src/z.ts"]);
1058    }
1059
1060    #[test]
1061    fn manifest_misses_on_file_id_shift_until_graph_remap_exists() {
1062        let before = vec![file(0, "/project/src/a.ts"), file(1, "/project/src/c.ts")];
1063        let after = vec![file(9, "/project/src/c.ts"), file(2, "/project/src/a.ts")];
1064        let map = content_hashes(&[("/project/src/a.ts", 10), ("/project/src/c.ts", 20)]);
1065
1066        let cached = manifest(&before, mode(), &map);
1067        let current = manifest(&after, mode(), &map);
1068
1069        assert!(
1070            !cached.matches_inputs(&current),
1071            "the persisted graph is still FileId-keyed, so FileId shifts cannot trust it"
1072        );
1073        assert_eq!(
1074            cached.classify_resolution_mismatch(&current),
1075            None,
1076            "stable-keyed resolver payloads may be remapped across FileId shifts"
1077        );
1078    }
1079
1080    #[test]
1081    fn cached_resolve_result_remaps_internal_targets_by_stable_key() {
1082        let key_a = StableFileKey::from_root_relative(
1083            Path::new("/project"),
1084            Path::new("/project/src/a.ts"),
1085        );
1086        let key_b = StableFileKey::from_root_relative(
1087            Path::new("/project"),
1088            Path::new("/project/src/b.ts"),
1089        );
1090        let key_by_file_id =
1091            FxHashMap::from_iter([(FileId(0), key_a.clone()), (FileId(1), key_b.clone())]);
1092        let id_by_key = FxHashMap::from_iter([(key_a, FileId(7)), (key_b, FileId(9))]);
1093
1094        let cached = CachedResolveResult::from_resolve_result(
1095            &ResolveResult::InternalPackageModule {
1096                file_id: FileId(1),
1097                package_name: "@scope/pkg".to_string(),
1098            },
1099            &key_by_file_id,
1100        )
1101        .expect("target file id should map to a stable key");
1102
1103        let restored = cached
1104            .into_resolve_result(&id_by_key)
1105            .expect("stable key should map to current FileId");
1106
1107        assert!(matches!(
1108            restored,
1109            ResolveResult::InternalPackageModule {
1110                file_id: FileId(9),
1111                ref package_name,
1112            } if package_name == "@scope/pkg"
1113        ));
1114    }
1115
1116    #[test]
1117    fn cached_resolve_result_preserves_commonjs_provenance() {
1118        let key = StableFileKey::from_root_relative(
1119            Path::new("/project"),
1120            Path::new("/project/src/dependency.ts"),
1121        );
1122        let key_by_file_id = FxHashMap::from_iter([(FileId(3), key.clone())]);
1123        let id_by_key = FxHashMap::from_iter([(key, FileId(8))]);
1124
1125        let cached = CachedResolveResult::from_resolve_result(
1126            &ResolveResult::CommonJsInternalModule(FileId(3)),
1127            &key_by_file_id,
1128        )
1129        .expect("CommonJS target should map to a stable key");
1130        let restored = cached
1131            .into_resolve_result(&id_by_key)
1132            .expect("stable key should map to the current FileId");
1133
1134        assert!(matches!(
1135            restored,
1136            ResolveResult::CommonJsInternalModule(FileId(8))
1137        ));
1138    }
1139
1140    #[test]
1141    fn cached_resolve_result_preserves_commonjs_bare_package_provenance() {
1142        let cached = CachedResolveResult::from_resolve_result(
1143            &ResolveResult::CommonJsNpmPackage("shared-package".to_string()),
1144            &FxHashMap::default(),
1145        )
1146        .expect("bare CommonJS package should not need a stable file key");
1147        let restored = cached
1148            .into_resolve_result(&FxHashMap::default())
1149            .expect("bare CommonJS package should restore without a file map");
1150
1151        assert!(matches!(
1152            restored,
1153            ResolveResult::CommonJsNpmPackage(package_name)
1154                if package_name == "shared-package"
1155        ));
1156    }
1157
1158    #[test]
1159    fn cache_resolved_project_rejects_unknown_internal_targets() {
1160        let files = vec![file(0, "/project/src/a.ts")];
1161        let module = ResolvedModule {
1162            file_id: FileId(0),
1163            path: PathBuf::from("/project/src/a.ts"),
1164            resolved_imports: vec![ResolvedImport {
1165                info: import_info("./missing"),
1166                target: ResolveResult::InternalModule(FileId(1)),
1167            }],
1168            ..ResolvedModule::default()
1169        };
1170        let project = ResolvedProject {
1171            modules: vec![module],
1172            replaced_module_targets: Vec::new(),
1173            ..ResolvedProject::default()
1174        };
1175
1176        let cached = cache_resolved_project(Path::new("/project"), &files, &project);
1177
1178        assert!(cached.is_none());
1179    }
1180
1181    #[test]
1182    fn cached_graph_restores_current_factory_property_sources() {
1183        use fallow_types::extract::{
1184            FactoryPropertySource, FactoryReturnObjectPropertySourceFact, SemanticFact,
1185        };
1186        let files = vec![file(0, "/project/src/app.ts")];
1187        let project = ResolvedProject {
1188            modules: vec![ResolvedModule {
1189                file_id: FileId(0),
1190                path: PathBuf::from("/project/src/app.ts"),
1191                ..ResolvedModule::default()
1192            }],
1193            ..ResolvedProject::default()
1194        };
1195        let cached = cache_resolved_project(Path::new("/project"), &files, &project)
1196            .expect("stable graph cache");
1197        let fact = SemanticFact::FactoryReturnObjectPropertySource(Box::new(
1198            FactoryReturnObjectPropertySourceFact {
1199                factory_export_name: "createUi".into(),
1200                property_path: "page".into(),
1201                source: FactoryPropertySource::FunctionReturn {
1202                    callee_name: "make".into(),
1203                },
1204            },
1205        ));
1206        let callback_source = SemanticFact::FactoryReturnObjectPropertySource(Box::new(
1207            FactoryReturnObjectPropertySourceFact {
1208                factory_export_name: "wrap".into(),
1209                property_path: "value".into(),
1210                source: FactoryPropertySource::CallbackParameterReturn { parameter_index: 0 },
1211            },
1212        ));
1213        let callback_access = SemanticFact::CallbackFactoryPropertyAccess(Box::new(
1214            fallow_types::extract::CallbackFactoryPropertyAccessFact {
1215                callee_name: "wrap".into(),
1216                callee_member: None,
1217                property_path: "value".into(),
1218                member: "go".into(),
1219                vue_only: false,
1220                assigned_class: Some("Assigned".into()),
1221                arguments: vec![fallow_types::extract::CallbackFactoryArgument {
1222                    parameter_index: 0,
1223                    class_local_name: "C".into(),
1224                    getter: true,
1225                    lazy_safe: true,
1226                }],
1227            },
1228        ));
1229        for current in [vec![fact, callback_source, callback_access], Vec::new()] {
1230            let module = ModuleInfo {
1231                semantic_facts: current.clone().into(),
1232                ..ModuleInfo::empty(FileId(0))
1233            };
1234            let restored =
1235                restore_resolved_project(Path::new("/project"), &[module], &files, &cached)
1236                    .expect("current parsed facts with cached resolution");
1237            assert_eq!(
1238                restored.modules[0].semantic_facts.as_ref(),
1239                current.as_slice()
1240            );
1241        }
1242    }
1243
1244    #[test]
1245    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
1246    fn a_changed_probed_path_takes_the_cache_miss_path() {
1247        let temp = tempfile::tempdir().unwrap();
1248        let root = temp.path();
1249        std::fs::create_dir_all(root.join("src")).unwrap();
1250        std::fs::write(root.join("src/data.json"), "{}\n").unwrap();
1251        let app = root.join("src/app.ts");
1252        let files = vec![DiscoveredFile {
1253            id: FileId(0),
1254            path: app.clone(),
1255            size_bytes: 1,
1256        }];
1257        let module = ModuleInfo {
1258            imports: vec![import_info("./data")],
1259            ..ModuleInfo::empty(FileId(0))
1260        };
1261        let resolved = ResolvedProject {
1262            modules: vec![ResolvedModule {
1263                file_id: FileId(0),
1264                path: app,
1265                resolved_imports: vec![ResolvedImport {
1266                    info: import_info("./data"),
1267                    target: ResolveResult::ExternalFile(root.join("src/data.json")),
1268                }],
1269                ..ResolvedModule::default()
1270            }],
1271            missed_probes: crate::missed_probes::MissedProbes::from_paths(vec![
1272                "src/data".to_string(),
1273            ]),
1274            ..ResolvedProject::default()
1275        };
1276        let cached = cache_resolved_project(root, &files, &resolved).expect("stable keys");
1277        let restore =
1278            || restore_resolved_project(root, std::slice::from_ref(&module), &files, &cached);
1279        assert!(restore().is_some(), "no probed path changed");
1280
1281        std::fs::write(root.join("src/data"), "export {};\n").unwrap();
1282        assert!(restore().is_none(), "a file appeared at a missed path");
1283        std::fs::remove_file(root.join("src/data")).unwrap();
1284        assert!(restore().is_some());
1285
1286        std::fs::remove_file(root.join("src/data.json")).unwrap();
1287        assert!(
1288            restore().is_none(),
1289            "a resolved target outside discovery is gone"
1290        );
1291    }
1292
1293    #[test]
1294    fn cached_dynamic_pattern_targets_preserve_empty_rows() {
1295        let files = vec![file(0, "/project/src/app.ts")];
1296        let pattern = DynamicImportPattern {
1297            prefix: "./missing/".into(),
1298            suffix: Some(".ts".into()),
1299            span: Span::new(0, 1),
1300            mechanism: ModuleLoadMechanism::EsModule,
1301            excludes: Vec::new(),
1302            imported_name: fallow_types::extract::ImportedName::Namespace,
1303        };
1304        let module = ModuleInfo {
1305            dynamic_import_patterns: vec![pattern.clone()],
1306            ..ModuleInfo::empty(FileId(0))
1307        };
1308        let resolved = ResolvedProject {
1309            modules: vec![ResolvedModule {
1310                file_id: FileId(0),
1311                path: PathBuf::from("/project/src/app.ts"),
1312                resolved_dynamic_patterns: vec![(pattern, Vec::new())],
1313                ..ResolvedModule::default()
1314            }],
1315            replaced_module_targets: Vec::new(),
1316            ..ResolvedProject::default()
1317        };
1318
1319        let cached = cache_resolved_project(Path::new("/project"), &files, &resolved)
1320            .expect("all dynamic pattern targets should have stable keys");
1321        let restored = restore_resolved_project(
1322            Path::new("/project"),
1323            std::slice::from_ref(&module),
1324            &files,
1325            &cached,
1326        )
1327        .expect("cached dynamic pattern rows should align with extracted patterns");
1328
1329        assert_eq!(restored.modules[0].resolved_dynamic_patterns.len(), 1);
1330        assert!(
1331            restored.modules[0].resolved_dynamic_patterns[0]
1332                .1
1333                .is_empty()
1334        );
1335
1336        let mut sparse_cached = cached;
1337        sparse_cached.modules[0]
1338            .resolved_dynamic_pattern_targets
1339            .clear();
1340        assert!(
1341            restore_resolved_project(
1342                Path::new("/project"),
1343                std::slice::from_ref(&module),
1344                &files,
1345                &sparse_cached,
1346            )
1347            .is_none(),
1348            "version-50 sparse rows must take the safe cache-miss path"
1349        );
1350    }
1351
1352    #[test]
1353    fn cached_replaced_target_remaps_both_file_ids_by_stable_key() {
1354        let source_key = StableFileKey::from_root_relative(
1355            Path::new("/project"),
1356            Path::new("/project/src/example.test.ts"),
1357        );
1358        let target_key = StableFileKey::from_root_relative(
1359            Path::new("/project"),
1360            Path::new("/project/src/dependency.ts"),
1361        );
1362        let key_by_file_id = FxHashMap::from_iter([
1363            (FileId(2), source_key.clone()),
1364            (FileId(3), target_key.clone()),
1365        ]);
1366        let id_by_key = FxHashMap::from_iter([(source_key, FileId(8)), (target_key, FileId(9))]);
1367        let resolved = ResolvedReplacedModuleTarget {
1368            source_file: FileId(2),
1369            target_file: FileId(3),
1370        };
1371
1372        let cached = CachedResolvedReplacedModuleTarget::from_resolved(resolved, &key_by_file_id)
1373            .expect("both file ids should map to stable keys");
1374        let restored = cached
1375            .into_resolved(&id_by_key)
1376            .expect("both stable keys should map to current file ids");
1377
1378        assert_eq!(
1379            restored,
1380            ResolvedReplacedModuleTarget {
1381                source_file: FileId(8),
1382                target_file: FileId(9),
1383            }
1384        );
1385    }
1386
1387    #[test]
1388    fn cache_resolved_project_rejects_unknown_replacement_targets() {
1389        let files = vec![file(0, "/project/src/example.test.ts")];
1390        let project = ResolvedProject {
1391            modules: vec![ResolvedModule {
1392                file_id: FileId(0),
1393                path: PathBuf::from("/project/src/example.test.ts"),
1394                ..ResolvedModule::default()
1395            }],
1396            replaced_module_targets: vec![ResolvedReplacedModuleTarget {
1397                source_file: FileId(0),
1398                target_file: FileId(1),
1399            }],
1400            ..ResolvedProject::default()
1401        };
1402
1403        let cached = cache_resolved_project(Path::new("/project"), &files, &project);
1404
1405        assert!(cached.is_none());
1406    }
1407
1408    #[test]
1409    fn manifest_misses_on_content_change() {
1410        let files = vec![file(0, "/project/src/a.ts")];
1411        let cached_map = content_hashes(&[("/project/src/a.ts", 10)]);
1412        let current_map = content_hashes(&[("/project/src/a.ts", 11)]);
1413
1414        let cached = manifest(&files, mode(), &cached_map);
1415        let current = manifest(&files, mode(), &current_map);
1416
1417        assert!(!cached.matches_inputs(&current));
1418    }
1419
1420    #[test]
1421    fn manifest_misses_on_file_deletion() {
1422        let before = vec![
1423            file(0, "/project/src/a.ts"),
1424            file(1, "/project/src/deleted.ts"),
1425        ];
1426        let after = vec![file(0, "/project/src/a.ts")];
1427        let map = content_hashes(&[("/project/src/a.ts", 10), ("/project/src/deleted.ts", 20)]);
1428
1429        let cached = manifest(&before, mode(), &map);
1430        let current = manifest(&after, mode(), &map);
1431
1432        assert!(!cached.matches_inputs(&current));
1433    }
1434
1435    #[test]
1436    fn manifest_misses_on_file_rename_with_same_content() {
1437        let before = vec![file(0, "/project/src/old.ts")];
1438        let after = vec![file(0, "/project/src/new.ts")];
1439        let map = content_hashes(&[("/project/src/old.ts", 10), ("/project/src/new.ts", 10)]);
1440
1441        let cached = manifest(&before, mode(), &map);
1442        let current = manifest(&after, mode(), &map);
1443
1444        assert!(!cached.matches_inputs(&current));
1445    }
1446
1447    #[test]
1448    fn manifest_misses_on_workspace_scoped_file_set() {
1449        let full_project = vec![
1450            file(0, "/project/packages/app/src/index.ts"),
1451            file(1, "/project/packages/shared/src/index.ts"),
1452        ];
1453        let workspace_scoped = vec![file(0, "/project/packages/app/src/index.ts")];
1454        let map = content_hashes(&[
1455            ("/project/packages/app/src/index.ts", 10),
1456            ("/project/packages/shared/src/index.ts", 20),
1457        ]);
1458
1459        let cached = manifest(&full_project, mode(), &map);
1460        let current = manifest(&workspace_scoped, mode(), &map);
1461
1462        assert!(!cached.matches_inputs(&current));
1463        assert_eq!(
1464            cached.classify_resolution_mismatch(&current),
1465            Some(CacheRejection::FileSetChanged)
1466        );
1467    }
1468
1469    #[test]
1470    fn manifest_misses_on_mode_change() {
1471        let files = vec![file(0, "/project/src/a.ts")];
1472        let map = content_hashes(&[("/project/src/a.ts", 10)]);
1473
1474        let cached = manifest(&files, mode(), &map);
1475        let current = manifest(&files, GraphCacheMode::new(1, 99, 3), &map);
1476
1477        assert!(!cached.matches_inputs(&current));
1478    }
1479
1480    #[test]
1481    fn manifest_misses_on_version_change() {
1482        let files = vec![file(0, "/project/src/a.ts")];
1483        let map = content_hashes(&[("/project/src/a.ts", 10)]);
1484        let mut cached = manifest(&files, mode(), &map);
1485        let current = manifest(&files, mode(), &map);
1486
1487        cached.version = GRAPH_CACHE_VERSION + 1;
1488
1489        assert!(!cached.matches_inputs(&current));
1490    }
1491}