@smoothbricks/nx-plugin 0.4.28 → 0.4.29

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 (124) hide show
  1. package/README.md +203 -83
  2. package/dist/bounded-test-policy.d.ts +10 -3
  3. package/dist/bounded-test-policy.d.ts.map +1 -1
  4. package/dist/bounded-test-policy.js +19 -25
  5. package/dist/cargo-closure-input.d.ts +12 -0
  6. package/dist/cargo-closure-input.d.ts.map +1 -1
  7. package/dist/cargo-closure-input.js +29 -7
  8. package/dist/cargo-source-hash.d.ts.map +1 -1
  9. package/dist/cargo-source-hash.js +42 -19
  10. package/dist/ensure-built-receipt.d.ts +34 -6
  11. package/dist/ensure-built-receipt.d.ts.map +1 -1
  12. package/dist/ensure-built-receipt.js +265 -159
  13. package/dist/ensure-built-witness.d.ts +27 -2
  14. package/dist/ensure-built-witness.d.ts.map +1 -1
  15. package/dist/ensure-built-witness.js +2176 -15
  16. package/dist/ensure-built.d.ts +99 -1
  17. package/dist/ensure-built.d.ts.map +1 -1
  18. package/dist/ensure-built.js +34 -53
  19. package/dist/executors/bounded-exec/cpu-pool.d.ts +16 -5
  20. package/dist/executors/bounded-exec/cpu-pool.d.ts.map +1 -1
  21. package/dist/executors/bounded-exec/cpu-pool.js +43 -19
  22. package/dist/executors/bounded-exec/executor.d.ts +11 -2
  23. package/dist/executors/bounded-exec/executor.d.ts.map +1 -1
  24. package/dist/executors/bounded-exec/executor.js +139 -39
  25. package/dist/executors/bounded-exec/ram-temp.d.ts +17 -11
  26. package/dist/executors/bounded-exec/ram-temp.d.ts.map +1 -1
  27. package/dist/executors/bounded-exec/ram-temp.js +27 -13
  28. package/dist/generators/bun-test-tracing/generator.js +2 -2
  29. package/dist/graph-input-contract.d.ts +98 -0
  30. package/dist/graph-input-contract.d.ts.map +1 -0
  31. package/dist/graph-input-contract.js +624 -0
  32. package/dist/index.d.ts +12 -5
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +17 -3
  35. package/dist/managed-files/ci-workflow.d.ts.map +1 -1
  36. package/dist/managed-files/ci-workflow.js +5 -2
  37. package/dist/managed-files/publish-workflow.d.ts +11 -1
  38. package/dist/managed-files/publish-workflow.d.ts.map +1 -1
  39. package/dist/producer-receipts.d.ts +19 -0
  40. package/dist/producer-receipts.d.ts.map +1 -0
  41. package/dist/producer-receipts.js +921 -0
  42. package/dist/testing.d.ts +8 -0
  43. package/dist/testing.d.ts.map +1 -1
  44. package/dist/testing.js +58 -0
  45. package/managed/raw/patches/nx@23.2.1.patch +328 -50
  46. package/managed/raw/tooling/direnv/developer-links.ts +147 -21
  47. package/managed/raw/tooling/direnv/devenv.smoo.nix +7 -7
  48. package/managed/raw/tooling/direnv/github-actions-bootstrap.sh +14 -5
  49. package/managed/raw/tooling/direnv/linked-snapshots.ts +206 -40
  50. package/managed/raw/tooling/direnv/repo-path +15 -2
  51. package/managed/raw/tooling/direnv/setup-environment.ts +179 -114
  52. package/managed/templates/github/actions/cache-node-modules/action.yml +9 -0
  53. package/managed/templates/github/actions/setup-devenv/action.yml +63 -7
  54. package/nextest.toml +1 -1
  55. package/package.json +11 -6
  56. package/src/__tests__/fixture-nx-env.ts +7 -0
  57. package/src/__tests__/owned-installation.ts +174 -0
  58. package/src/bin/smoo-nx-bound-failures.test.ts +1 -1
  59. package/src/bounded-test-policy.test.ts +36 -22
  60. package/src/bounded-test-policy.ts +19 -27
  61. package/src/bun-bootstrap.test.ts +1 -1
  62. package/src/cargo-closure-input.test.ts +60 -11
  63. package/src/cargo-closure-input.ts +28 -6
  64. package/src/cargo-resolve-cache.test.ts +140 -25
  65. package/src/cargo-source-hash.test.ts +78 -3
  66. package/src/cargo-source-hash.ts +48 -30
  67. package/src/cross-check-policy.test.ts +2 -2
  68. package/src/ensure-built-receipt.test.ts +111 -16
  69. package/src/ensure-built-receipt.ts +251 -149
  70. package/src/ensure-built-witness.test.ts +197 -13
  71. package/src/ensure-built-witness.ts +187 -15
  72. package/src/ensure-built.test.ts +156 -102
  73. package/src/ensure-built.ts +114 -64
  74. package/src/executors/bounded-exec/cpu-pool.test.ts +116 -32
  75. package/src/executors/bounded-exec/cpu-pool.ts +55 -17
  76. package/src/executors/bounded-exec/cpu-tokens.test.ts +2 -2
  77. package/src/executors/bounded-exec/executor-host.test.ts +51 -41
  78. package/src/executors/bounded-exec/executor.test.ts +155 -35
  79. package/src/executors/bounded-exec/executor.ts +156 -45
  80. package/src/executors/bounded-exec/progress.test.ts +1 -1
  81. package/src/executors/bounded-exec/ram-temp-host.test.ts +46 -17
  82. package/src/executors/bounded-exec/ram-temp.test.ts +65 -3
  83. package/src/executors/bounded-exec/ram-temp.ts +32 -16
  84. package/src/executors/bounded-exec/verdict.test.ts +17 -12
  85. package/src/generators/bounded-test-targets/generator.test.ts +1 -3
  86. package/src/generators/bun-test-tracing/generator.test.ts +2 -2
  87. package/src/generators/bun-test-tracing/generator.ts +2 -2
  88. package/src/graph-input-contract.test.ts +371 -0
  89. package/src/graph-input-contract.ts +605 -0
  90. package/src/index.test.ts +3 -3
  91. package/src/index.ts +24 -3
  92. package/src/linked-snapshots.nx.test.ts +112 -30
  93. package/src/managed-files/ci-workflow.ts +5 -2
  94. package/src/managed-files/publish-workflow.ts +12 -1
  95. package/src/managed-files/repo-path.test.ts +44 -1
  96. package/src/managed-files/setup-devenv-free-disk.test.ts +95 -0
  97. package/src/nextest-code-bound.test.ts +23 -17
  98. package/src/nextest-partitions.test.ts +7 -1
  99. package/src/nx-cache-restore-mtime.test.ts +2 -2
  100. package/src/nx-daemon-claim.test.ts +5 -5
  101. package/src/nx-daemon-idle-cpu.test.ts +0 -1
  102. package/src/nx-daemon-idle-policy.test.ts +56 -0
  103. package/src/nx-daemon-ignore-files.test.ts +2 -2
  104. package/src/nx-daemon-validity.test.ts +31 -9
  105. package/src/nx-dot-input-policy.test.ts +5 -5
  106. package/src/nx-files-archive-racy.test.ts +1 -1
  107. package/src/nx-incomplete-run-summary.test.ts +1 -1
  108. package/src/nx-plugin-load-errors.test.ts +2 -2
  109. package/src/nx-project-graph-errors.test.ts +70 -0
  110. package/src/nx-skipped-task-exit.test.ts +2 -2
  111. package/src/nx-store-resolution.test.ts +7 -25
  112. package/src/nx-task-output-lease.test.ts +3 -3
  113. package/src/nx-use-local.test.ts +7 -5
  114. package/src/producer-receipts.test.ts +164 -0
  115. package/src/producer-receipts.ts +631 -0
  116. package/src/runtime-input.test.ts +1 -1
  117. package/src/serial-group-wiring.test.ts +4 -4
  118. package/src/task-results.test.ts +18 -16
  119. package/src/test-timings.test.ts +2 -2
  120. package/src/testing.test.ts +5 -5
  121. package/src/testing.ts +59 -0
  122. package/src/typecheck-test-policy.test.ts +1 -1
  123. package/src/typescript-resolution.test.ts +76 -0
  124. package/test-timings.json +5 -0
