@smoothbricks/nx-plugin 0.4.28 → 0.4.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/README.md +277 -89
  2. package/dist/bin/smoo-nx-test-clocks.d.ts +3 -0
  3. package/dist/bin/smoo-nx-test-clocks.d.ts.map +1 -0
  4. package/dist/bin/smoo-nx-test-clocks.js +28 -0
  5. package/dist/bounded-test-policy.d.ts +8 -8
  6. package/dist/bounded-test-policy.d.ts.map +1 -1
  7. package/dist/bounded-test-policy.js +18 -30
  8. package/dist/cargo-closure-input.d.ts +23 -0
  9. package/dist/cargo-closure-input.d.ts.map +1 -1
  10. package/dist/cargo-closure-input.js +41 -9
  11. package/dist/cargo-source-hash.d.ts.map +1 -1
  12. package/dist/cargo-source-hash.js +42 -19
  13. package/dist/ensure-built-receipt.d.ts +40 -6
  14. package/dist/ensure-built-receipt.d.ts.map +1 -1
  15. package/dist/ensure-built-receipt.js +297 -159
  16. package/dist/ensure-built-witness.d.ts +65 -4
  17. package/dist/ensure-built-witness.d.ts.map +1 -1
  18. package/dist/ensure-built-witness.js +2237 -23
  19. package/dist/ensure-built.d.ts +99 -1
  20. package/dist/ensure-built.d.ts.map +1 -1
  21. package/dist/ensure-built.js +45 -56
  22. package/dist/executors/bounded-exec/cpu-pool.d.ts +22 -7
  23. package/dist/executors/bounded-exec/cpu-pool.d.ts.map +1 -1
  24. package/dist/executors/bounded-exec/cpu-pool.js +51 -22
  25. package/dist/executors/bounded-exec/executor.d.ts +12 -3
  26. package/dist/executors/bounded-exec/executor.d.ts.map +1 -1
  27. package/dist/executors/bounded-exec/executor.js +174 -51
  28. package/dist/executors/bounded-exec/no-space.d.ts +8 -0
  29. package/dist/executors/bounded-exec/no-space.d.ts.map +1 -0
  30. package/dist/executors/bounded-exec/no-space.js +31 -0
  31. package/dist/executors/bounded-exec/ram-temp.d.ts +20 -11
  32. package/dist/executors/bounded-exec/ram-temp.d.ts.map +1 -1
  33. package/dist/executors/bounded-exec/ram-temp.js +42 -17
  34. package/dist/executors/bounded-exec/verdict.d.ts +34 -4
  35. package/dist/executors/bounded-exec/verdict.d.ts.map +1 -1
  36. package/dist/executors/bounded-exec/verdict.js +54 -3
  37. package/dist/generators/bun-test-tracing/generator.js +2 -2
  38. package/dist/graph-input-contract.d.ts +102 -0
  39. package/dist/graph-input-contract.d.ts.map +1 -0
  40. package/dist/graph-input-contract.js +637 -0
  41. package/dist/index.d.ts +12 -5
  42. package/dist/index.d.ts.map +1 -1
  43. package/dist/index.js +17 -3
  44. package/dist/managed-files/ci-workflow.d.ts.map +1 -1
  45. package/dist/managed-files/ci-workflow.js +5 -2
  46. package/dist/managed-files/publish-workflow.d.ts +11 -1
  47. package/dist/managed-files/publish-workflow.d.ts.map +1 -1
  48. package/dist/owned-installation.d.ts +14 -0
  49. package/dist/owned-installation.d.ts.map +1 -0
  50. package/dist/owned-installation.js +324 -0
  51. package/dist/producer-receipts.d.ts +19 -0
  52. package/dist/producer-receipts.d.ts.map +1 -0
  53. package/dist/producer-receipts.js +926 -0
  54. package/dist/test-backstop.d.ts +9 -0
  55. package/dist/test-backstop.d.ts.map +1 -0
  56. package/dist/test-backstop.js +10 -0
  57. package/dist/test-clock-policy.d.ts +30 -0
  58. package/dist/test-clock-policy.d.ts.map +1 -0
  59. package/dist/test-clock-policy.js +686 -0
  60. package/dist/testing.d.ts +8 -0
  61. package/dist/testing.d.ts.map +1 -1
  62. package/dist/testing.js +66 -1
  63. package/managed/raw/patches/nx@23.2.1.patch +328 -50
  64. package/managed/raw/tooling/direnv/developer-links.ts +148 -29
  65. package/managed/raw/tooling/direnv/devenv.smoo.nix +7 -7
  66. package/managed/raw/tooling/direnv/github-actions-bootstrap.sh +14 -5
  67. package/managed/raw/tooling/direnv/linked-snapshots.ts +206 -40
  68. package/managed/raw/tooling/direnv/repo-path +15 -2
  69. package/managed/raw/tooling/direnv/setup-environment.ts +179 -115
  70. package/managed/templates/github/actions/cache-node-modules/action.yml +9 -0
  71. package/managed/templates/github/actions/setup-devenv/action.yml +63 -7
  72. package/nextest.toml +1 -1
  73. package/package.json +25 -9
  74. package/src/__tests__/cargo-closure-fixture.ts +113 -0
  75. package/src/__tests__/counted-cargo.ts +8 -25
  76. package/src/__tests__/directory-change.ts +27 -0
  77. package/src/__tests__/fixture-nx-env.ts +7 -0
  78. package/src/__tests__/owned-installation.ts +14 -0
  79. package/src/__tests__/past-tick.ts +12 -0
  80. package/src/bin/smoo-nx-bound-failures.test.ts +1 -1
  81. package/src/bin/smoo-nx-test-clocks.ts +29 -0
  82. package/src/bounded-test-policy.test.ts +36 -22
  83. package/src/bounded-test-policy.ts +18 -32
  84. package/src/bun-bootstrap.test.ts +1 -1
  85. package/src/cargo-closure-input.property.test.ts +50 -0
  86. package/src/cargo-closure-input.test.ts +73 -121
  87. package/src/cargo-closure-input.ts +47 -8
  88. package/src/cargo-closure-key.test.ts +239 -0
  89. package/src/cargo-resolve-cache.test.ts +168 -31
  90. package/src/cargo-source-hash.test.ts +78 -3
  91. package/src/cargo-source-hash.ts +48 -30
  92. package/src/cross-check-policy.test.ts +2 -2
  93. package/src/ensure-built-receipt.test.ts +111 -16
  94. package/src/ensure-built-receipt.ts +294 -149
  95. package/src/ensure-built-witness.test.ts +306 -13
  96. package/src/ensure-built-witness.ts +255 -24
  97. package/src/ensure-built.test.ts +228 -102
  98. package/src/ensure-built.ts +127 -66
  99. package/src/executors/bounded-exec/cpu-pool.test.ts +134 -32
  100. package/src/executors/bounded-exec/cpu-pool.ts +64 -20
  101. package/src/executors/bounded-exec/cpu-tokens.test.ts +2 -2
  102. package/src/executors/bounded-exec/disk-lease.test.ts +47 -13
  103. package/src/executors/bounded-exec/executor-host.test.ts +74 -52
  104. package/src/executors/bounded-exec/executor.test.ts +343 -97
  105. package/src/executors/bounded-exec/executor.ts +192 -56
  106. package/src/executors/bounded-exec/hang-diagnostics.test.ts +14 -8
  107. package/src/executors/bounded-exec/no-space.ts +40 -0
  108. package/src/executors/bounded-exec/progress.test.ts +1 -1
  109. package/src/executors/bounded-exec/ram-temp-host.test.ts +51 -21
  110. package/src/executors/bounded-exec/ram-temp.test.ts +92 -16
  111. package/src/executors/bounded-exec/ram-temp.ts +49 -20
  112. package/src/executors/bounded-exec/verdict.test.ts +127 -22
  113. package/src/executors/bounded-exec/verdict.ts +78 -3
  114. package/src/generators/bounded-test-targets/generator.test.ts +1 -3
  115. package/src/generators/bun-test-tracing/generator.test.ts +2 -2
  116. package/src/generators/bun-test-tracing/generator.ts +2 -2
  117. package/src/graph-input-contract.test.ts +379 -0
  118. package/src/graph-input-contract.ts +627 -0
  119. package/src/index.test.ts +3 -3
  120. package/src/index.ts +24 -3
  121. package/src/linked-snapshots.nx.test.ts +112 -30
  122. package/src/managed-files/ci-workflow.ts +5 -2
  123. package/src/managed-files/publish-workflow.ts +12 -1
  124. package/src/managed-files/repo-path.test.ts +44 -1
  125. package/src/managed-files/setup-devenv-free-disk.test.ts +95 -0
  126. package/src/nextest-code-bound.test.ts +23 -17
  127. package/src/nextest-extraction.test.ts +114 -4
  128. package/src/nextest-partitions.test.ts +7 -1
  129. package/src/nx-cache-restore-mtime.test.ts +2 -2
  130. package/src/nx-daemon-claim.test.ts +10 -8
  131. package/src/nx-daemon-idle-cpu.test.ts +0 -1
  132. package/src/nx-daemon-idle-policy.test.ts +61 -1
  133. package/src/nx-daemon-ignore-files.test.ts +2 -2
  134. package/src/nx-daemon-validity.test.ts +36 -22
  135. package/src/nx-dot-input-policy.test.ts +5 -5
  136. package/src/nx-files-archive-racy.test.ts +1 -1
  137. package/src/nx-incomplete-run-summary.test.ts +1 -1
  138. package/src/nx-plugin-load-errors.test.ts +2 -2
  139. package/src/nx-project-graph-errors.test.ts +70 -0
  140. package/src/nx-skipped-task-exit.test.ts +2 -2
  141. package/src/nx-store-resolution.test.ts +7 -25
  142. package/src/nx-task-output-lease.test.ts +3 -3
  143. package/src/nx-use-local.test.ts +7 -5
  144. package/src/owned-installation.ts +174 -0
  145. package/src/producer-receipts.test.ts +164 -0
  146. package/src/producer-receipts.ts +636 -0
  147. package/src/runtime-input.test.ts +1 -1
  148. package/src/serial-group-wiring.test.ts +4 -4
  149. package/src/task-results.test.ts +18 -16
  150. package/src/test-backstop.ts +11 -0
  151. package/src/test-clock-policy.test.ts +338 -0
  152. package/src/test-clock-policy.ts +708 -0
  153. package/src/test-timings.test.ts +2 -2
  154. package/src/testing.test.ts +5 -5
  155. package/src/testing.ts +67 -1
  156. package/src/typecheck-test-policy.test.ts +1 -1
  157. package/src/typescript-resolution.test.ts +76 -0
  158. package/test-timings.json +8 -0
