fallow-core 3.50.0

Internal detector backend for fallow-engine and fallow-api
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
//! Correctness gate for the persisted graph cache.
//!
//! The persisted graph cache (`crate::cache`, gated on `no_cache == false`)
//! loads a previously-built `ModuleGraph` from `.fallow/graph-cache.bin` and
//! skips the graph build when the file set + fingerprints + graph-affecting
//! options are byte-identical. The non-negotiable invariant is TRANSPARENCY: a
//! cache hit must produce identical analysis results to a cold build. These
//! tests run each fixture cold (clean cache, persists) then warm (loads) and
//! assert the full `AnalysisResults` is identical.
//!
//! The edit cases (source edits, renames, options, manifests, install state)
//! live in the cache model tests of `fallow-engine`
//! (`crates/engine/tests/integration/cache_model`). Those tests compare each
//! warm run with a cache-free run over generated edit sequences, and check
//! that the graph cache key covers each path that import resolution reads.

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};

/// Run the same fixture cold (clean cache) then warm (cache present) and assert
/// the full results are byte-identical. The cold run persists `graph-cache.bin`;
/// the warm run loads it and skips the graph build.
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);

    // Cache dir lives OUTSIDE the project root so it is not itself an analyzed
    // source tree; the graph cache writes `graph-cache.bin` here.
    let cache_dir = temp.path().join("cache");

    let config = create_config_with_cache(root, cache_dir.clone());

    // Cold: no cache exists yet, graph is built fresh and persisted.
    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"
    );

    // Warm: graph-cache.bin exists; the graph build is skipped and the cached
    // graph is loaded (with namespace_imported reconstructed).
    let warm = fallow_core::analyze(&config).expect("warm analysis succeeds");

    // Full structural equality: serialize both and compare every issue vec.
    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)
    })
}

/// The manifest hashes per `FileId`, mirroring what the analysis path feeds
/// the manifest. Parsing without a cache is what the production builder gets
/// from the parse stage it runs anyway.
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() {
    // Exercises `import * as ns` so the `namespace_imported` reconstruction on
    // cache load is on the path.
    assert_cold_warm_identical("namespace-imports");
}

#[test]
fn barrel_exports_cold_vs_warm_identical() {
    // Exercises re-export chains + reachability + unused exports.
    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() {
    // Exercises cross-package member crediting (ExportSymbol.members round-trip).
    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
    );
}

/// An edit that keeps every import statement keeps the resolver payload: the
/// warm run resolves no specifier, builds the graph again from the edited
/// modules, and still names the reason that the persisted graph was refused.
/// An edit of an import statement resolves the imports again.
#[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"
    );
}

/// Force the resolver-payload reuse path: the manifest still passes
/// `classify_resolution_mismatch` while the persisted graph is unusable, so the
/// graph is rebuilt from the cached `ResolvedProject` alone. Every import field
/// the graph reads must survive that mirror, so the rebuilt output has to match
/// the cold output exactly.
#[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(&current),
        "shifted FileIds must not trust the persisted graph"
    );
    assert!(
        store
            .manifest
            .classify_resolution_mismatch(&current)
            .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
    );
}

/// A cached graph whose module paths differ from the discovered files must not
/// be reused. The manifest still matches, so only a check of the graph itself
/// keeps the foreign path out of the findings.
#[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"
    );
}

/// Persist a cold run, change the cached graph with `edit`, then assert that
/// the warm run rebuilds and matches 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() {
    // Issue #2375: the type-only-star flag rides on `ImportInfo`, so a graph
    // rebuilt from the cached resolver payload alone must still credit the
    // ambient `export type *` target in the type lane only.
    assert_resolver_cache_hit_matches_cold("issue-2375-ambient-type-star");
}

/// Resolve a real-world benchmark fixture path. These are gitignored symlinks
/// that may be absent on a fresh checkout, so callers skip when missing.
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)
}

/// Run a real-world benchmark fixture cold then warm and assert `total_issues`
/// is identical. Skips (does not fail) when the fixture is absent locally
/// (benchmark fixtures are gitignored symlinks). Runs in place against the
/// fixture root, writing the graph cache into an out-of-tree scratch dir so the
/// fixture is never mutated.
fn assert_benchmark_cold_warm_total(name: &str) {
    let fixture = benchmark_fixture_path(name);
    if !fixture.exists() {
        // Benchmark fixtures are gitignored symlinks that may be absent on a
        // fresh checkout: treat as a skip (silent pass) rather than a failure.
        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");
}

/// The manifest must hit on identical inputs and miss when file content or a
/// graph-affecting mode hash changes. This pins `matches_inputs` against the
/// real `from_discovered_files` shape used by the integration path.
#[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))
    );
}