@@ -1,11 +1,25 @@
1
- import { expect, it } from 'bun:test';
1
+ import { afterAll, expect, it } 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,7 @@ 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';
23
38
  import { CARGO_CLOSURE_INPUT } from './cargo-closure-input.js';
24
39
  import {
25
40
  acquireCargoResolveLock,
@@ -31,6 +46,10 @@ import { createNodesV2 } from './index.js';
31
46
 
32
47
  useFixtureCargoHome();
33
48
 
49
+ /** The Nx installation this file's graph fixtures share; none may write into it. */
50
+ const installation = testFileInstallation('cargo-resolve-installation-');
51
+ afterAll(() => installation.retire());
52
+
34
53
  /*
35
54
  * What Cargo resolution costs, measured by the one number that matters: how many `cargo metadata`
36
55
  * children were actually started. A `cargo` ahead of the real one on PATH reports each child's life
@@ -49,7 +68,6 @@ useFixtureCargoHome();
49
68
 
50
69
  const sourceModule = join(import.meta.dir, 'cargo-source-hash.ts');
51
70
  const cliModule = join(import.meta.dir, 'bin', 'smoo-nx-cargo-hash.ts');
52
- const repositoryRoot = join(import.meta.dir, '../../..');
53
71
 
54
72
  const spawned = async (cargo: CountedCargo): Promise<number> => (await cargo.runs()).spawned;
55
73
 
@@ -81,7 +99,7 @@ function alive(pid: number): boolean {
81
99
  /** How a subprocess ended, with everything it printed. */
82
100
  interface Ended {
83
101
  readonly exitCode: number | null;
84
- readonly signalCode: NodeJS.Signals | null;
102
+ readonly signalCode: Bun.Subprocess['signalCode'];
85
103
  readonly stdout: string;
86
104
  readonly stderr: string;
87
105
  }
@@ -348,7 +366,7 @@ it('concurrent resolutions of one Cargo workspace share one cargo child, and an
348
366
  expect(await members()).toEqual(['after']);
349
367
  expect(await spawned(cargo)).toBe(2);
350
368
  });