@@ -1,11 +1,25 @@
1
- import { expect, it } from 'bun:test';
1
+ import { afterAll, expect, it, jest } from 'bun:test';
2
2
  import { execFileSync } from 'node:child_process';
3
- import { appendFile, mkdir, mkdtemp, readFile, realpath, rm, symlink, utimes, writeFile } from 'node:fs/promises';
3
+ import {
4
+ appendFile,
5
+ mkdir,
6
+ mkdtemp,
7
+ readdir,
8
+ readFile,
9
+ realpath,
10
+ rename,
11
+ rm,
12
+ stat,
13
+ symlink,
14
+ utimes,
15
+ writeFile,
16
+ } from 'node:fs/promises';
4
17
  import { tmpdir } from 'node:os';
5
18
  import { delimiter, dirname, join } from 'node:path';
6
19
 
7
20
  import type { CreateNodesResultV2 } from 'nx/src/devkit-exports.js';
8
21
  import { FileLock } from 'nx/src/native/index.js';
22
+ import { workspaceDataDirectoryForWorkspace } from 'nx/src/utils/cache-directory.js';
9
23
  import { resetWorkspaceContext } from 'nx/src/utils/workspace-context.js';
10
24
  import {
11
25
  type CannedCargo,
@@ -20,6 +34,8 @@ import {
20
34
  withEnvironment,
21
35
  } from './__tests__/counted-cargo.js';
22
36
  import { useFixtureCargoHome } from './__tests__/fixture-cargo-home.js';
37
+ import { testFileInstallation } from './__tests__/owned-installation.js';
38
+ import { BOUNDED_TEST_IDLE_TIMEOUT_MS } from './bounded-test-policy.js';
23
39
  import { CARGO_CLOSURE_INPUT } from './cargo-closure-input.js';
24
40
  import {
25
41
  acquireCargoResolveLock,
@@ -31,6 +47,10 @@ import { createNodesV2 } from './index.js';
31
47
 
32
48
  useFixtureCargoHome();
33
49
 
50
+ /** The Nx installation this file's graph fixtures share; none may write into it. */
51
+ const installation = testFileInstallation('cargo-resolve-installation-');
52
+ afterAll(() => installation.retire());
53
+
34
54
  /*
35
55
  * What Cargo resolution costs, measured by the one number that matters: how many `cargo metadata`
36
56
  * children were actually started. A `cargo` ahead of the real one on PATH reports each child's life
@@ -49,7 +69,6 @@ useFixtureCargoHome();
49
69
 
50
70
  const sourceModule = join(import.meta.dir, 'cargo-source-hash.ts');
51
71
  const cliModule = join(import.meta.dir, 'bin', 'smoo-nx-cargo-hash.ts');
52
- const repositoryRoot = join(import.meta.dir, '../../..');
53
72
 
54
73
  const spawned = async (cargo: CountedCargo): Promise<number> => (await cargo.runs()).spawned;
55
74
 
@@ -81,7 +100,7 @@ function alive(pid: number): boolean {
81
100
  /** How a subprocess ended, with everything it printed. */
82
101
  interface Ended {
83
102
  readonly exitCode: number | null;
84
- readonly signalCode: NodeJS.Signals | null;
103
+ readonly signalCode: Bun.Subprocess['signalCode'];
85
104
  readonly stdout: string;
86
105
  readonly stderr: string;
87
106
  }
@@ -348,7 +367,7 @@ it('concurrent resolutions of one Cargo workspace share one cargo child, and an
348
367
  expect(await members()).toEqual(['after']);
349
368
  expect(await spawned(cargo)).toBe(2);
350
369
  });
351
- }, 20_000);
370
+ });
352
371
 
