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