351
- }, 20_000);
369
+ });
352
370
 
353
371
  it("a failed resolution rejects every sharer with a CargoMetadataError carrying Cargo's stderr, and is not kept for the next call", async () => {
354
372
  await withCannedWorkspace(async ({ cargo, answer, members, workspace, manifest }) => {
@@ -380,7 +398,7 @@ it("a failed resolution rejects every sharer with a CargoMetadataError carrying
380
398
  expect(await members()).toEqual(['recovered']);
381
399
  expect(await spawned(cargo)).toBe(2);
382
400
  });
383
- }, 20_000);
401
+ });
384
402
 
385
403
  it('a Cargo that cannot run, or whose answer is not metadata, is a CargoMetadataError', async () => {
386
404
  await withCannedWorkspace(async ({ cargo, workspace, manifest }) => {
@@ -395,7 +413,7 @@ it('a Cargo that cannot run, or whose answer is not metadata, is a CargoMetadata
395
413
  });
396
414
  expect(await spawned(cargo)).toBe(2);
397
415
  });
398
- }, 20_000);
416
+ });
399
417
 
400
418
  it('source edits, non-Rust edits and a rewrite of the same bytes never run Cargo', async () => {
401
419
  await withCannedWorkspace(async ({ root, cargo, answer, members, workspace }) => {
@@ -421,7 +439,7 @@ it('source edits, non-Rust edits and a rewrite of the same bytes never run Cargo
421
439
  }
422
440
  expect(await spawned(cargo)).toBe(1);
423
441
  });
424
- }, 20_000);
442
+ });
425
443
 