353
372
  it("a failed resolution rejects every sharer with a CargoMetadataError carrying Cargo's stderr, and is not kept for the next call", async () => {
354
373
  await withCannedWorkspace(async ({ cargo, answer, members, workspace, manifest }) => {
@@ -380,7 +399,7 @@ it("a failed resolution rejects every sharer with a CargoMetadataError carrying
380
399
  expect(await members()).toEqual(['recovered']);
381
400
  expect(await spawned(cargo)).toBe(2);
382
401
  });
383
- }, 20_000);
402
+ });
384
403
 
385
404
  it('a Cargo that cannot run, or whose answer is not metadata, is a CargoMetadataError', async () => {
386
405
  await withCannedWorkspace(async ({ cargo, workspace, manifest }) => {
@@ -395,7 +414,7 @@ it('a Cargo that cannot run, or whose answer is not metadata, is a CargoMetadata
395
414
  });
396
415
  expect(await spawned(cargo)).toBe(2);
397
416
  });
398
- }, 20_000);
417
+ });
399
418
 
400
419
  it('source edits, non-Rust edits and a rewrite of the same bytes never run Cargo', async () => {
401
420
  await withCannedWorkspace(async ({ root, cargo, answer, members, workspace }) => {
@@ -421,7 +440,7 @@ it('source edits, non-Rust edits and a rewrite of the same bytes never run Cargo
421
440
  }
422
441
  expect(await spawned(cargo)).toBe(1);
423
442
  });
424
- }, 20_000);
443
+ });
425
444
 
426
445
  interface KeyedFile {
427
446
  readonly name: string;
@@ -481,7 +500,10 @@ for (const file of KEYED_FILES) {
481
500
  expect(await resolvesAs('same bytes')).toEqual(['one']);
482
501
  expect(await spawned(cargo)).toBe(2);
483
502
 
503
+ // Identical size and mtime cannot stand in for the current bytes.
504
+ const before = await stat(join(root, file.path));
484
505
  await put(root, file.path, `${original}# two\n`);
506
+ await utimes(join(root, file.path), before.atime, before.mtime);
485
507
  expect(await resolvesAs('two')).toEqual(['two']);
486
508
  expect(await spawned(cargo)).toBe(3);
487
509
 
@@ -493,9 +515,54 @@ for (const file of KEYED_FILES) {
493
515
  expect(await resolvesAs('settled')).toEqual([file.removable ? 'removed' : 'two']);
494
516
  expect(await spawned(cargo)).toBe(file.removable ? 4 : 3);
495
517
  });
496
- }, 30_000);
518
+ });
497
519
  }
498
520
 
521
+ it('retargeting a configuration symlink with identical bytes still resolves the new canonical input', async () => {
522
+ await withCannedWorkspace(async ({ root, workspace, cargo, answer, members }) => {
523
+ const config = join(workspace, '.cargo/config.toml');
524
+ await put(root, 'config-a.toml', '[net]\noffline=true\n');
525
+ await put(root, 'config-b.toml', '[net]\noffline=true\n');
526
+ await mkdir(dirname(config), { recursive: true });
527
+ await symlink(join(root, 'config-a.toml'), config);
528
+ await answer('first target');
529
+ expect(await members()).toEqual(['first target']);
530
+ expect(await spawned(cargo)).toBe(1);
531
+
532
+ await rm(config);
533
+ await symlink(join(root, 'config-b.toml'), config);
534
+ await answer('second target');
535
+ expect(await members()).toEqual(['second target']);
536
+ expect(await spawned(cargo)).toBe(2);
537
+ await answer('unchanged');
538
+ expect(await members()).toEqual(['second target']);
539
+ expect(await spawned(cargo)).toBe(2);
540
+ });
541
+ });
542
+
543
+ it('a resolution input read failure is not a missing file or a reusable answer', async () => {
544
+ await withCannedWorkspace(async ({ workspace, manifest, cargo, answer }) => {
545
+ // Use the graph caller's inventory so this tests the resolution reader,
546
+ // independently of how the native workspace census treats a symlink loop.
547
+ const indexed = new Set(['Cargo.toml', 'crates/leaf/Cargo.toml']);
548
+ const members = async () => [...(await readCargoResolve(manifest, workspace, indexed)).members];
549
+ await answer('cold');
550
+ expect(await members()).toEqual(['cold']);
551
+ const config = join(workspace, '.cargo/config.toml');
552
+ await mkdir(dirname(config), { recursive: true });
553
+ await symlink('config.toml', config);
554
+ const failure = expectCargoMetadataError(await rejectionOf(members()), manifest);
555
+ expect(failure.message).toContain('ELOOP');
556
+ expect(failure.message).toContain(config);
557
+ expect(await spawned(cargo)).toBe(1);
558
+
559
+ await rm(config);
560
+ await answer('trap');
561
+ expect(await members()).toEqual(['cold']);
562
+ expect(await spawned(cargo)).toBe(1);
563
+ });
564
+ });
565
+
499
566
  it('resolves again exactly once when the cargo on PATH or the rustup selection changes', async () => {
500
567
  await withCannedWorkspace(async ({ root, cargo, answer, members, environment }) => {
501
568
  const resolvesAs = async (name: string, selection: Record<string, string> = {}): Promise<string[]> => {
@@ -527,7 +594,7 @@ it('resolves again exactly once when the cargo on PATH or the rustup selection c
527
594
  expect(await resolvesAs('same cargo', elsewhere)).toEqual(['another cargo']);
528
595
  expect(await spawned(cargo)).toBe(5);
529
596
  });
530
- }, 30_000);
597
+ });
531
598
 
