Skip to main content

fallow_graph/cache/
mod.rs

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