426
444
  interface KeyedFile {
427
445
  readonly name: string;
@@ -481,7 +499,10 @@ for (const file of KEYED_FILES) {
481
499
  expect(await resolvesAs('same bytes')).toEqual(['one']);
482
500
  expect(await spawned(cargo)).toBe(2);
483
501
 
502
+ // Identical size and mtime cannot stand in for the current bytes.
503
+ const before = await stat(join(root, file.path));
484
504
  await put(root, file.path, `${original}# two\n`);
505
+ await utimes(join(root, file.path), before.atime, before.mtime);
485
506
  expect(await resolvesAs('two')).toEqual(['two']);
486
507
  expect(await spawned(cargo)).toBe(3);
487
508
 
@@ -493,9 +514,54 @@ for (const file of KEYED_FILES) {
493
514
  expect(await resolvesAs('settled')).toEqual([file.removable ? 'removed' : 'two']);
494
515
  expect(await spawned(cargo)).toBe(file.removable ? 4 : 3);
495
516
  });
496
- }, 30_000);
517
+ });
497
518
  }
498
519
 
520
+ it('retargeting a configuration symlink with identical bytes still resolves the new canonical input', async () => {
521
+ await withCannedWorkspace(async ({ root, workspace, cargo, answer, members }) => {
522
+ const config = join(workspace, '.cargo/config.toml');
523
+ await put(root, 'config-a.toml', '[net]\noffline=true\n');
524
+ await put(root, 'config-b.toml', '[net]\noffline=true\n');
525
+ await mkdir(dirname(config), { recursive: true });
526
+ await symlink(join(root, 'config-a.toml'), config);
527
+ await answer('first target');
528
+ expect(await members()).toEqual(['first target']);
529
+ expect(await spawned(cargo)).toBe(1);
530
+
531
+ await rm(config);
532
+ await symlink(join(root, 'config-b.toml'), config);
533
+ await answer('second target');
534
+ expect(await members()).toEqual(['second target']);
535
+ expect(await spawned(cargo)).toBe(2);
536
+ await answer('unchanged');
537
+ expect(await members()).toEqual(['second target']);
538
+ expect(await spawned(cargo)).toBe(2);
539
+ });
540
+ });
541
+
542
+ it('a resolution input read failure is not a missing file or a reusable answer', async () => {
543
+ await withCannedWorkspace(async ({ workspace, manifest, cargo, answer }) => {
544
+ // Use the graph caller's inventory so this tests the resolution reader,
545
+ // independently of how the native workspace census treats a symlink loop.
546
+ const indexed = new Set(['Cargo.toml', 'crates/leaf/Cargo.toml']);
547
+ const members = async () => [...(await readCargoResolve(manifest, workspace, indexed)).members];
548
+ await answer('cold');
549
+ expect(await members()).toEqual(['cold']);
550
+ const config = join(workspace, '.cargo/config.toml');
551
+ await mkdir(dirname(config), { recursive: true });
552
+ await symlink('config.toml', config);
553
+ const failure = expectCargoMetadataError(await rejectionOf(members()), manifest);
554
+ expect(failure.message).toContain('ELOOP');
555
+ expect(failure.message).toContain(config);
556
+ expect(await spawned(cargo)).toBe(1);
557
+
558
+ await rm(config);
559
+ await answer('trap');
560
+ expect(await members()).toEqual(['cold']);
561
+ expect(await spawned(cargo)).toBe(1);
562
+ });
563
+ });
564
+
499
565
  it('resolves again exactly once when the cargo on PATH or the rustup selection changes', async () => {
500
566
  await withCannedWorkspace(async ({ root, cargo, answer, members, environment }) => {
501
567
  const resolvesAs = async (name: string, selection: Record<string, string> = {}): Promise<string[]> => {
@@ -527,7 +593,7 @@ it('resolves again exactly once when the cargo on PATH or the rustup selection c
527
593
  expect(await resolvesAs('same cargo', elsewhere)).toEqual(['another cargo']);
528
594
  expect(await spawned(cargo)).toBe(5);
529
595
  });
530
- }, 30_000);
596
+ });
531
597
 