532
599
  it('a discovered manifest outside the workspace, edited while the first resolution holds, is never answered from before the edit', async () => {
533
600
  await withCannedWorkspace(async ({ root, cargo, answer, members, workspace, manifest }) => {
@@ -550,7 +617,7 @@ it('a discovered manifest outside the workspace, edited while the first resoluti
550
617
  expect(await members()).toEqual(['after']);
551
618
  expect(await spawned(cargo)).toBe(2);
552
619
  });
553
- }, 20_000);
620
+ });
554
621
 
555
622
  it('an edit made while Cargo resolves is answered by a resolution that follows the first, never beside it', async () => {
556
623
  await withCannedWorkspace(async ({ cargo, answer, members, workspace, manifest }) => {
@@ -576,7 +643,7 @@ it('an edit made while Cargo resolves is answered by a resolution that follows t
576
643
  expect(await members()).toEqual(['after']);
577
644
  expect(await spawned(cargo)).toBe(2);
578
645
  });
579
- }, 20_000);
646
+ });
580
647
 
581
648
  it('an answer Cargo read after an edit is never kept for the workspace as it was before the edit', async () => {
582
649
  await withCannedWorkspace(async ({ cargo, answer, members, workspace, manifest }) => {
@@ -598,7 +665,7 @@ it('an answer Cargo read after an edit is never kept for the workspace as it was
598
665
  await answer('before');
599
666
  expect(await members()).toEqual(['before']);
600
667
  });
601
- }, 20_000);
668
+ });
602
669
 
603
670
  it('a process that has never resolved an unchanged workspace reads the answer an earlier one left, without Cargo', async () => {
604
671
  await withCannedWorkspace(async (fixture) => {
@@ -626,7 +693,7 @@ it('a process that has never resolved an unchanged workspace reads the answer an
626
693
  expect(await freshResolver(fixture, 'edited again').result).toEqual(edited);
627
694
  expect(await spawned(cargo)).toBe(2);
628
695
  });
629
- }, 60_000);
696
+ });
630
697
 
631
698
  it('fresh processes that ask at once for a workspace nobody has resolved share one cargo child', async () => {
632
699
  await withCannedWorkspace(async (fixture) => {
@@ -645,7 +712,7 @@ it('fresh processes that ask at once for a workspace nobody has resolved share o
645
712
  expect(results[0]).toMatchObject({ members: ['cold'] });
646
713
  expect(await spawned(cargo)).toBe(1);
647
714
  });
648
- }, 60_000);
715
+ });
649
716
 
650
717
  it('a worker that exits on SIGTERM while Cargo resolves leaves no cargo child behind', async () => {
651
718
  await withCannedWorkspace(async ({ root, workspace, manifest, cargo, answer, environment }) => {
@@ -673,7 +740,7 @@ it('a worker that exits on SIGTERM while Cargo resolves leaves no cargo child be
673
740
  // The child's end is the end of its connection to the fixture, killed before it answered.
674
741
  await cargo.waitForDisconnects([pid]);
675
742
  });
676
- }, 20_000);
743
+ });
677
744
 
678
745
  it("a worker that exits with callers waiting on two resolutions leaves none of Cargo's processes behind, and the next process resolves normally", async () => {
679
746
  await withCannedWorkspace(async (fixture) => {
@@ -730,7 +797,7 @@ it("a worker that exits with callers waiting on two resolutions leaves none of C
730
797
  expect(await freshResolver(fixture, 'again').result).toEqual(next);
731
798
  expect(await spawned(cargo)).toBe(3);
732
799
  });
733
- }, 60_000);
800
+ });
734
801
 
735
802
  // A standalone `smoo-nx-cargo-hash` has no handler of its own, so a signal would end it on the spot,
736
803
  // before any exit hook could take the Cargo it started along. The module forwards the signal to
@@ -754,7 +821,7 @@ for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP'] as const) {
754
821
  expect(ended.signalCode, proc.describe()).toBe(signal);
755
822
  await cargo.waitForDisconnects(running);
756
823
  });
757
- }, 30_000);
824
+ });
758
825
  }
759
826
 
760
827
  /* ---- The same, with the real Cargo, through the project graph and the hash command ---- */
@@ -808,7 +875,7 @@ async function graphFixture(root: string): Promise<string> {
808
875
  };
809
876
  for (const [path, text] of Object.entries(files)) await put(root, path, text);
810
877
  execFileSync('git', ['init', '--quiet', workspace], { stdio: 'pipe' });
811
- await symlink(join(repositoryRoot, 'node_modules'), join(workspace, 'node_modules'), 'dir');
878
+ await symlink(await installation.nodeModules(), join(workspace, 'node_modules'), 'dir');
812
879
  relock(workspace);
813
880
  return workspace;
814
881
  }
@@ -912,7 +979,7 @@ it('a project graph over an unchanged Cargo workspace runs Cargo once, however o
912
979
  expect(byFile(await graph())).toEqual(edited);
913
980
  expect(await spawned(cargo)).toBe(expected + 1);
914
981
  });
