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