532
598
  it('a discovered manifest outside the workspace, edited while the first resolution holds, is never answered from before the edit', async () => {
533
599
  await withCannedWorkspace(async ({ root, cargo, answer, members, workspace, manifest }) => {
@@ -550,7 +616,7 @@ it('a discovered manifest outside the workspace, edited while the first resoluti
550
616
  expect(await members()).toEqual(['after']);
551
617
  expect(await spawned(cargo)).toBe(2);
552
618
  });
553
- }, 20_000);
619
+ });
554
620
 
555
621
  it('an edit made while Cargo resolves is answered by a resolution that follows the first, never beside it', async () => {
556
622
  await withCannedWorkspace(async ({ cargo, answer, members, workspace, manifest }) => {
@@ -576,7 +642,7 @@ it('an edit made while Cargo resolves is answered by a resolution that follows t
576
642
  expect(await members()).toEqual(['after']);
577
643
  expect(await spawned(cargo)).toBe(2);
578
644
  });
579
- }, 20_000);
645
+ });
580
646
 
581
647
  it('an answer Cargo read after an edit is never kept for the workspace as it was before the edit', async () => {
582
648
  await withCannedWorkspace(async ({ cargo, answer, members, workspace, manifest }) => {
@@ -598,7 +664,7 @@ it('an answer Cargo read after an edit is never kept for the workspace as it was
598
664
  await answer('before');
599
665
  expect(await members()).toEqual(['before']);
600
666
  });
601
- }, 20_000);
667
+ });
602
668
 
603
669
  it('a process that has never resolved an unchanged workspace reads the answer an earlier one left, without Cargo', async () => {
604
670
  await withCannedWorkspace(async (fixture) => {
@@ -626,7 +692,7 @@ it('a process that has never resolved an unchanged workspace reads the answer an
626
692
  expect(await freshResolver(fixture, 'edited again').result).toEqual(edited);
627
693
  expect(await spawned(cargo)).toBe(2);
628
694
  });
629
- }, 60_000);
695
+ });
630
696
 
631
697
  it('fresh processes that ask at once for a workspace nobody has resolved share one cargo child', async () => {
632
698
  await withCannedWorkspace(async (fixture) => {
@@ -645,7 +711,7 @@ it('fresh processes that ask at once for a workspace nobody has resolved share o
645
711
  expect(results[0]).toMatchObject({ members: ['cold'] });
646
712
  expect(await spawned(cargo)).toBe(1);
647
713
  });
648
- }, 60_000);
714
+ });
649
715
 
650
716
  it('a worker that exits on SIGTERM while Cargo resolves leaves no cargo child behind', async () => {
651
717
  await withCannedWorkspace(async ({ root, workspace, manifest, cargo, answer, environment }) => {
@@ -673,7 +739,7 @@ it('a worker that exits on SIGTERM while Cargo resolves leaves no cargo child be
673
739
  // The child's end is the end of its connection to the fixture, killed before it answered.
674
740
  await cargo.waitForDisconnects([pid]);
675
741
  });
676
- }, 20_000);
742
+ });
677
743
 
678
744
  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
745
  await withCannedWorkspace(async (fixture) => {
@@ -730,7 +796,7 @@ it("a worker that exits with callers waiting on two resolutions leaves none of C
730
796
  expect(await freshResolver(fixture, 'again').result).toEqual(next);
731
797
  expect(await spawned(cargo)).toBe(3);
732
798
  });
733
- }, 60_000);
799
+ });
734
800
 
735
801
  // A standalone `smoo-nx-cargo-hash` has no handler of its own, so a signal would end it on the spot,
