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