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 = 69;
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}
405
406/// Convert a resolved project into the compact graph-cache resolver payload.
407#[must_use]
408pub fn cache_resolved_project(
409    root: &Path,
410    files: &[DiscoveredFile],
411    resolved: &ResolvedProject,
412) -> Option<CachedResolvedProject> {
413    let key_by_file_id = stable_key_by_file_id(root, files);
414    let modules = resolved
415        .modules
416        .iter()
417        .map(|module| CachedResolvedModule::from_resolved(module, &key_by_file_id))
418        .collect::<Option<Vec<_>>>()?;
419    let replaced_module_targets = resolved
420        .replaced_module_targets
421        .iter()
422        .copied()
423        .map(|target| CachedResolvedReplacedModuleTarget::from_resolved(target, &key_by_file_id))
424        .collect::<Option<Vec<_>>>()?;
425    Some(CachedResolvedProject {
426        modules,
427        replaced_module_targets,
428    })
429}
430
431/// Restore a resolved project from cached resolver payloads and current parsed modules.
432///
433/// Returns `None` if the payload no longer aligns with the current parse result.
434/// A normal graph-cache manifest hit should keep these aligned; this extra check
435/// keeps corrupt or hand-edited cache files on the safe miss path.
436#[must_use]
437pub fn restore_resolved_project(
438    root: &Path,
439    modules: &[fallow_types::extract::ModuleInfo],
440    files: &[DiscoveredFile],
441    cached: &CachedResolvedProject,
442) -> Option<ResolvedProject> {
443    if modules.len() != cached.modules.len() {
444        return None;
445    }
446
447    let mut indexes = RestoreResolvedModuleIndexes::new(root, modules, files);
448    let resolved_modules = cached
449        .modules
450        .iter()
451        .map(|entry| restore_cached_resolved_module(entry, &mut indexes))
452        .collect::<Option<Vec<_>>>()?;
453    let mut replaced_module_targets = cached
454        .replaced_module_targets
455        .iter()
456        .cloned()
457        .map(|target| target.into_resolved(&indexes.file_ids))
458        .collect::<Option<Vec<_>>>()?;
459    replaced_module_targets
460        .sort_unstable_by_key(|target| (target.source_file.0, target.target_file.0));
461    replaced_module_targets.dedup();
462    Some(ResolvedProject {
463        modules: resolved_modules,
464        replaced_module_targets,
465        work: crate::resolve::ResolveWork::default(),
466    })
467}
468
469struct RestoreResolvedModuleIndexes<'a> {
470    file_ids: rustc_hash::FxHashMap<StableFileKey, FileId>,
471    modules: rustc_hash::FxHashMap<StableFileKey, &'a fallow_types::extract::ModuleInfo>,
472    paths: rustc_hash::FxHashMap<StableFileKey, std::path::PathBuf>,
473}
474
475impl<'a> RestoreResolvedModuleIndexes<'a> {
476    fn new(
477        root: &Path,
478        modules: &'a [fallow_types::extract::ModuleInfo],
479        files: &[DiscoveredFile],
480    ) -> Self {
481        let key_by_file_id = stable_key_by_file_id(root, files);
482        let id_by_key: rustc_hash::FxHashMap<_, _> = key_by_file_id
483            .iter()
484            .map(|(file_id, key)| (key.clone(), *file_id))
485            .collect();
486        let by_key: rustc_hash::FxHashMap<_, _> = modules
487            .iter()
488            .filter_map(|module| {
489                key_by_file_id
490                    .get(&module.file_id)
491                    .map(|key| (key.clone(), module))
492            })
493            .collect();
494        let path_by_key: rustc_hash::FxHashMap<_, _> = files
495            .iter()
496            .map(|file| {
497                (
498                    StableFileKey::from_root_relative(root, &file.path),
499                    file.path.clone(),
500                )
501            })
502            .collect();
503
504        Self {
505            file_ids: id_by_key,
506            modules: by_key,
507            paths: path_by_key,
508        }
509    }
510}
511
512fn restore_cached_resolved_module(
513    entry: &CachedResolvedModule,
514    indexes: &mut RestoreResolvedModuleIndexes<'_>,
515) -> Option<ResolvedModule> {
516    let module = indexes.modules.remove(&entry.key)?;
517    let path = indexes.paths.get(&entry.key)?.clone();
518    let resolved_dynamic_pattern_targets =
519        restore_dynamic_pattern_targets(entry, module, &indexes.file_ids)?;
520
521    Some(ResolvedModule {
522        file_id: module.file_id,
523        path,
524        exports: Arc::clone(&module.exports),
525        re_exports: entry
526            .re_exports
527            .iter()
528            .cloned()
529            .map(|re_export| re_export.into_resolved(&indexes.file_ids))
530            .collect::<Option<Vec<_>>>()?,
531        resolved_imports: entry
532            .resolved_imports
533            .iter()
534            .cloned()
535            .map(|import| import.into_resolved(&indexes.file_ids))
536            .collect::<Option<Vec<_>>>()?,
537        resolved_dynamic_imports: entry
538            .resolved_dynamic_imports
539            .iter()
540            .cloned()
541            .map(|import| import.into_resolved(&indexes.file_ids))
542            .collect::<Option<Vec<_>>>()?,
543        resolved_dynamic_patterns: module
544            .dynamic_import_patterns
545            .iter()
546            .cloned()
547            .zip(resolved_dynamic_pattern_targets)
548            .collect(),
549        member_accesses: Arc::clone(&module.member_accesses),
550        semantic_facts: Arc::clone(&module.semantic_facts),
551        whole_object_uses: Arc::clone(&module.whole_object_uses),
552        has_cjs_exports: module.has_cjs_exports,
553        has_angular_component_template_url: module.has_angular_component_template_url,
554        unused_import_bindings: module.unused_import_bindings.iter().cloned().collect(),
555        type_referenced_import_bindings: module.type_referenced_import_bindings.clone(),
556        value_referenced_import_bindings: module.value_referenced_import_bindings.clone(),
557        namespace_object_aliases: module.namespace_object_aliases.clone(),
558        exported_factory_returns: Arc::clone(&module.exported_factory_returns),
559        exported_factory_return_object_shapes: Arc::clone(
560            &module.exported_factory_return_object_shapes,
561        ),
562        type_member_types: Arc::clone(&module.type_member_types),
563        missing_export_targets: entry.missing_export_targets.clone(),
564    })
565}
566
567fn restore_dynamic_pattern_targets(
568    entry: &CachedResolvedModule,
569    module: &fallow_types::extract::ModuleInfo,
570    id_by_key: &rustc_hash::FxHashMap<StableFileKey, FileId>,
571) -> Option<Vec<Vec<FileId>>> {
572    if entry.resolved_dynamic_pattern_targets.len() != module.dynamic_import_patterns.len() {
573        return None;
574    }
575    entry
576        .resolved_dynamic_pattern_targets
577        .iter()
578        .map(|targets| {
579            targets
580                .iter()
581                .map(|key| id_by_key.get(key).copied())
582                .collect::<Option<Vec<_>>>()
583        })
584        .collect()
585}
586
587fn stable_key_by_file_id(
588    root: &Path,
589    files: &[DiscoveredFile],
590) -> rustc_hash::FxHashMap<FileId, StableFileKey> {
591    files
592        .iter()
593        .map(|file| (file.id, StableFileKey::from_root_relative(root, &file.path)))
594        .collect()
595}
596
597fn span_to_pair(span: Span) -> [u32; 2] {
598    [span.start, span.end]
599}
600
601fn pair_to_span(pair: [u32; 2]) -> Span {
602    Span::new(pair[0], pair[1])
603}
604
605/// Serialize an [`oxc_span::Span`] as a `[start, end]` `u32` pair.
606///
607/// `oxc_span::Span` does not enable its own serde feature in this workspace, so
608/// the graph types that carry spans route them through this module via
609/// `#[serde(with = "crate::cache::span_serde")]`. A 2-element array keeps the
610/// postcard encoding compact (two varints) and is trivially lossless: a `Span`
611/// is fully described by its `start` / `end` offsets.
612pub(crate) mod span_serde {
613    use oxc_span::Span;
614    use serde::{Deserialize, Deserializer, Serialize, Serializer};
615
616    #[expect(
617        clippy::trivially_copy_pass_by_ref,
618        reason = "serde `serialize_with` / `with` requires a `&T` signature"
619    )]
620    pub fn serialize<S: Serializer>(span: &Span, serializer: S) -> Result<S::Ok, S::Error> {
621        [span.start, span.end].serialize(serializer)
622    }
623
624    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Span, D::Error> {
625        let [start, end] = <[u32; 2]>::deserialize(deserializer)?;
626        Ok(Span::new(start, end))
627    }
628}
629
630/// Lossless cache (de)serialization for `Vec<MemberInfo>`.
631///
632/// `fallow_types::extract::MemberInfo` derives only `serde::Serialize`, and its
633/// `span` field uses `serialize_with` with no matching deserializer, so it
634/// cannot be deserialized through a plain derive. Rather than change the shared
635/// type's serde shape (which would ripple into JSON output), the cache mirrors
636/// it field-for-field into a dedicated `CachedMemberInfo` and converts both
637/// ways. Every `MemberInfo` field is carried, so the round-trip is lossless.
638pub(crate) mod member_serde {
639    use fallow_types::extract::{MemberInfo, MemberKind};
640    use oxc_span::Span;
641    use serde::{Deserialize, Deserializer, Serialize, Serializer};
642
643    #[derive(Serialize, Deserialize)]
644    struct CachedMemberInfo {
645        name: String,
646        kind: MemberKind,
647        span: [u32; 2],
648        has_decorator: bool,
649        decorator_names: Vec<String>,
650        is_instance_returning_static: bool,
651        is_self_returning: bool,
652    }
653
654    impl From<&MemberInfo> for CachedMemberInfo {
655        fn from(member: &MemberInfo) -> Self {
656            Self {
657                name: member.name.clone(),
658                kind: member.kind,
659                span: [member.span.start, member.span.end],
660                has_decorator: member.has_decorator,
661                decorator_names: member.decorator_names.clone(),
662                is_instance_returning_static: member.is_instance_returning_static,
663                is_self_returning: member.is_self_returning,
664            }
665        }
666    }
667
668    impl From<CachedMemberInfo> for MemberInfo {
669        fn from(cached: CachedMemberInfo) -> Self {
670            Self {
671                name: cached.name,
672                kind: cached.kind,
673                span: Span::new(cached.span[0], cached.span[1]),
674                has_decorator: cached.has_decorator,
675                decorator_names: cached.decorator_names,
676                is_instance_returning_static: cached.is_instance_returning_static,
677                is_self_returning: cached.is_self_returning,
678            }
679        }
680    }
681
682    pub fn serialize<S: Serializer>(
683        members: &[MemberInfo],
684        serializer: S,
685    ) -> Result<S::Ok, S::Error> {
686        let mirror: Vec<CachedMemberInfo> = members.iter().map(CachedMemberInfo::from).collect();
687        mirror.serialize(serializer)
688    }
689
690    pub fn deserialize<'de, D: Deserializer<'de>>(
691        deserializer: D,
692    ) -> Result<Vec<MemberInfo>, D::Error> {
693        let mirror = Vec::<CachedMemberInfo>::deserialize(deserializer)?;
694        Ok(mirror.into_iter().map(MemberInfo::from).collect())
695    }
696}
697
698/// Option dimensions that affect graph construction.
699///
700/// The hashes are intentionally opaque to this crate. Callers decide which
701/// resolver/plugin/entry-point inputs feed each hash, while this contract keeps
702/// graph-cache validation explicit and typed.
703#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
704pub struct GraphCacheMode {
705    /// Import resolver and tsconfig-relevant options.
706    pub resolver_options_hash: u64,
707    /// Entry point set and reachability root options.
708    pub entry_points_hash: u64,
709    /// Plugin-derived graph-affecting configuration.
710    pub plugin_config_hash: u64,
711}
712
713impl GraphCacheMode {
714    /// Build a mode from explicit hash dimensions.
715    #[must_use]
716    pub const fn new(
717        resolver_options_hash: u64,
718        entry_points_hash: u64,
719        plugin_config_hash: u64,
720    ) -> Self {
721        Self {
722            resolver_options_hash,
723            entry_points_hash,
724            plugin_config_hash,
725        }
726    }
727}
728
729/// Source freshness for one file in a graph-cache manifest.
730#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
731pub struct GraphCacheFile {
732    /// Persistable identity for the file.
733    pub key: StableFileKey,
734    /// Current in-memory identifier for the file.
735    ///
736    /// The stable key is the durable identity, but the persisted `ModuleGraph`
737    /// is still `FileId`-keyed. Until a future graph-cache format remaps graph
738    /// edges through stable keys, a changed assignment must miss rather than
739    /// trust a graph whose `modules[file_id]` indexes point at different files.
740    pub file_id: FileId,
741    /// xxh3 hash of the parsed source content.
742    ///
743    /// Content, not `(mtime, size)`: the metadata pair is writer-controlled and
744    /// a same-length rewrite with a restored mtime leaves it unchanged, so a
745    /// metadata-keyed manifest can hand back the previous run's graph for a
746    /// tree that no longer matches it. The hash is free here because the parse
747    /// stage already computed it, and unlike a ctime it survives `cp -Rp` and
748    /// CI cache restores, which is what makes a warm graph reusable across
749    /// checkouts at all.
750    ///
751    /// `0` when the run produced no module for the file (an unreadable source).
752    pub content_hash: u64,
753}
754
755impl GraphCacheFile {
756    /// Build a graph-cache file row from a discovered file and content hash.
757    #[must_use]
758    fn from_discovered_file(root: &Path, file: &DiscoveredFile, content_hash: u64) -> Self {
759        Self {
760            key: StableFileKey::from_root_relative(root, &file.path),
761            file_id: file.id,
762            content_hash,
763        }
764    }
765}
766
767/// Manifest inputs required to trust a persisted graph cache entry.
768#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
769pub struct GraphCacheManifest {
770    /// Root anchoring the absolute paths retained in the graph and resolver payload.
771    pub root: PathBuf,
772    /// Schema version used by the persisted graph-cache entry.
773    pub version: u32,
774    /// Graph-affecting option dimensions.
775    pub mode: GraphCacheMode,
776    /// Stable file identities, current FileId assignments, and freshness metadata.
777    pub files: Vec<GraphCacheFile>,
778}
779
780impl GraphCacheManifest {
781    /// Build a manifest and sort files by stable key for deterministic compare.
782    #[must_use]
783    fn new(root: &Path, mode: GraphCacheMode, mut files: Vec<GraphCacheFile>) -> Self {
784        sort_files(&mut files);
785        Self {
786            root: root.to_path_buf(),
787            version: GRAPH_CACHE_VERSION,
788            mode,
789            files,
790        }
791    }
792
793    /// Build a manifest from discovered files plus a content-hash provider.
794    pub fn from_discovered_files(
795        root: &Path,
796        files: &[DiscoveredFile],
797        mode: GraphCacheMode,
798        mut content_hash_for_file: impl FnMut(&DiscoveredFile) -> u64,
799    ) -> Self {
800        let rows = files
801            .iter()
802            .map(|file| {
803                GraphCacheFile::from_discovered_file(root, file, content_hash_for_file(file))
804            })
805            .collect();
806        Self::new(root, mode, rows)
807    }
808
809    /// True when a persisted manifest matches the current graph inputs.
810    #[must_use]
811    pub fn matches_inputs(&self, current: &Self) -> bool {
812        self.version == GRAPH_CACHE_VERSION
813            && current.version == GRAPH_CACHE_VERSION
814            && self.root == current.root
815            && self.mode == current.mode
816            && self.files == current.files
817    }
818
819    /// Name the first input dimension that differs from the current run, for
820    /// a manifest whose resolution inputs may differ from the current run.
821    ///
822    /// The caller decides graph reuse after a successful, fully paid load, so
823    /// this is the most expensive refusal in the pipeline and used to be the
824    /// only silent one. `None` means the resolution inputs actually match and
825    /// the caller should not be asking.
826    #[must_use]
827    pub fn classify_resolution_mismatch(&self, current: &Self) -> Option<CacheRejection> {
828        if self.version != GRAPH_CACHE_VERSION || current.version != GRAPH_CACHE_VERSION {
829            return Some(CacheRejection::VersionMismatch);
830        }
831        if self.root != current.root {
832            return Some(CacheRejection::RootMismatch);
833        }
834        if self.mode != current.mode {
835            return Some(CacheRejection::ModeMismatch);
836        }
837        if self.files.len() != current.files.len()
838            || self
839                .files
840                .iter()
841                .zip(current.files.iter())
842                .any(|(cached, current)| cached.key != current.key)
843        {
844            return Some(CacheRejection::FileSetChanged);
845        }
846        self.files
847            .iter()
848            .zip(current.files.iter())
849            .any(|(cached, current)| cached.content_hash != current.content_hash)
850            .then_some(CacheRejection::FingerprintChanged)
851    }
852}
853
854fn sort_files(files: &mut [GraphCacheFile]) {
855    files.sort_unstable_by(|a, b| a.key.cmp(&b.key));
856}
857
858#[cfg(test)]
859mod tests {
860    use std::path::{Path, PathBuf};
861
862    use fallow_types::discover::FileId;
863    use fallow_types::extract::{DynamicImportPattern, ModuleInfo, ModuleLoadMechanism};
864    use rustc_hash::FxHashMap;
865
866    use super::*;
867
868    fn file(id: u32, path: &str) -> DiscoveredFile {
869        DiscoveredFile {
870            id: FileId(id),
871            path: PathBuf::from(path),
872            size_bytes: 1,
873        }
874    }
875
876    fn mode() -> GraphCacheMode {
877        GraphCacheMode::new(1, 2, 3)
878    }
879
880    fn content_hashes(pairs: &[(&str, u64)]) -> FxHashMap<PathBuf, u64> {
881        pairs
882            .iter()
883            .map(|(path, hash)| (PathBuf::from(path), *hash))
884            .collect()
885    }
886
887    fn manifest(
888        files: &[DiscoveredFile],
889        mode: GraphCacheMode,
890        map: &FxHashMap<PathBuf, u64>,
891    ) -> GraphCacheManifest {
892        GraphCacheManifest::from_discovered_files(Path::new("/project"), files, mode, |file| {
893            *map.get(&file.path).unwrap()
894        })
895    }
896
897    fn import_info(source: &str) -> ImportInfo {
898        ImportInfo {
899            source: source.to_string(),
900            imported_name: fallow_types::extract::ImportedName::SideEffect,
901            local_name: String::new(),
902            is_type_only: false,
903            is_type_only_star: false,
904            from_style: false,
905            span: Span::new(0, 0),
906            source_span: Span::new(0, 0),
907        }
908    }
909
910    #[test]
911    fn cached_import_info_round_trip_keeps_every_field() {
912        // The resolver payload is replayed into a fresh graph build, so any
913        // field the mirror drops silently changes analysis behaviour behind a
914        // cache hit. Compare the debug rendering so a future field that is not
915        // mirrored fails here instead of in a warm-only output diff.
916        let original = ImportInfo {
917            source: "./impl".to_string(),
918            imported_name: fallow_types::extract::ImportedName::Namespace,
919            local_name: "ns".to_string(),
920            is_type_only: true,
921            is_type_only_star: true,
922            from_style: true,
923            span: Span::new(3, 41),
924            source_span: Span::new(17, 25),
925        };
926
927        let restored = ImportInfo::from(CachedImportInfo::from(&original));
928
929        assert_eq!(format!("{restored:?}"), format!("{original:?}"));
930    }
931
932    #[test]
933    fn manifest_sorts_by_stable_file_key() {
934        let files = vec![file(0, "/project/src/z.ts"), file(1, "/project/src/a.ts")];
935        let map = content_hashes(&[("/project/src/z.ts", 10), ("/project/src/a.ts", 20)]);
936
937        let manifest = manifest(&files, mode(), &map);
938
939        let keys: Vec<&str> = manifest
940            .files
941            .iter()
942            .map(|file| file.key.as_str())
943            .collect();
944        assert_eq!(keys, vec!["src/a.ts", "src/z.ts"]);
945    }
946
947    #[test]
948    fn manifest_misses_on_file_id_shift_until_graph_remap_exists() {
949        let before = vec![file(0, "/project/src/a.ts"), file(1, "/project/src/c.ts")];
950        let after = vec![file(9, "/project/src/c.ts"), file(2, "/project/src/a.ts")];
951        let map = content_hashes(&[("/project/src/a.ts", 10), ("/project/src/c.ts", 20)]);
952
953        let cached = manifest(&before, mode(), &map);
954        let current = manifest(&after, mode(), &map);
955
956        assert!(
957            !cached.matches_inputs(&current),
958            "the persisted graph is still FileId-keyed, so FileId shifts cannot trust it"
959        );
960        assert_eq!(
961            cached.classify_resolution_mismatch(&current),
962            None,
963            "stable-keyed resolver payloads may be remapped across FileId shifts"
964        );
965    }
966
967    #[test]
968    fn cached_resolve_result_remaps_internal_targets_by_stable_key() {
969        let key_a = StableFileKey::from_root_relative(
970            Path::new("/project"),
971            Path::new("/project/src/a.ts"),
972        );
973        let key_b = StableFileKey::from_root_relative(
974            Path::new("/project"),
975            Path::new("/project/src/b.ts"),
976        );
977        let key_by_file_id =
978            FxHashMap::from_iter([(FileId(0), key_a.clone()), (FileId(1), key_b.clone())]);
979        let id_by_key = FxHashMap::from_iter([(key_a, FileId(7)), (key_b, FileId(9))]);
980
981        let cached = CachedResolveResult::from_resolve_result(
982            &ResolveResult::InternalPackageModule {
983                file_id: FileId(1),
984                package_name: "@scope/pkg".to_string(),
985            },
986            &key_by_file_id,
987        )
988        .expect("target file id should map to a stable key");
989
990        let restored = cached
991            .into_resolve_result(&id_by_key)
992            .expect("stable key should map to current FileId");
993
994        assert!(matches!(
995            restored,
996            ResolveResult::InternalPackageModule {
997                file_id: FileId(9),
998                ref package_name,
999            } if package_name == "@scope/pkg"
1000        ));
1001    }
1002
1003    #[test]
1004    fn cached_resolve_result_preserves_commonjs_provenance() {
1005        let key = StableFileKey::from_root_relative(
1006            Path::new("/project"),
1007            Path::new("/project/src/dependency.ts"),
1008        );
1009        let key_by_file_id = FxHashMap::from_iter([(FileId(3), key.clone())]);
1010        let id_by_key = FxHashMap::from_iter([(key, FileId(8))]);
1011
1012        let cached = CachedResolveResult::from_resolve_result(
1013            &ResolveResult::CommonJsInternalModule(FileId(3)),
1014            &key_by_file_id,
1015        )
1016        .expect("CommonJS target should map to a stable key");
1017        let restored = cached
1018            .into_resolve_result(&id_by_key)
1019            .expect("stable key should map to the current FileId");
1020
1021        assert!(matches!(
1022            restored,
1023            ResolveResult::CommonJsInternalModule(FileId(8))
1024        ));
1025    }
1026
1027    #[test]
1028    fn cached_resolve_result_preserves_commonjs_bare_package_provenance() {
1029        let cached = CachedResolveResult::from_resolve_result(
1030            &ResolveResult::CommonJsNpmPackage("shared-package".to_string()),
1031            &FxHashMap::default(),
1032        )
1033        .expect("bare CommonJS package should not need a stable file key");
1034        let restored = cached
1035            .into_resolve_result(&FxHashMap::default())
1036            .expect("bare CommonJS package should restore without a file map");
1037
1038        assert!(matches!(
1039            restored,
1040            ResolveResult::CommonJsNpmPackage(package_name)
1041                if package_name == "shared-package"
1042        ));
1043    }
1044
1045    #[test]
1046    fn cache_resolved_project_rejects_unknown_internal_targets() {
1047        let files = vec![file(0, "/project/src/a.ts")];
1048        let module = ResolvedModule {
1049            file_id: FileId(0),
1050            path: PathBuf::from("/project/src/a.ts"),
1051            resolved_imports: vec![ResolvedImport {
1052                info: import_info("./missing"),
1053                target: ResolveResult::InternalModule(FileId(1)),
1054            }],
1055            ..ResolvedModule::default()
1056        };
1057        let project = ResolvedProject {
1058            modules: vec![module],
1059            replaced_module_targets: Vec::new(),
1060            ..ResolvedProject::default()
1061        };
1062
1063        let cached = cache_resolved_project(Path::new("/project"), &files, &project);
1064
1065        assert!(cached.is_none());
1066    }
1067
1068    #[test]
1069    fn cached_dynamic_pattern_targets_preserve_empty_rows() {
1070        let files = vec![file(0, "/project/src/app.ts")];
1071        let pattern = DynamicImportPattern {
1072            prefix: "./missing/".into(),
1073            suffix: Some(".ts".into()),
1074            span: Span::new(0, 1),
1075            mechanism: ModuleLoadMechanism::EsModule,
1076        };
1077        let module = ModuleInfo {
1078            dynamic_import_patterns: vec![pattern.clone()],
1079            ..ModuleInfo::empty(FileId(0))
1080        };
1081        let resolved = ResolvedProject {
1082            modules: vec![ResolvedModule {
1083                file_id: FileId(0),
1084                path: PathBuf::from("/project/src/app.ts"),
1085                resolved_dynamic_patterns: vec![(pattern, Vec::new())],
1086                ..ResolvedModule::default()
1087            }],
1088            replaced_module_targets: Vec::new(),
1089            ..ResolvedProject::default()
1090        };
1091
1092        let cached = cache_resolved_project(Path::new("/project"), &files, &resolved)
1093            .expect("all dynamic pattern targets should have stable keys");
1094        let restored = restore_resolved_project(
1095            Path::new("/project"),
1096            std::slice::from_ref(&module),
1097            &files,
1098            &cached,
1099        )
1100        .expect("cached dynamic pattern rows should align with extracted patterns");
1101
1102        assert_eq!(restored.modules[0].resolved_dynamic_patterns.len(), 1);
1103        assert!(
1104            restored.modules[0].resolved_dynamic_patterns[0]
1105                .1
1106                .is_empty()
1107        );
1108
1109        let mut sparse_cached = cached;
1110        sparse_cached.modules[0]
1111            .resolved_dynamic_pattern_targets
1112            .clear();
1113        assert!(
1114            restore_resolved_project(
1115                Path::new("/project"),
1116                std::slice::from_ref(&module),
1117                &files,
1118                &sparse_cached,
1119            )
1120            .is_none(),
1121            "version-50 sparse rows must take the safe cache-miss path"
1122        );
1123    }
1124
1125    #[test]
1126    fn cached_replaced_target_remaps_both_file_ids_by_stable_key() {
1127        let source_key = StableFileKey::from_root_relative(
1128            Path::new("/project"),
1129            Path::new("/project/src/example.test.ts"),
1130        );
1131        let target_key = StableFileKey::from_root_relative(
1132            Path::new("/project"),
1133            Path::new("/project/src/dependency.ts"),
1134        );
1135        let key_by_file_id = FxHashMap::from_iter([
1136            (FileId(2), source_key.clone()),
1137            (FileId(3), target_key.clone()),
1138        ]);
1139        let id_by_key = FxHashMap::from_iter([(source_key, FileId(8)), (target_key, FileId(9))]);
1140        let resolved = ResolvedReplacedModuleTarget {
1141            source_file: FileId(2),
1142            target_file: FileId(3),
1143        };
1144
1145        let cached = CachedResolvedReplacedModuleTarget::from_resolved(resolved, &key_by_file_id)
1146            .expect("both file ids should map to stable keys");
1147        let restored = cached
1148            .into_resolved(&id_by_key)
1149            .expect("both stable keys should map to current file ids");
1150
1151        assert_eq!(
1152            restored,
1153            ResolvedReplacedModuleTarget {
1154                source_file: FileId(8),
1155                target_file: FileId(9),
1156            }
1157        );
1158    }
1159
1160    #[test]
1161    fn cache_resolved_project_rejects_unknown_replacement_targets() {
1162        let files = vec![file(0, "/project/src/example.test.ts")];
1163        let project = ResolvedProject {
1164            modules: vec![ResolvedModule {
1165                file_id: FileId(0),
1166                path: PathBuf::from("/project/src/example.test.ts"),
1167                ..ResolvedModule::default()
1168            }],
1169            replaced_module_targets: vec![ResolvedReplacedModuleTarget {
1170                source_file: FileId(0),
1171                target_file: FileId(1),
1172            }],
1173            ..ResolvedProject::default()
1174        };
1175
1176        let cached = cache_resolved_project(Path::new("/project"), &files, &project);
1177
1178        assert!(cached.is_none());
1179    }
1180
1181    #[test]
1182    fn manifest_misses_on_content_change() {
1183        let files = vec![file(0, "/project/src/a.ts")];
1184        let cached_map = content_hashes(&[("/project/src/a.ts", 10)]);
1185        let current_map = content_hashes(&[("/project/src/a.ts", 11)]);
1186
1187        let cached = manifest(&files, mode(), &cached_map);
1188        let current = manifest(&files, mode(), &current_map);
1189
1190        assert!(!cached.matches_inputs(&current));
1191    }
1192
1193    #[test]
1194    fn manifest_misses_on_file_deletion() {
1195        let before = vec![
1196            file(0, "/project/src/a.ts"),
1197            file(1, "/project/src/deleted.ts"),
1198        ];
1199        let after = vec![file(0, "/project/src/a.ts")];
1200        let map = content_hashes(&[("/project/src/a.ts", 10), ("/project/src/deleted.ts", 20)]);
1201
1202        let cached = manifest(&before, mode(), &map);
1203        let current = manifest(&after, mode(), &map);
1204
1205        assert!(!cached.matches_inputs(&current));
1206    }
1207
1208    #[test]
1209    fn manifest_misses_on_file_rename_with_same_content() {
1210        let before = vec![file(0, "/project/src/old.ts")];
1211        let after = vec![file(0, "/project/src/new.ts")];
1212        let map = content_hashes(&[("/project/src/old.ts", 10), ("/project/src/new.ts", 10)]);
1213
1214        let cached = manifest(&before, mode(), &map);
1215        let current = manifest(&after, mode(), &map);
1216
1217        assert!(!cached.matches_inputs(&current));
1218    }
1219
1220    #[test]
1221    fn manifest_misses_on_workspace_scoped_file_set() {
1222        let full_project = vec![
1223            file(0, "/project/packages/app/src/index.ts"),
1224            file(1, "/project/packages/shared/src/index.ts"),
1225        ];
1226        let workspace_scoped = vec![file(0, "/project/packages/app/src/index.ts")];
1227        let map = content_hashes(&[
1228            ("/project/packages/app/src/index.ts", 10),
1229            ("/project/packages/shared/src/index.ts", 20),
1230        ]);
1231
1232        let cached = manifest(&full_project, mode(), &map);
1233        let current = manifest(&workspace_scoped, mode(), &map);
1234
1235        assert!(!cached.matches_inputs(&current));
1236        assert_eq!(
1237            cached.classify_resolution_mismatch(&current),
1238            Some(CacheRejection::FileSetChanged)
1239        );
1240    }
1241
1242    #[test]
1243    fn manifest_misses_on_mode_change() {
1244        let files = vec![file(0, "/project/src/a.ts")];
1245        let map = content_hashes(&[("/project/src/a.ts", 10)]);
1246
1247        let cached = manifest(&files, mode(), &map);
1248        let current = manifest(&files, GraphCacheMode::new(1, 99, 3), &map);
1249
1250        assert!(!cached.matches_inputs(&current));
1251    }
1252
1253    #[test]
1254    fn manifest_misses_on_version_change() {
1255        let files = vec![file(0, "/project/src/a.ts")];
1256        let map = content_hashes(&[("/project/src/a.ts", 10)]);
1257        let mut cached = manifest(&files, mode(), &map);
1258        let current = manifest(&files, mode(), &map);
1259
1260        cached.version = GRAPH_CACHE_VERSION + 1;
1261
1262        assert!(!cached.matches_inputs(&current));
1263    }
1264}