736
802
  // before any exit hook could take the Cargo it started along. The module forwards the signal to
@@ -754,7 +820,7 @@ for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP'] as const) {
754
820
  expect(ended.signalCode, proc.describe()).toBe(signal);
755
821
  await cargo.waitForDisconnects(running);
756
822
  });
757
- }, 30_000);
823
+ });
758
824
  }
759
825
 
760
826
  /* ---- The same, with the real Cargo, through the project graph and the hash command ---- */
@@ -808,7 +874,7 @@ async function graphFixture(root: string): Promise<string> {
808
874
  };
809
875
  for (const [path, text] of Object.entries(files)) await put(root, path, text);
810
876
  execFileSync('git', ['init', '--quiet', workspace], { stdio: 'pipe' });
811
- await symlink(join(repositoryRoot, 'node_modules'), join(workspace, 'node_modules'), 'dir');
877
+ await symlink(await installation.nodeModules(), join(workspace, 'node_modules'), 'dir');
812
878
  relock(workspace);
813
879
  return workspace;
814
880
  }
@@ -912,7 +978,7 @@ it('a project graph over an unchanged Cargo workspace runs Cargo once, however o
912
978
  expect(byFile(await graph())).toEqual(edited);
913
979
  expect(await spawned(cargo)).toBe(expected + 1);
914
980
  });
915
- }, 120_000);
981
+ });
916
982
 
917
983
  it('a Cargo workspace Cargo refuses fails the project graph with a CargoMetadataError, and no runtime hash stands in', async () => {
918
984
  await withGraphWorkspace(async ({ workspace, cargo, graph }) => {
@@ -937,7 +1003,56 @@ it('a Cargo workspace Cargo refuses fails the project graph with a CargoMetadata
937
1003
  expect(byFile(await graph())).toEqual(repaired);
938
1004
  expect(await spawned(cargo)).toBe(4);
939
1005
  });
940
- }, 120_000);
1006
+ });
1007
+
1008
+ for (const replaced of [false, true]) {
1009
+ it(`cache publication records a ${replaced ? 'rebound' : 'missing'} parent with the original filesystem cause`, async () => {
1010
+ await withGraphWorkspace(async ({ workspace, cargo }) => {
1011
+ const manifest = join(workspace, 'Cargo.toml');
1012
+ await cargo.beforeAnswer.close();
1013
+ const refused = rejectionOf(readCargoResolve(manifest, workspace));
1014
+ await cargo.waitForRuns((runs) => runs.read === 1, 'real locked/offline Cargo to read before cache publication');
1015
+ const namespace = join(workspaceDataDirectoryForWorkspace(workspace), 'cargo-resolve');
1016
+ const entries = await readdir(namespace);
1017
+ expect(entries).toHaveLength(1);
1018
+ const [entry] = entries;
1019
+ if (entry === undefined) throw new Error('the real resolver created no owned cache namespace');
1020
+ const directory = join(namespace, entry);
1021
+ const before = await stat(directory, { bigint: true });
1022
+ let atOpen = before;
1023
+ if (replaced) {
1024
+ await rename(directory, `${directory}.retired`);
1025
+ await mkdir(directory);
1026
+ atOpen = await stat(directory, { bigint: true });
1027
+ expect(atOpen.ino).not.toBe(before.ino);
1028
+ // Force publication to report the replacement rather than silently sign under a new namespace.
1029
+ await mkdir(join(directory, 'entry.cache'));
1030
+ } else {
1031
+ await rm(directory, { recursive: true });
1032
+ }
1033
+ await cargo.beforeAnswer.open();
1034
+ const failure = expectCargoMetadataError(await refused, manifest);
1035
+ expect(failure.message).toContain(directory);
1036
+ expect(failure.message).toContain('entry.cache.');
1037
+ expect(failure.message).toContain(
1038
+ `"parentBeforeLock":${JSON.stringify({ state: 'present', dev: before.dev.toString(), ino: before.ino.toString() })}`,
1039
+ );
1040
+ if (replaced) {
1041
+ const expected = JSON.stringify({ state: 'present', dev: atOpen.dev.toString(), ino: atOpen.ino.toString() });
1042
+ expect(failure.message).toContain(`"parentAtTmpOpen":${expected}`);
1043
+ expect(failure.message).toContain(`"parentAfterFailure":${expected}`);
1044
+ } else {
1045
+ expect(failure.message).toContain('"parentAtTmpOpen":{"state":"unavailable","code":"ENOENT"');
1046
+ expect(failure.message).toContain('"parentAfterFailure":{"state":"unavailable","code":"ENOENT"');
1047
+ }
1048
+ const publication = failure.cause;
1049
+ expect(publication).toBeInstanceOf(Error);
1050
+ if (!(publication instanceof Error)) throw new Error('cache publication lost its structured cause');
1051
+ expect(publication.cause).toHaveProperty('code', replaced ? 'EISDIR' : 'ENOENT');
1052
+ expect(await spawned(cargo)).toBe(1);
1053
+ });
1054
+ });
1055
+ }
941
1056
 
