use fallow_core::graph_cache::{GraphCacheFileHashes, GraphCacheManifest, GraphCacheMode};
use fallow_types::discover::FileId;
use super::common::{copy_fixture_tree, create_config_with_cache, fixture_path};
fn assert_cold_warm_identical(fixture: &str) {
let temp = tempfile::tempdir().expect("create temp dir");
let root = temp.path().join("project");
copy_fixture_tree(&fixture_path(fixture), &root);
let cache_dir = temp.path().join("cache");
let config = create_config_with_cache(root, cache_dir.clone());
let cold = fallow_core::analyze(&config).expect("cold analysis succeeds");
assert!(
cache_dir.join("graph-cache.bin").exists(),
"{fixture}: cold run must persist graph-cache.bin"
);
let warm = fallow_core::analyze(&config).expect("warm analysis succeeds");
let cold_json = serde_json::to_value(&cold).expect("serialize cold results");
let warm_json = serde_json::to_value(&warm).expect("serialize warm results");
assert_eq!(
cold_json, warm_json,
"{fixture}: warm (cache hit) results must be byte-identical to cold results"
);
assert_eq!(
cold.total_issues(),
warm.total_issues(),
"{fixture}: total issue count must match cold vs warm"
);
}
fn current_manifest_with_cached_mode(
config: &fallow_config::ResolvedConfig,
store: &fallow_core::graph_cache::GraphCacheStore,
) -> GraphCacheManifest {
let files = fallow_core::discover::discover_files(config);
let hashes = content_hashes_for(&files);
GraphCacheManifest::from_discovered_files(&config.root, &files, store.manifest.mode, |file| {
hashes
.get(file.id.0 as usize)
.copied()
.unwrap_or(GraphCacheFileHashes::NO_MODULE)
})
}
fn content_hashes_for(
files: &[fallow_types::discover::DiscoveredFile],
) -> Vec<GraphCacheFileHashes> {
let parsed = fallow_core::extract::parse_all_files(files, None, false);
let mut hashes = vec![GraphCacheFileHashes::NO_MODULE; files.len()];
for module in &parsed.modules {
if let Some(slot) = hashes.get_mut(module.file_id.0 as usize) {
*slot = GraphCacheFileHashes::of_module(module);
}
}
hashes
}
#[test]
fn namespace_imports_cold_vs_warm_identical() {
assert_cold_warm_identical("namespace-imports");
}
#[test]
fn barrel_exports_cold_vs_warm_identical() {
assert_cold_warm_identical("barrel-exports");
}
#[test]
fn effective_export_resolution_cold_vs_warm_identical() {
assert_cold_warm_identical("effective-export-explicit-shadow");
assert_cold_warm_identical("effective-export-ambiguous-star");
assert_cold_warm_identical("effective-export-ambiguous-star-partial");
assert_cold_warm_identical("effective-export-ambiguous-star-nested");
assert_cold_warm_identical("effective-export-convergent-star");
assert_cold_warm_identical("declaration-merge");
assert_cold_warm_identical("renamed-star-surface");
}
#[test]
fn cross_package_members_cold_vs_warm_identical() {
assert_cold_warm_identical("cross-package-enum-class-members");
}
#[test]
fn basic_project_cold_vs_warm_identical() {
assert_cold_warm_identical("basic-project");
}
#[test]
#[expect(
deprecated,
reason = "trace timings are still the internal contract for this cache performance gate"
)]
fn warm_graph_cache_hit_skips_import_resolution() {
let temp = tempfile::tempdir().expect("create temp dir");
let root = temp.path().join("project");
copy_fixture_tree(&fixture_path("barrel-exports"), &root);
let cache_dir = temp.path().join("cache");
let config = create_config_with_cache(root, cache_dir);
let cold = fallow_core::analyze_with_trace(&config).expect("cold analysis");
let warm = fallow_core::analyze_with_trace(&config).expect("warm analysis");
let cold_json = serde_json::to_value(&cold.results).expect("serialize cold results");
let warm_json = serde_json::to_value(&warm.results).expect("serialize warm results");
assert_eq!(
cold_json, warm_json,
"warm graph-cache hit must preserve analysis output"
);
let warm_timings = warm.timings.expect("trace timings retained");
assert!(
warm_timings.resolve_imports_ms.abs() <= f64::EPSILON,
"warm graph-cache hit must skip import resolution, got {}ms",
warm_timings.resolve_imports_ms
);
}
#[test]
#[expect(
deprecated,
reason = "trace timings are still the internal contract for this cache performance gate"
)]
fn body_edit_reuses_the_resolver_payload_and_matches_the_cache_free_run() {
let temp = tempfile::tempdir().expect("create temp dir");
let root = temp.path().join("project");
copy_fixture_tree(&fixture_path("barrel-exports"), &root);
let config = create_config_with_cache(root.clone(), temp.path().join("cache"));
let mut cache_free = create_config_with_cache(root.clone(), temp.path().join("cold-cache"));
cache_free.no_cache = true;
let entry = root.join("src/index.ts");
let original = std::fs::read_to_string(&entry).expect("read the entry file");
let cold = fallow_core::analyze_with_trace(&config).expect("cold analysis");
let cold_calls = cold
.timings
.expect("trace timings retained")
.counters
.resolve_specifier_calls;
assert!(cold_calls > 0, "the fixture must have imports to resolve");
let body_edit = original.replace("console.log(foo);", "console.log('foo');");
assert_ne!(body_edit, original, "the fixture entry must use `foo`");
std::fs::write(&entry, &body_edit).expect("edit below the imports");
let warm = fallow_core::analyze_with_trace(&config).expect("warm analysis");
let expected = fallow_core::analyze(&cache_free).expect("cache-free analysis");
assert_eq!(
serde_json::to_value(&warm.results).expect("serialize warm results"),
serde_json::to_value(&expected).expect("serialize cache-free results"),
"a run that reuses the resolver payload must match the cache-free run"
);
assert_ne!(
serde_json::to_value(&warm.results).expect("serialize warm results"),
serde_json::to_value(&cold.results).expect("serialize cold results"),
"the edit must change the result, or a stale graph would pass"
);
let warm_timings = warm.timings.expect("trace timings retained");
assert_eq!(
warm_timings.counters.resolve_specifier_calls, 0,
"an edit below the imports must not resolve a specifier again"
);
assert_eq!(
warm_timings.graph_cache_rejection,
Some(fallow_types::cache_rejection::CacheRejection::FingerprintChanged),
"the run must still name why the persisted graph was not reused"
);
let reused_cache = std::fs::read(temp.path().join("cache/graph-cache.bin"))
.expect("the run that reused the resolver payload wrote the graph cache");
let fresh = create_config_with_cache(root, temp.path().join("fresh-cache"));
fallow_core::analyze(&fresh).expect("first run with an empty cache");
let fresh_cache = std::fs::read(temp.path().join("fresh-cache/graph-cache.bin"))
.expect("the first run wrote the graph cache");
assert!(
reused_cache == fresh_cache,
"the cache written after a resolver payload reuse must equal the cache of a first run"
);
let unchanged = fallow_core::analyze_with_trace(&config).expect("run with no change");
assert_eq!(
unchanged
.timings
.expect("trace timings retained")
.graph_cache_rejection,
None,
"the next run with no change must reuse the graph"
);
std::fs::write(&entry, format!("import './missing-module';\n{original}"))
.expect("edit an import statement");
let resolved_again = fallow_core::analyze_with_trace(&config).expect("warm analysis");
let expected = fallow_core::analyze(&cache_free).expect("cache-free analysis");
assert_eq!(
serde_json::to_value(&resolved_again.results).expect("serialize warm results"),
serde_json::to_value(&expected).expect("serialize cache-free results"),
);
assert!(
resolved_again
.timings
.expect("trace timings retained")
.counters
.resolve_specifier_calls
> 0,
"an edit of an import statement must resolve the imports again"
);
}
#[expect(
deprecated,
reason = "trace timings are still the internal contract for this cache performance gate"
)]
fn assert_resolver_cache_hit_matches_cold(fixture: &str) {
let temp = tempfile::tempdir().expect("create temp dir");
let root = temp.path().join("project");
copy_fixture_tree(&fixture_path(fixture), &root);
let cache_dir = temp.path().join("cache");
let config = create_config_with_cache(root, cache_dir.clone());
let cold = fallow_core::analyze_with_trace(&config).expect("cold analysis");
let mut store = fallow_core::graph_cache::GraphCacheStore::load(&cache_dir)
.expect("persisted graph cache exists after cold run");
let current = current_manifest_with_cached_mode(&config, &store);
for file in &mut store.manifest.files {
file.file_id = FileId(file.file_id.0 + 10_000);
}
store.graph.modules_mut().clear();
store.graph.package_usage.clear();
store.graph.type_only_package_usage.clear();
store.graph.entry_points.clear();
store.graph.runtime_entry_points.clear();
store.graph.test_entry_points.clear();
store.graph.reverse_deps.clear();
assert!(
!store.manifest.matches_inputs(¤t),
"shifted FileIds must not trust the persisted graph"
);
assert!(
store
.manifest
.classify_resolution_mismatch(¤t)
.is_none(),
"stable file keys and content hashes should still allow resolver reuse"
);
store.save(fallow_types::path_guard::CacheTarget::inside(&cache_dir));
let warm = fallow_core::analyze_with_trace(&config).expect("resolver-cache analysis");
let cold_json = serde_json::to_value(&cold.results).expect("serialize cold results");
let warm_json = serde_json::to_value(&warm.results).expect("serialize warm results");
assert_eq!(
cold_json, warm_json,
"resolver-cache hit must rebuild the graph and preserve analysis output"
);
let warm_timings = warm.timings.expect("trace timings retained");
assert!(
warm_timings.resolve_imports_ms.abs() <= f64::EPSILON,
"resolver-cache hit must skip import resolution, got {}ms",
warm_timings.resolve_imports_ms
);
assert!(
warm_timings.build_graph_ms > f64::EPSILON,
"resolver-cache hit must rebuild the graph, got {}ms",
warm_timings.build_graph_ms
);
}
#[test]
fn exact_cache_hit_rebuilds_when_a_module_path_is_outside_the_root() {
let temp = tempfile::tempdir().expect("create temp dir");
let root = temp.path().join("project");
copy_fixture_tree(&fixture_path("basic-project"), &root);
let cache_dir = temp.path().join("cache");
let outside = temp.path().join("elsewhere").join("other.ts");
let config = create_config_with_cache(root, cache_dir.clone());
let cold = fallow_core::analyze(&config).expect("cold analysis");
let mut store = fallow_core::graph_cache::GraphCacheStore::load(&cache_dir)
.expect("persisted graph cache exists after cold run");
for module in store.graph.modules_mut() {
module.path.clone_from(&outside);
}
store.save(fallow_types::path_guard::CacheTarget::inside(&cache_dir));
let warm = fallow_core::analyze(&config).expect("warm analysis");
let warm_json = serde_json::to_string(&warm).expect("serialize warm results");
assert!(
!warm_json.contains("elsewhere"),
"a cached module path outside the root must not reach the findings"
);
assert_eq!(
serde_json::to_value(&cold).expect("serialize cold results"),
serde_json::to_value(&warm).expect("serialize warm results"),
"a rejected graph cache must rebuild to the cold results"
);
}
fn assert_edited_cache_rebuilds(edit: impl FnOnce(&mut fallow_core::graph::ModuleGraph)) {
let temp = tempfile::tempdir().expect("create temp dir");
let root = temp.path().join("project");
copy_fixture_tree(&fixture_path("basic-project"), &root);
let cache_dir = temp.path().join("cache");
let config = create_config_with_cache(root, cache_dir.clone());
let cold = fallow_core::analyze(&config).expect("cold analysis");
let mut store = fallow_core::graph_cache::GraphCacheStore::load(&cache_dir)
.expect("persisted graph cache exists after cold run");
edit(&mut store.graph);
store.save(fallow_types::path_guard::CacheTarget::inside(&cache_dir));
let warm = fallow_core::analyze(&config).expect("warm analysis");
assert_eq!(
serde_json::to_value(&cold).expect("serialize cold results"),
serde_json::to_value(&warm).expect("serialize warm results"),
"an edited graph cache must rebuild to the cold results"
);
}
#[test]
fn exact_cache_hit_rebuilds_when_one_module_path_changes() {
assert_edited_cache_rebuilds(|graph| {
let modules = graph.modules_mut();
let last = modules.len() - 1;
modules[last].path = modules[last].path.with_file_name("other.ts");
});
}
#[test]
fn exact_cache_hit_rebuilds_when_two_inside_paths_swap() {
assert_edited_cache_rebuilds(|graph| {
let modules = graph.modules_mut();
let (first, second) = (modules[0].path.clone(), modules[1].path.clone());
modules[0].path = second;
modules[1].path = first;
});
}
#[test]
fn resolver_cache_hit_rebuilds_graph_when_file_ids_shift() {
assert_resolver_cache_hit_matches_cold("barrel-exports");
}
#[test]
fn resolver_cache_hit_preserves_ambient_type_only_star_lane() {
assert_resolver_cache_hit_matches_cold("issue-2375-ambient-type-star");
}
fn benchmark_fixture_path(name: &str) -> std::path::PathBuf {
std::path::PathBuf::from(
std::env::var_os("CARGO_MANIFEST_DIR").expect("cargo sets CARGO_MANIFEST_DIR"),
)
.parent()
.unwrap()
.parent()
.unwrap()
.join("benchmarks")
.join("fixtures")
.join("real-world")
.join(name)
}
fn assert_benchmark_cold_warm_total(name: &str) {
let fixture = benchmark_fixture_path(name);
if !fixture.exists() {
return;
}
let cache = tempfile::tempdir().expect("create temp cache dir");
let config = create_config_with_cache(fixture, cache.path().to_path_buf());
let cold = fallow_core::analyze(&config).expect("cold benchmark analysis");
assert!(
cache.path().join("graph-cache.bin").exists(),
"{name}: cold run must persist graph-cache.bin"
);
let warm = fallow_core::analyze(&config).expect("warm benchmark analysis");
assert_eq!(
cold.total_issues(),
warm.total_issues(),
"{name}: total_issues must be identical cold vs warm"
);
}
#[test]
fn benchmark_preact_cold_vs_warm_total_identical() {
assert_benchmark_cold_warm_total("preact");
}
#[test]
fn benchmark_zod_cold_vs_warm_total_identical() {
assert_benchmark_cold_warm_total("zod");
}
#[test]
fn manifest_matches_only_on_identical_inputs() {
let temp = tempfile::tempdir().expect("create temp dir");
let root = temp.path().join("project");
copy_fixture_tree(&fixture_path("namespace-imports"), &root);
let config = create_config_with_cache(root, temp.path().join("cache"));
let files = fallow_core::discover::discover_files(&config);
let hashes = content_hashes_for(&files);
let content_hash_provider = |file: &fallow_types::discover::DiscoveredFile| {
hashes
.get(file.id.0 as usize)
.copied()
.unwrap_or(GraphCacheFileHashes::NO_MODULE)
};
let manifest_a = GraphCacheManifest::from_discovered_files(
&config.root,
&files,
GraphCacheMode::new(1, 2, 3),
content_hash_provider,
);
let manifest_same = GraphCacheManifest::from_discovered_files(
&config.root,
&files,
GraphCacheMode::new(1, 2, 3),
content_hash_provider,
);
let manifest_other_mode = GraphCacheManifest::from_discovered_files(
&config.root,
&files,
GraphCacheMode::new(1, 99, 3),
content_hash_provider,
);
assert!(manifest_a.matches_inputs(&manifest_same));
assert!(!manifest_a.matches_inputs(&manifest_other_mode));
}
#[test]
fn a_graph_cache_from_another_root_never_reuses_original_checkout_paths() {
let temp = tempfile::tempdir().expect("temp root");
let original = temp.path().join("original");
let relocated = temp.path().join("relocated");
let cache = temp.path().join("cache");
std::fs::create_dir_all(original.join("src")).unwrap();
std::fs::write(
original.join("package.json"),
r#"{"name":"relocation","main":"src/index.ts"}"#,
)
.unwrap();
std::fs::write(
original.join("src/index.ts"),
"import { used } from './lib'; console.log(used);\n",
)
.unwrap();
std::fs::write(
original.join("src/lib.ts"),
"export const used = 1; export const unused = 2;\n",
)
.unwrap();
let original_config = create_config_with_cache(original.clone(), cache.clone());
fallow_core::analyze(&original_config).expect("prime original cache");
copy_fixture_tree(&original, &relocated);
let mut relocated_config = create_config_with_cache(relocated.clone(), cache);
let warm = fallow_core::analyze(&relocated_config).expect("relocated warm analysis");
relocated_config.no_cache = true;
let cold = fallow_core::analyze(&relocated_config).expect("relocated uncached analysis");
assert_eq!(format!("{warm:#?}"), format!("{cold:#?}"));
assert!(
warm.unused_exports
.iter()
.all(|finding| finding.export.path.starts_with(&relocated))
);
}