915
- }, 120_000);
982
+ });
916
983
 
917
984
  it('a Cargo workspace Cargo refuses fails the project graph with a CargoMetadataError, and no runtime hash stands in', async () => {
918
985
  await withGraphWorkspace(async ({ workspace, cargo, graph }) => {
@@ -937,7 +1004,56 @@ it('a Cargo workspace Cargo refuses fails the project graph with a CargoMetadata
937
1004
  expect(byFile(await graph())).toEqual(repaired);
938
1005
  expect(await spawned(cargo)).toBe(4);
939
1006
  });
940
- }, 120_000);
1007
+ });
1008
+
1009
+ for (const replaced of [false, true]) {
1010
+ it(`cache publication records a ${replaced ? 'rebound' : 'missing'} parent with the original filesystem cause`, async () => {
1011
+ await withGraphWorkspace(async ({ workspace, cargo }) => {
1012
+ const manifest = join(workspace, 'Cargo.toml');
1013
+ await cargo.beforeAnswer.close();
1014
+ const refused = rejectionOf(readCargoResolve(manifest, workspace));
1015
+ await cargo.waitForRuns((runs) => runs.read === 1, 'real locked/offline Cargo to read before cache publication');
1016
+ const namespace = join(workspaceDataDirectoryForWorkspace(workspace), 'cargo-resolve');
1017
+ const entries = await readdir(namespace);
1018
+ expect(entries).toHaveLength(1);
1019
+ const [entry] = entries;
1020
+ if (entry === undefined) throw new Error('the real resolver created no owned cache namespace');
1021
+ const directory = join(namespace, entry);
1022
+ const before = await stat(directory, { bigint: true });
1023
+ let atOpen = before;
1024
+ if (replaced) {
1025
+ await rename(directory, `${directory}.retired`);
1026
+ await mkdir(directory);
1027
+ atOpen = await stat(directory, { bigint: true });
1028
+ expect(atOpen.ino).not.toBe(before.ino);
1029
+ // Force publication to report the replacement rather than silently sign under a new namespace.
1030
+ await mkdir(join(directory, 'entry.cache'));
1031
+ } else {
1032
+ await rm(directory, { recursive: true });
1033
+ }
1034
+ await cargo.beforeAnswer.open();
1035
+ const failure = expectCargoMetadataError(await refused, manifest);
1036
+ expect(failure.message).toContain(directory);
1037
+ expect(failure.message).toContain('entry.cache.');
1038
+ expect(failure.message).toContain(
1039
+ `"parentBeforeLock":${JSON.stringify({ state: 'present', dev: before.dev.toString(), ino: before.ino.toString() })}`,
1040
+ );
1041
+ if (replaced) {
1042
+ const expected = JSON.stringify({ state: 'present', dev: atOpen.dev.toString(), ino: atOpen.ino.toString() });
1043
+ expect(failure.message).toContain(`"parentAtTmpOpen":${expected}`);
1044
+ expect(failure.message).toContain(`"parentAfterFailure":${expected}`);
1045
+ } else {
1046
+ expect(failure.message).toContain('"parentAtTmpOpen":{"state":"unavailable","code":"ENOENT"');
1047
+ expect(failure.message).toContain('"parentAfterFailure":{"state":"unavailable","code":"ENOENT"');
1048
+ }
1049
+ const publication = failure.cause;
1050
+ expect(publication).toBeInstanceOf(Error);
1051
+ if (!(publication instanceof Error)) throw new Error('cache publication lost its structured cause');
1052
+ expect(publication.cause).toHaveProperty('code', replaced ? 'EISDIR' : 'ENOENT');
1053
+ expect(await spawned(cargo)).toBe(1);
1054
+ });
1055
+ });
1056
+ }
941
1057
 
942
1058
  it('fresh smoo-nx-cargo-hash processes over an unchanged Cargo workspace run Cargo once between them', async () => {
943
1059
  await withGraphWorkspace(async ({ root, workspace, cargo }) => {
@@ -982,20 +1098,30 @@ it('fresh smoo-nx-cargo-hash processes over an unchanged Cargo workspace run Car
982
1098
  expect(await hash()).toBe(manifestEdited);
983
1099
  expect(await spawned(cargo)).toBe(2);
984
1100
  });
985
- }, 120_000);
1101
+ });
986
1102
 
987
1103
  it('a Cargo child that never answers is killed and named at the resolve bound', async () => {
988
1104
  await withCannedWorkspace(async ({ cargo, answer, workspace, manifest }) => {
989
1105
  await answer('before');
990
1106
  await cargo.beforeAnswer.close();
991
1107
  try {
992
- const refused = await rejectionOf(readCargoResolve(manifest, workspace, undefined, 100));
993
- expect(String(refused)).toContain('did not finish within 100ms');
1108
+ // The resolve bound is a timer in this process, started only once the lock is held and Cargo is spawned. The
1109
+ // clock stays stopped until the canned Cargo reports that it read the workspace and is held at the closed
1110
+ // answer latch; only then is the bound advanced, so it expires on a child that can never answer.
1111
+ jest.useFakeTimers();
1112
+ try {
1113
+ const refusal = rejectionOf(readCargoResolve(manifest, workspace, undefined, 100));
1114
+ await cargo.waitForRuns((runs) => runs.read >= 1, 'the canned Cargo to read the workspace and be held');
1115
+ jest.advanceTimersByTime(100);
1116
+ expect(String(await refusal)).toContain('did not finish within 100ms');
1117
+ } finally {
1118
+ jest.useRealTimers();
1119
+ }
994
1120
  } finally {
995
1121
  await cargo.beforeAnswer.open();
996
1122
  }
997
1123
  });
998
- }, 20_000);
1124
+ });
999
1125
 