942
1057
  it('fresh smoo-nx-cargo-hash processes over an unchanged Cargo workspace run Cargo once between them', async () => {
943
1058
  await withGraphWorkspace(async ({ root, workspace, cargo }) => {
@@ -982,7 +1097,7 @@ it('fresh smoo-nx-cargo-hash processes over an unchanged Cargo workspace run Car
982
1097
  expect(await hash()).toBe(manifestEdited);
983
1098
  expect(await spawned(cargo)).toBe(2);
984
1099
  });
985
- }, 120_000);
1100
+ });
986
1101
 
987
1102
  it('a Cargo child that never answers is killed and named at the resolve bound', async () => {
988
1103
  await withCannedWorkspace(async ({ cargo, answer, workspace, manifest }) => {
@@ -995,7 +1110,7 @@ it('a Cargo child that never answers is killed and named at the resolve bound',
995
1110
  await cargo.beforeAnswer.open();
996
1111
  }
997
1112
  });
998
- }, 20_000);
1113
+ });
999
1114
 
1000
1115
  it('a held resolve lock times out with its name and elapsed wait and leaves no lock child', async () => {
1001
1116
  const root = await realpath(await mkdtemp(join(tmpdir(), 'cargo-resolve-lock-')));
@@ -1023,7 +1138,7 @@ it('a held resolve lock times out with its name and elapsed wait and leaves no l
1023
1138
  } finally {
1024
1139
  await rm(root, { recursive: true, force: true });
1025
1140
  }
1026
- }, 20_000);
1141
+ });
1027
1142
 
1028
1143
  it('a successful resolve lock lease holds the kernel lock until its child is released and reaped', async () => {
1029
1144
  const root = await realpath(await mkdtemp(join(tmpdir(), 'cargo-resolve-lease-')));
@@ -1041,4 +1156,4 @@ it('a successful resolve lock lease holds the kernel lock until its child is rel
1041
1156
  } finally {
1042
1157
  await rm(root, { recursive: true, force: true });
1043
1158
  }
1044
- }, 20_000);
1159
+ });
@@ -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
  }
@@ -117,7 +117,7 @@ describe('Linux cross-check policy', () => {
117
117
  } finally {
118
118
  await rm(project, { recursive: true, force: true });
119
119
  }
120
- }, 60_000);
120
+ });
121
121
 
122
122
  it('fails closed on Darwin without the linux-cross compiler instead of compiling', () => {
123
123
  // Without this guard a Darwin cache miss sits in ring's cc-rs looking for
@@ -167,7 +167,7 @@ describe('Linux cross-check policy', () => {
167
167
  } finally {
168
168
  await rm(root, { recursive: true, force: true });
169
169
  }
170
- }, 30_000);
170
+ });
171
171
 
172
172
  it('pins clippy to the committed lockfile and local cache', () => {
173
173
  expect(cargoFrozen('clippy --workspace')).toBe('cargo --frozen clippy --workspace');