1000
1126
  it('a held resolve lock times out with its name and elapsed wait and leaves no lock child', async () => {
1001
1127
  const root = await realpath(await mkdtemp(join(tmpdir(), 'cargo-resolve-lock-')));
@@ -1004,15 +1130,24 @@ it('a held resolve lock times out with its name and elapsed wait and leaves no l
1004
1130
  const holder = new FileLock(lockFile);
1005
1131
  holder.lock();
1006
1132
  try {
1007
- const started = performance.now();
1008
- const refused = await rejectionOf(acquireCargoResolveLock(lockFile, 100));
1133
+ // The lock's bound is a timer in this process, and the waiter cannot take the lock while the holder keeps it.
1134
+ // The clock stays stopped while the waiter queues; advancing it by the bound is what ends the wait, and the
1135
+ // refusal must then name the lock, the wait and the reaped waiter while the holder still holds the lock.
1136
+ jest.useFakeTimers();
1137
+ let refused: unknown;
1138
+ try {
1139
+ const attempt = rejectionOf(acquireCargoResolveLock(lockFile, 100));
1140
+ jest.advanceTimersByTime(100);
1141
+ refused = await attempt;
1142
+ } finally {
1143
+ jest.useRealTimers();
1144
+ }
1009
1145
  if (!(refused instanceof CargoResolveLockError)) throw new Error(`unexpected lock refusal: ${refused}`);
1010
1146
  expect(refused.name).toBe('CargoResolveLockError');
1011
1147
  expect(refused.message).toContain(lockFile);
1012
1148
  expect(refused.message).toContain(`waited ${refused.waitedMs}ms`);
1013
1149
  expect(refused.message).toContain('bound 100ms');
1014
1150
  expect(refused.waitedMs).toBeGreaterThanOrEqual(100);
1015
- expect(performance.now() - started).toBeLessThan(1_100);
1016
1151
  if (refused.waiterPid === undefined) throw new Error('the lock refusal named no spawned waiter');
1017
1152
  expect(refused.message).toContain(`reaped lock waiter pid ${refused.waiterPid}`);
1018
1153
  expect(alive(refused.waiterPid)).toBe(false);
@@ -1023,13 +1158,15 @@ it('a held resolve lock times out with its name and elapsed wait and leaves no l
1023
1158
  } finally {
1024
1159
  await rm(root, { recursive: true, force: true });
1025
1160
  }
1026
- }, 20_000);
1161
+ });
1027
1162
 
1028
1163
  it('a successful resolve lock lease holds the kernel lock until its child is released and reaped', async () => {
1029
1164
  const root = await realpath(await mkdtemp(join(tmpdir(), 'cargo-resolve-lease-')));
1030
1165
  try {
1031
1166
  const lockFile = join(root, 'resolve.lock');
1032
- const lease = await acquireCargoResolveLock(lockFile, 5_000);
1167
+ // The lock is granted by the child's `locked` line and released by the child's exit, so I/O decides this case; the
1168
+ // bound is the leg backstop, which an uncontended lock never reaches.
1169
+ const lease = await acquireCargoResolveLock(lockFile, BOUNDED_TEST_IDLE_TIMEOUT_MS);
1033
1170
  try {
1034
1171
  expect(alive(lease.pid)).toBe(true);
1035
1172
  expect(new FileLock(lockFile).check()).toBe(true);
@@ -1041,4 +1178,4 @@ it('a successful resolve lock lease holds the kernel lock until its child is rel
1041
1178
  } finally {
1042
1179
  await rm(root, { recursive: true, force: true });
1043
1180
  }
1044
- }, 20_000);
1181
+ });
@@ -1,11 +1,11 @@
1
1
  import { expect, it } from 'bun:test';
2
2
  import { execFileSync } from 'node:child_process';
3
- import { mkdir, mkdtemp, readFile, realpath, rename, rm, symlink, writeFile } from 'node:fs/promises';
3
+ import { mkdir, mkdtemp, readFile, realpath, rename, rm, stat, symlink, utimes, writeFile } from 'node:fs/promises';
4
4
  import { homedir, tmpdir } from 'node:os';
5
- import { dirname, join } from 'node:path';
5
+ import { dirname, join, relative } from 'node:path';
6
6
  import { useFixtureCargoHome } from './__tests__/fixture-cargo-home.js';
7
7
  import { runtimeInputValue } from './__tests__/runtime-input.js';
8
- import { hashCargoPathInputs } from './cargo-source-hash.js';
8
+ import { hashCargoPathInputs, readCargoResolve } from './cargo-source-hash.js';
9
9
 
10
10
  useFixtureCargoHome();
11
11
 
@@ -256,6 +256,81 @@ it('include-workspace hashes in-workspace transitive source edits without changi
256
256
  }
257
257
  });
258
258
 
259
+ it.each(['external', 'workspace/node_modules/external'])(
260
+ 'follows same-size same-mtime dependency edits in %s and hashes the newly reached source bytes',
261
+ async (externalDirectory) => {
262
+ const root = await realpath(await mkdtemp(join(tmpdir(), 'cargo-hash-boundary-')));
263
+ const workspace = join(root, 'workspace');
264
+ const manifest = join(workspace, 'Cargo.toml');
265
+ const external = join(root, externalDirectory);
266
+ const externalManifest = join(external, 'Cargo.toml');
267
+ async function put(file: string, text: string): Promise<void> {
268
+ await mkdir(dirname(file), { recursive: true });
269
+ await writeFile(file, text);
270
+ }
271
+ const dependencyManifest = (name: string) =>
272
+ '[package]\nname="external"\nversion="0.1.0"\nedition="2021"\n[workspace]\n' +
273
+ `[dependencies]\nside={path=${JSON.stringify(relative(external, join(root, name)))}}\n`;
274
+ const sideManifest = '[package]\nname="side"\nversion="0.1.0"\nedition="2021"\n[workspace]\n';
275
+ const timestamp = new Date(1_700_000_000_000);
276
+ try {
277
+ // A nested installed workspace must not be auto-enrolled as a member of this one.
278
+ await put(
279
+ manifest,
280
+ '[package]\nname="app"\nversion="0.1.0"\nedition="2021"\n[workspace]\nexclude=["node_modules/external"]\n' +
281
+ `[dependencies]\nexternal={path=${JSON.stringify(relative(workspace, external))}}\n`,
282
+ );
283
+ await put(join(workspace, 'src/lib.rs'), 'pub fn app() {}\n');
284
+ await put(externalManifest, dependencyManifest('left'));
285
+ await put(join(external, 'src/lib.rs'), 'pub fn external() {}\n');
286
+ for (const side of ['left', 'rght']) {
287
+ await put(join(root, side, 'Cargo.toml'), sideManifest);
288
+ await put(join(root, side, 'src/lib.rs'), 'pub fn side() -> u8 { 1 }\n');
289
+ }
290
+ execFileSync('git', ['init', '--quiet', workspace], { stdio: 'pipe' });
291
+ await put(join(workspace, '.gitignore'), 'node_modules/\n.nx/\n');
292
+ execFileSync('cargo', ['generate-lockfile', '--offline', '--manifest-path', manifest], { stdio: 'pipe' });
293
+ await utimes(externalManifest, timestamp, timestamp);
294
+ const before = await stat(externalManifest);
295
+ const lock = await readFile(join(workspace, 'Cargo.lock'), 'utf8');
296
+ const initialResolve = await readCargoResolve(manifest, workspace);
297
+ expect(initialResolve.local.map((pkg) => pkg.manifest)).toContain(join(root, 'left/Cargo.toml'));
298
+ const initial = await hashCargoPathInputs(manifest, workspace);
299
+
300
+ // Both packages have the same name/version, so the locked graph stays
301
+ // valid. Only the dependency manifest's bytes identify its new location.
302
+ await writeFile(externalManifest, dependencyManifest('rght'));
303
+ await utimes(externalManifest, timestamp, timestamp);
304
+ const after = await stat(externalManifest);
305
+ expect(after.size).toBe(before.size);
306
+ expect(after.mtimeMs).toBe(before.mtimeMs);
307
+ const changedResolve = await readCargoResolve(manifest, workspace);
308
+ const manifests = changedResolve.local.map((pkg) => pkg.manifest);
309
+ expect(manifests).toContain(join(root, 'rght/Cargo.toml'));
310
+ expect(manifests).not.toContain(join(root, 'left/Cargo.toml'));
311
+ expect(await readFile(join(workspace, 'Cargo.lock'), 'utf8')).toBe(lock);
312
+ const changed = await hashCargoPathInputs(manifest, workspace);
313
+ expect(changed).not.toBe(initial);
314
+
315
+ await writeFile(join(root, 'left/src/lib.rs'), 'pub fn side() -> u8 { 2 }\n');
316
+ expect(await hashCargoPathInputs(manifest, workspace)).toBe(changed);
317
+ const source = join(root, 'rght/src/lib.rs');
318
+ const sourceBefore = await stat(source);
319
+ await writeFile(source, 'pub fn side() -> u8 { 2 }\n');
320
+ await utimes(source, sourceBefore.atime, sourceBefore.mtime);
321
+ const sourceChanged = await hashCargoPathInputs(manifest, workspace);
322
+ expect(sourceChanged).not.toBe(changed);
323
+
324
+ await rm(join(root, 'rght/Cargo.toml'));
325
+ await expect(hashCargoPathInputs(manifest, workspace)).rejects.toThrow('Locked offline Cargo resolution failed');
326
+ await put(join(root, 'rght/Cargo.toml'), sideManifest);
327
+ expect(await hashCargoPathInputs(manifest, workspace)).toBe(sourceChanged);
328
+ } finally {
329
+ await rm(root, { recursive: true, force: true });
330
+ }
331
+ },
332
+ );
333
+
259
334
  it('include-workspace CLI accepts an optional manifest and refuses unsupported arguments', async () => {
260
335
  const root = await mkdtemp(join(tmpdir(), 'cargo-hash-cli-'));
261
336
  try {
@@ -1,20 +1,8 @@
1
1
  import { type ChildProcess, type ChildProcessByStdio, execFileSync, spawn, spawnSync } from 'node:child_process';
2
2
  import { createHash, randomUUID } from 'node:crypto';
3
3
  import { channel } from 'node:diagnostics_channel';
4
- import { constants, existsSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
5
- import {
6
- access,
7
- lstat,
8
- mkdir,
9
- readdir,
10
- readFile,
11
- readlink,
12
- realpath,
13
- rename,
14
- rm,
15
- stat,
16
- writeFile,
17
- } from 'node:fs/promises';
4
+ import { accessSync, constants, existsSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
5
+ import { lstat, mkdir, readdir, readFile, readlink, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';
18
6
  import { createRequire } from 'node:module';
19
7
  import { homedir } from 'node:os';
20
8
  import { delimiter, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
@@ -390,15 +378,16 @@ function resolutionFiles(
390
378
  if (cargo !== null) paths.add(join(cargo.root, 'Cargo.toml'));
391
379
  const directories = new Set<string>([root]);
392
380
  for (const file of paths) directories.add(dirname(file));
381
+ const ancestors = new Set<string>();
393
382
  for (const directory of directories) {
394
383
  paths.add(join(directory, 'Cargo.lock'));
395
- for (let ancestor = directory; ; ancestor = dirname(ancestor)) {
384
+ for (let ancestor = directory; !ancestors.has(ancestor); ancestor = dirname(ancestor)) {
385
+ ancestors.add(ancestor);
396
386
  paths.add(join(ancestor, '.cargo/config'));
397
387
  paths.add(join(ancestor, '.cargo/config.toml'));
398
388
  paths.add(join(ancestor, 'rust-toolchain'));
399
389
  paths.add(join(ancestor, 'rust-toolchain.toml'));
400
390
  paths.add(join(ancestor, 'Cargo.toml'));
401
- if (dirname(ancestor) === ancestor) break;
402
391
  }
403
392
  }
404
393
  for (const pin of CARGO_TOOLCHAIN_PIN_INPUTS) paths.add(pin.replace('{workspaceRoot}', root));
@@ -409,12 +398,12 @@ function resolutionFiles(
409
398
  }
410
399
 
411
400
  /** Toolchain selection can change even while the declared pin's bytes do not. */
412
- async function cargoExecutable(): Promise<string> {
401
+ function cargoExecutable(): string {
413
402
  for (const directory of (process.env.PATH ?? '').split(delimiter)) {
414
403
  const executable = resolve(directory, process.platform === 'win32' ? 'cargo.exe' : 'cargo');
415
404
  try {
416
- await access(executable, constants.X_OK);
417
- return await realpath(executable);
405
+ accessSync(executable, constants.X_OK);
406
+ return realpathSync.native(executable);
418
407
  } catch (error) {
419
408
  if (
420
409
  !(
@@ -429,21 +418,24 @@ async function cargoExecutable(): Promise<string> {
429
418
  return '<cargo-not-on-PATH>';
430
419
  }
431
420
 
432
- async function resolutionKey(
421
+ function resolutionKey(
433
422
  root: string,
434
423
  manifest: string,
435
424
  cargo: CargoResolve | null,
436
425
  indexed: ReadonlySet<string>,
437
- ): Promise<string> {
426
+ ): string {
438
427
  const cargoHome = resolve(process.env.CARGO_HOME ?? join(homedir(), '.cargo'));
439
- const executable = await cargoExecutable();
428
+ const executable = cargoExecutable();
440
429
  const hash = createHash('sha256').update(
441
430
  `${RESOLVE_CACHE_SCHEMA}\0${root}\0${manifest}\0${cargoHome}\0${executable}\0${process.env.RUSTUP_TOOLCHAIN ?? ''}\0${process.env.RUSTUP_HOME ?? ''}\0`,
442
431
  );
443
432
  for (const file of [...resolutionFiles(root, manifest, cargo, indexed)].sort()) {
444
433
  hash.update(file).update('\0');
445
434
  try {
446
- const [bytes, canonical] = await Promise.all([readFile(file), realpath(file)]);
435
+ // Most ancestor inputs are absent. Read first so those paths need no
436
+ // canonical lookup; small resolution files need no per-file async dispatch.
437
+ const bytes = readFileSync(file);
438
+ const canonical = realpathSync.native(file);
447
439
  hash.update(`${canonical}\0${bytes.length}\0`).update(bytes);
448
440
  } catch (error) {
449
441
  if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT')) throw error;
@@ -538,7 +530,7 @@ export async function readCargoResolve(
538
530
  }
539
531
  } else await state.ready;
540
532
  for (let joined = 0; joined <= 3; joined += 1) {
541
- const key = await resolutionKey(root, manifest, state.cached?.cargo ?? null, index);
533
+ const key = resolutionKey(root, manifest, state.cached?.cargo ?? null, index);
542
534
  const pending = state.pending;
543
535
  if (pending !== undefined) {
544
536
  if (joined === 3) break;
@@ -572,6 +564,24 @@ export async function readCargoResolve(
572
564
  }
573
565
  }
574
566
 
567
+ type CacheParentObservation =
568
+ | { readonly state: 'present'; readonly dev: string; readonly ino: string }
569
+ | { readonly state: 'unavailable'; readonly code: string; readonly detail: string };
570
+
571
+ async function observeCacheParent(directory: string): Promise<CacheParentObservation> {
572
+ try {
573
+ const parent = await stat(directory, { bigint: true });
574
+ return { state: 'present', dev: parent.dev.toString(), ino: parent.ino.toString() };
575
+ } catch (error) {
576
+ if (!(error instanceof Error)) throw error;
577
+ return {
578
+ state: 'unavailable',
579
+ code: 'code' in error && typeof error.code === 'string' ? error.code : error.name,
580
+ detail: error.message,
581
+ };
582
+ }
583
+ }
584
+
575
585
  async function resolveAndCache(
576
586
  root: string,
577
587
  manifest: string,
@@ -587,18 +597,18 @@ async function resolveAndCache(
587
597
  // A warm cache answers with no lock: reading it and keying it spawns nothing and
588
598
  // waits for nobody, so an unchanged workspace never queues behind a foreign flight.
589
599
  state.cached = await loadResolveCache(file);
590
- {
591
- const key = await resolutionKey(root, manifest, state.cached?.cargo ?? null, indexed);
592
- if (state.cached?.key === key) return state.cached.cargo;
600
+ if (state.cached !== null && state.cached.key === resolutionKey(root, manifest, state.cached.cargo, indexed)) {
601
+ return state.cached.cargo;
593
602
  }
594
603
  const lockFile = join(directory, 'resolve.lock');
604
+ const parentBeforeLock = await observeCacheParent(directory);
595
605
  const lock = await acquireCargoResolveLock(lockFile, boundMs);
596
606
  try {
597
607
  // Another worker may have populated it while this worker waited.
598
608
  state.cached = await loadResolveCache(file);
599
609
  let inputs = state.cached?.cargo ?? null;
600
610
  for (let attempt = 0; attempt < 3; attempt += 1) {
601
- const before = await resolutionKey(root, manifest, inputs, indexed);
611
+ const before = resolutionKey(root, manifest, inputs, indexed);
602
612
  if (state.cached?.key === before) return state.cached.cargo;
603
613
  const knownFiles = resolutionFiles(root, manifest, inputs, indexed);
604
614
  // A filesystem timestamp, not a sandbox's wall clock: a newly
@@ -609,8 +619,8 @@ async function resolveAndCache(
609
619
  const cargo = cargoFromMetadata(metadata);
610
620
  // Capture the published key before validation. Reading it afterwards
611
621
  // could pair a post-edit key with Cargo's pre-edit answer.
612
- const key = await resolutionKey(root, manifest, cargo, indexed);
613
- let changed = before !== (await resolutionKey(root, manifest, inputs, indexed));
622
+ const key = resolutionKey(root, manifest, cargo, indexed);
623
+ let changed = before !== resolutionKey(root, manifest, inputs, indexed);
614
624
  for (const added of resolutionFiles(root, manifest, cargo, indexed)) {
615
625
  if (knownFiles.has(added)) continue;
616
626
  try {
@@ -624,9 +634,17 @@ async function resolveAndCache(
624
634
  continue;
625
635
  }
626
636
  const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;
637
+ const parentAtTmpOpen = await observeCacheParent(directory);
627
638
  try {
628
639
  await writeFile(temporary, `${key}\n${JSON.stringify(metadata)}\n`);
629
640
  await rename(temporary, file);
641
+ } catch (error) {
642
+ const parentAfterFailure = await observeCacheParent(directory);
643
+ const cause = error instanceof Error ? error.message : String(error);
644
+ throw new Error(
645
+ `Cargo resolution cache publication failed: ${JSON.stringify({ directory, lockFile, temporary, parentBeforeLock, parentAtTmpOpen, parentAfterFailure })}; ${cause}`,
646
+ { cause: error },
647
+ );
630
648
  } finally {
631
649
  await rm(temporary, { force: true });
632
650
  }