@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
@@ -0,0 +1,174 @@
1
+ /**
2
+ * A fixture's own copy of the repository's Nx installation, and the check that nothing wrote into it.
3
+ *
4
+ * The graph witness binds node stamps (ctime included) of every file in the closure of Nx, this plugin and
5
+ * TypeScript (README "Ancestor directories bind..."). Linked from the repository, that closure is the host's: on CI
6
+ * its files are hardlinks in the shared Bun store, and any other task that installs, restores or cleans changes their
7
+ * link count, so their ctime, so a fixture's installation identity, between two calls of one test. A fixture must not
8
+ * take an input it does not own.
9
+ *
10
+ * So the closure is copied, exactly as the witness's own census resolves it in the repository: each package once,
11
+ * with the census's own exclusions (`node_modules`, `.git`, `.nx`), each dependency edge relinked beside its copy as
12
+ * Bun's isolated layout does, the top-level packages' bins in `.bin`. Every copy is a new inode, cloned where the
13
+ * volume allows and written otherwise, so no link count is shared with anything outside its owner.
14
+ *
15
+ * A test file makes one copy, on first use, shared by its fixtures; its `afterAll` retires it, failing the suite and
16
+ * naming the changed nodes if any fixture wrote into it.
17
+ */
18
+ import { constants } from 'node:fs';
19
+ import { cp, mkdir, readFile, rm, symlink } from 'node:fs/promises';
20
+ import { basename, dirname, join, relative } from 'node:path';
21
+ import { expandOutputs } from 'nx/src/native';
22
+ import { readModulePackageJson } from 'nx/src/utils/package-json';
23
+ import typia from 'typia';
24
+ import {
25
+ type GraphInstallationCensus,
26
+ graphInstallationCensus,
27
+ graphInstallationIdentity,
28
+ } from '../ensure-built-witness.js';
29
+ import { nxFixtureRoot } from './fixture-nx-env.js';
30
+
31
+ const repositoryRoot = join(import.meta.dir, '../../../..');
32
+
33
+ /** The configuration the census resolves: Nx, this plugin and TypeScript. */
34
+ const CENSUS_NX_JSON = { plugins: ['@smoothbricks/nx-plugin'] };
35
+
36
+ /** An installation made under `root`, and its identity when the copy was made. */
37
+ interface OwnedInstallation {
38
+ readonly root: string;
39
+ readonly identity: string;
40
+ }
41
+
42
+ /** The graph witness's installation identity resolved from `root`; an unproved installation fails loudly. */
43
+ function installationIdentity(root: string): string {
44
+ let unproved = 'no detail';
45
+ const identity = graphInstallationIdentity(
46
+ root,
47
+ CENSUS_NX_JSON,
48
+ readModulePackageJson,
49
+ expandOutputs,
50
+ null,
51
+ (detail) => {
52
+ unproved = detail;
53
+ },
54
+ );
55
+ if (identity === null) throw new Error(`the Nx installation resolved from ${root} is unproved: ${unproved}`);
56
+ return identity;
57
+ }
58
+
59
+ /** Copy the repository's installation closure into `root/node_modules`; `root` is an empty directory the caller owns.
60
+ *
61
+ * Only the closure is read from the repository, never its proof: the repository's installation is the host's, whose
62
+ * shared store other tasks relink while the census reads it, which changes node stamps and would make every test that
63
+ * copies it fail for the host's work rather than its own. The copy, which the fixture owns, is what gets proved.
64
+ */
65
+ async function makeOwnedInstallation(root: string): Promise<OwnedInstallation> {
66
+ let unread = 'no detail';
67
+ const census = graphInstallationCensus(
68
+ repositoryRoot,
69
+ CENSUS_NX_JSON,
70
+ readModulePackageJson,
71
+ expandOutputs,
72
+ null,
73
+ (detail) => {
74
+ unread = detail;
75
+ },
76
+ );
77
+ if (census === null) throw new Error(`the Nx installation closure of ${repositoryRoot} cannot be read: ${unread}`);
78
+ const { resolutions } = census;
79
+ const modules = join(root, 'node_modules');
80
+ // Each source package root's copy, inside a store directory whose node_modules also holds its dependency links.
81
+ const copies = new Map<
82
+ string,
83
+ { readonly store: string; readonly copy: string; readonly bin: string | Record<string, string> | undefined }
84
+ >();
85
+ for (const [, , manifest] of resolutions) {
86
+ if (manifest === null || copies.has(dirname(manifest))) continue;
87
+ const { name, bin } = typia.json.assertParse<{ name: string; bin?: string | Record<string, string> }>(
88
+ await readFile(manifest, 'utf8'),
89
+ );
90
+ const store = join(modules, '.store', String(copies.size), 'node_modules');
91
+ copies.set(dirname(manifest), { store, copy: join(store, name), bin });
92
+ }
93
+ const copyOf = (source: string) => {
94
+ const copied = copies.get(source);
95
+ if (copied === undefined) throw new Error(`${source} resolves dependencies but is not in the census`);
96
+ return copied;
97
+ };
98
+ await Promise.all(
99
+ [...copies].map(([source, { copy }]) =>
100
+ cp(source, copy, {
101
+ recursive: true,
102
+ verbatimSymlinks: true,
103
+ mode: constants.COPYFILE_FICLONE,
104
+ filter: (path) => path === source || !['node_modules', '.git', '.nx'].includes(basename(path)),
105
+ }),
106
+ ),
107
+ );
108
+ for (const [from, name, manifest] of resolutions) {
109
+ if (manifest === null) continue;
110
+ const link = join(from === repositoryRoot ? modules : copyOf(from).store, name);
111
+ await mkdir(dirname(link), { recursive: true });
112
+ await symlink(relative(dirname(link), copyOf(dirname(manifest)).copy), link, 'dir');
113
+ if (from !== repositoryRoot) continue;
114
+ const { bin } = copyOf(dirname(manifest));
115
+ const commands = typeof bin === 'string' ? { [basename(name)]: bin } : (bin ?? {});
116
+ for (const [command, path] of Object.entries(commands)) {
117
+ await mkdir(join(modules, '.bin'), { recursive: true });
118
+ await symlink(relative(join(modules, '.bin'), join(link, path)), join(modules, '.bin', command));
119
+ }
120
+ }
121
+ return { root, identity: installationIdentity(root) };
122
+ }
123
+
124
+ /**
125
+ * Remove an installation, failing, with the changed nodes named, if its identity is no longer the one it was made
126
+ * with: the proof that its sharers only read it.
127
+ */
128
+ async function retireOwnedInstallation({ root, identity }: OwnedInstallation): Promise<void> {
129
+ try {
130
+ const retired = installationIdentity(root);
131
+ if (retired === identity) return;
132
+ const entries = (census: string) => {
133
+ const { nodes, files } = typia.json.assertParse<GraphInstallationCensus>(census);
134
+ return new Set([
135
+ ...nodes.map(({ path, stamp }) => `${path} ${stamp}`),
136
+ ...files.map(({ path, sha256 }) => `${path} ${sha256}`),
137
+ ]);
138
+ };
139
+ const made = entries(identity);
140
+ const now = entries(retired);
141
+ const changed = [
142
+ ...[...made].filter((entry) => !now.has(entry)).map((entry) => `- ${entry}`),
143
+ ...[...now].filter((entry) => !made.has(entry)).map((entry) => `+ ${entry}`),
144
+ ];
145
+ throw new Error(`a fixture changed the installation it shares, in ${root}:\n${changed.slice(0, 20).join('\n')}`);
146
+ } finally {
147
+ await rm(root, { recursive: true, force: true });
148
+ }
149
+ }
150
+
151
+ /** One test file's installation: made on first use and shared by its fixtures, retired by the file's `afterAll`. */
152
+ export interface TestFileInstallation {
153
+ /** The `node_modules` a fixture workspace links. */
154
+ readonly nodeModules: () => Promise<string>;
155
+ /** Fails if a fixture wrote into the copy; a file that never used it has nothing to retire. */
156
+ readonly retire: () => Promise<void>;
157
+ }
158
+
159
+ /**
160
+ * The installation one test file owns, in a fixture root named by `prefix`. Call once per file, at module scope:
161
+ * Bun runs many test files in one process, and each must own its copy.
162
+ */
163
+ export function testFileInstallation(prefix: string): TestFileInstallation {
164
+ let made: Promise<OwnedInstallation> | undefined;
165
+ return {
166
+ nodeModules: async () => {
167
+ made ??= nxFixtureRoot(prefix).then(makeOwnedInstallation);
168
+ return join((await made).root, 'node_modules');
169
+ },
170
+ retire: async () => {
171
+ if (made !== undefined) await retireOwnedInstallation(await made);
172
+ },
173
+ };
174
+ }
@@ -106,7 +106,7 @@ it('names the failed dependency Nx recorded in cacheDir, not the checkout-local
106
106
  if (published) await retireFixtureSocketDirectory(workspace);
107
107
  await rm(root, { recursive: true, force: true });
108
108
  }
109
- }, 90_000);
109
+ });
110
110
 
111
111
  function nxPath(script: string, env: NodeJS.ProcessEnv): string {
112
112
  const printed = spawnSync('node', ['-e', script], { cwd: repositoryRoot, env, encoding: 'utf8' });
@@ -9,9 +9,9 @@ import {
9
9
  BOUNDED_TEST_EXECUTOR,
10
10
  BOUNDED_TEST_IDLE_TIMEOUT_MS,
11
11
  BOUNDED_TEST_KILL_AFTER_MS,
12
- BOUNDED_TEST_PER_TEST_TIMEOUT_MS,
13
12
  type BoundedTestPolicyPackageJson,
14
13
  type BoundedTestPolicyProjectJson,
14
+ BUN_TEST_TIMEOUT_FLAG,
15
15
  boundedTestScriptAlias,
16
16
  checkBoundedTestTargetPolicy,
17
17
  checkWorkspaceBoundedTestTargetPolicy,
@@ -21,7 +21,7 @@ import {
21
21
  } from './bounded-test-policy.js';
22
22
  import type { ResolvedProjectTargets } from './package-target-policy.js';
23
23
 
24
- const TIMEOUT_FLAG = `--timeout=${BOUNDED_TEST_PER_TEST_TIMEOUT_MS}`;
24
+ const TIMEOUT_FLAG = BUN_TEST_TIMEOUT_FLAG;
25
25
  const BOUNDED_POLICY_MESSAGE = `nx.targets.test must use ${BOUNDED_TEST_EXECUTOR} or delegate through no-op targets to bounded test execution`;
26
26
 
27
27
  describe('bounded test target policy', () => {
@@ -226,37 +226,51 @@ describe('bounded test target policy', () => {
226
226
  }
227
227
  });
228
228
 
229
- it("accepts explicit Bun per-test timeouts up to each bounded leg's progress bound", () => {
229
+ it('accepts a bounded bun leg only when it deletes Bun per-test deadline', () => {
230
230
  const packageJson: BoundedTestPolicyPackageJson = {
231
231
  nx: { targets: { test: { executor: 'nx:noop', dependsOn: ['napi-test'] } } },
232
232
  };
233
- const check = (command: string, idleTimeoutMs = 600_000) => {
233
+ const check = (command: string) => {
234
234
  const resolvedProject = resolvedAggregateProject();
235
235
  resolvedProject.targetOptions = new Map([
236
- ['napi-test', { command, cwd: '{projectRoot}', idleTimeoutMs, killAfterMs: BOUNDED_TEST_KILL_AFTER_MS }],
236
+ [
237
+ 'napi-test',
238
+ { command, cwd: '{projectRoot}', idleTimeoutMs: 600_000, killAfterMs: BOUNDED_TEST_KILL_AFTER_MS },
239
+ ],
237
240
  ]);
238
241
  return checkBoundedTestTargetPolicy(packageJson, { projectName: 'cowshed', resolvedProject });
239
242
  };
240
- expect(check('bun test --timeout=600000')).toBe(true);
241
- expect(check('bun test --timeout 600000')).toBe(true);
242
- expect(check('bun test --timeout=1')).toBe(true);
243
- expect(check('bun test --timeout=30000', 30_000)).toBe(true);
243
+ expect(TIMEOUT_FLAG).toBe('--timeout=0');
244
+ expect(check(`bun test ${TIMEOUT_FLAG}`)).toBe(true);
245
+ expect(check(`bun test --config=../bunfig.toml ${TIMEOUT_FLAG} launcher.test.ts`)).toBe(true);
244
246
  for (const command of [
245
247
  'bun test',
246
248
  'bun test --timeout',
247
- 'bun test --timeout=0',
248
- 'bun test --timeout=-1',
249
- 'bun test --timeout=1.5',
250
- 'bun test --timeout=bad',
251
- 'bun test --timeout=9007199254740992',
252
- 'bun test --timeout=600001',
253
- 'bun test --timeout=30000 --timeout=600001',
254
- 'bun test --timeout=30000 --timeout',
255
- 'bun test --timeout=30000 --timeout=',
249
+ 'bun test --timeout=',
250
+ 'bun test --timeout 0',
251
+ 'bun test --timeout=600000',
252
+ 'bun test --timeout=30000',
253
+ `bun test ${TIMEOUT_FLAG} --timeout=30000`,
254
+ `bun test ${TIMEOUT_FLAG} --timeout`,
256
255
  ]) {
257
256
  expect(check(command)).toBe(false);
258
257
  }
259
- expect(check('bun test --timeout=600000', BOUNDED_TEST_IDLE_TIMEOUT_MS)).toBe(false);
258
+ });
259
+
260
+ it('lets a test outlive Bun default deadline under the flag the policy writes', async () => {
261
+ const scratch = await mkdtemp(join(tmpdir(), 'bun-no-deadline-'));
262
+ try {
263
+ const testFile = join(scratch, 'slow.test.ts');
264
+ // Bun's deadline is real time, so only a real wait past 5000 ms shows the flag deletes it.
265
+ await writeFile(
266
+ testFile,
267
+ "import { test } from 'bun:test';\ntest('outlives 5000 ms', () => Bun.sleep(5_200));\n",
268
+ );
269
+ const run = Bun.spawnSync([process.execPath, 'test', TIMEOUT_FLAG, testFile], { cwd: scratch });
270
+ expect({ exitCode: run.exitCode, stderr: run.stderr.toString() }).toMatchObject({ exitCode: 0 });
271
+ } finally {
272
+ await rm(scratch, { recursive: true, force: true });
273
+ }
260
274
  });
261
275
 
262
276
  it('checks every test leg selected by Nx target wildcards', () => {
@@ -430,13 +444,13 @@ describe('bounded test target policy', () => {
430
444
  expect(resolveTestCommand(packageJson)).toBe(`bun test ${TIMEOUT_FLAG}`);
431
445
  });
432
446
 
433
- it('idempotently appends --timeout to bare bun test commands', () => {
447
+ it('idempotently writes the no-deadline --timeout into bare bun test commands', () => {
434
448
  expect(ensureBunTestTimeoutFlag('bun test')).toBe(`bun test ${TIMEOUT_FLAG}`);
435
449
  expect(ensureBunTestTimeoutFlag('bun test --pass-with-no-tests')).toBe(
436
450
  `bun test ${TIMEOUT_FLAG} --pass-with-no-tests`,
437
451
  );
438
452
  expect(ensureBunTestTimeoutFlag(`bun test ${TIMEOUT_FLAG}`)).toBe(`bun test ${TIMEOUT_FLAG}`);
439
- expect(ensureBunTestTimeoutFlag('bun test --timeout=10')).toBe(`bun test ${TIMEOUT_FLAG}`);
453
+ expect(ensureBunTestTimeoutFlag('bun test --timeout=30000')).toBe(`bun test ${TIMEOUT_FLAG}`);
440
454
  expect(ensureBunTestTimeoutFlag('bun test --timeout 10 --bail')).toBe(`bun test ${TIMEOUT_FLAG} --bail`);
441
455
  // Non-bun-test commands are left alone (vitest, custom runners, etc.).
442
456
  expect(ensureBunTestTimeoutFlag('vitest run')).toBe('vitest run');
@@ -532,7 +546,7 @@ describe('bounded test target policy', () => {
532
546
  const shard = {
533
547
  executor: BOUNDED_TEST_EXECUTOR,
534
548
  options: {
535
- command: 'bun test --timeout=600000 --shard=1/2',
549
+ command: `bun test ${TIMEOUT_FLAG} --shard=1/2`,
536
550
  cwd: '{projectRoot}',
537
551
  idleTimeoutMs: 600_000,
538
552
  killAfterMs: BOUNDED_TEST_KILL_AFTER_MS,
@@ -17,15 +17,18 @@ export const BOUNDED_TEST_EXECUTOR = '@smoothbricks/nx-plugin:bounded-exec';
17
17
  * A test target's one bound: the `idleTimeoutMs` with which no test may go unfinished, the hang backstop of
18
18
  * specs/cowshed/08_testing.md. It is no wall-clock ceiling: a suite that keeps finishing tests runs as long as it
19
19
  * needs. It is the longest any single test may run, so it stays above every slow-timeout class in the plugin's
20
- * nextest.toml and every bun `--timeout`.
20
+ * nextest.toml; a bun leg has no per-test deadline of its own (`BUN_TEST_TIMEOUT_FLAG`).
21
21
  */
22
22
  export const BOUNDED_TEST_IDLE_TIMEOUT_MS = 180_000;
23
23
  export const BOUNDED_TEST_KILL_AFTER_MS = 10_000;
24
- // Per-test timeout passed to `bun test --timeout=<ms>`. Bun's default is
25
- // 5000ms which is too tight for git-fixture tests on slower CI runners
26
- // (Actions). The bunfig.toml `[test] timeout` key is silently ignored by
27
- // Bun — the only working surfaces are this CLI flag and `setDefaultTimeout()`.
28
- export const BOUNDED_TEST_PER_TEST_TIMEOUT_MS = 30_000;
24
+ /**
25
+ * Deletes Bun's per-test deadline: 5000 ms unless the command sets one, and Bun ignores a bunfig `[test] timeout`, so
26
+ * the flag is the one place to set it. `0` means no deadline (measured on the pinned Bun 1.4.2: a test blocked 12 s in
27
+ * `spawnSync` and one sleeping 7 s both pass under `--timeout=0`). A test waits for the event it is waiting for, and
28
+ * the leg's `idleTimeoutMs` ends a test that never returns; no per-test bound kills a test, however long a loaded host
29
+ * makes its work take (specs/cowshed/08_testing.md).
30
+ */
31
+ export const BUN_TEST_TIMEOUT_FLAG = '--timeout=0';
29
32
 
30
33
  export interface BoundedTestPolicyPackageJson {
31
34
  name?: string;
@@ -428,7 +431,7 @@ function isBoundedExecutionTarget(executor: unknown, rawOptions: unknown, allowe
428
431
  // A test leg is bounded by progress alone: a wall-clock ceiling fails a suite that is only slow.
429
432
  rawOptions.timeoutMs === undefined &&
430
433
  isPositiveSafeInteger(rawOptions.idleTimeoutMs) &&
431
- bunTestTimeoutIsBounded(command, rawOptions.idleTimeoutMs) &&
434
+ bunTestHasNoDeadline(command) &&
432
435
  typeof rawOptions.cwd === 'string' &&
433
436
  // `bun test` walks its working directory looking for test files, so it must start where that walk is cheap: the
434
437
  // project root or its `src/`. Any other command names what it runs and has no walk to bound. A cargo workspace's
@@ -439,21 +442,14 @@ function isBoundedExecutionTarget(executor: unknown, rawOptions: unknown, allowe
439
442
  );
440
443
  }
441
444
 
442
- /** A bun leg's per-test `--timeout` must fire before the leg's progress bound would. */
443
- function bunTestTimeoutIsBounded(command: string, idleTimeoutMs: number): boolean {
445
+ /** A bun leg deletes Bun's per-test deadline with `BUN_TEST_TIMEOUT_FLAG` and sets no other. */
446
+ function bunTestHasNoDeadline(command: string): boolean {
444
447
  if (!BUN_TEST_PREFIX.test(command)) {
445
448
  return true;
446
449
  }
447
450
  let found = false;
448
- for (const match of command.matchAll(/(?:^|\s)--timeout(?==|\s|$)(?:=(\S*)|\s+(\S+))?/g)) {
449
- const value = match[1] ?? match[2];
450
- const perTestTimeoutMs = Number(value);
451
- if (
452
- value === undefined ||
453
- !/^\d+$/.test(value) ||
454
- !isPositiveSafeInteger(perTestTimeoutMs) ||
455
- perTestTimeoutMs > idleTimeoutMs
456
- ) {
451
+ for (const match of command.matchAll(/(?:^|\s)(--timeout(?==|\s|$)\S*)/g)) {
452
+ if (match[1] !== BUN_TEST_TIMEOUT_FLAG) {
457
453
  return false;
458
454
  }
459
455
  found = true;
@@ -605,23 +601,19 @@ function resolveTargetCommand(existingTarget: unknown): string | null {
605
601
  const BUN_TEST_PREFIX = /^bun\s+test(?=\s|$)/;
606
602
  const EXISTING_BUN_TIMEOUT = /(^|\s)--timeout(?:=|\s+)(\S+)/;
607
603
 
608
- // Bun's `[test] timeout` bunfig key is silently ignored — only the CLI flag
609
- // and `setDefaultTimeout()` actually take effect. Normalize every `bun test`
610
- // command so the policy enforces the workspace per-test timeout in the one
611
- // place where Bun will honor it.
612
- export function ensureBunTestTimeoutFlag(command: string, timeoutMs = BOUNDED_TEST_PER_TEST_TIMEOUT_MS): string {
604
+ // Normalize every `bun test` command to `BUN_TEST_TIMEOUT_FLAG`, the one place Bun honors a per-test bound.
605
+ export function ensureBunTestTimeoutFlag(command: string): string {
613
606
  if (!BUN_TEST_PREFIX.test(command)) {
614
607
  return command;
615
608
  }
616
- const flag = `--timeout=${timeoutMs}`;
617
609
  const existing = EXISTING_BUN_TIMEOUT.exec(command);
618
610
  if (!existing) {
619
- return command.replace(BUN_TEST_PREFIX, `bun test ${flag}`);
611
+ return command.replace(BUN_TEST_PREFIX, () => `bun test ${BUN_TEST_TIMEOUT_FLAG}`);
620
612
  }
621
- if (existing[2] === String(timeoutMs)) {
613
+ if (existing[0].trimStart() === BUN_TEST_TIMEOUT_FLAG) {
622
614
  return command;
623
615
  }
624
- return command.replace(EXISTING_BUN_TIMEOUT, `${existing[1]}${flag}`);
616
+ return command.replace(EXISTING_BUN_TIMEOUT, (_match, lead: string) => `${lead}${BUN_TEST_TIMEOUT_FLAG}`);
625
617
  }
626
618
 
627
619
  function isPackageTestScriptRunnerCommand(command: string): boolean {
@@ -67,7 +67,7 @@ describe('Bun bootstrap imports', () => {
67
67
  expect(typeof policy.BOUNDED_TEST_EXECUTOR).toBe('string');
68
68
  expect(typeof policy.BOUNDED_TEST_IDLE_TIMEOUT_MS).toBe('number');
69
69
  expect(typeof policy.BOUNDED_TEST_KILL_AFTER_MS).toBe('number');
70
- expect(typeof policy.BOUNDED_TEST_PER_TEST_TIMEOUT_MS).toBe('number');
70
+ expect(typeof policy.BUN_TEST_TIMEOUT_FLAG).toBe('string');
71
71
  });
72
72
 
73
73
  it('imports workspace-config-policy', async () => {
@@ -1,4 +1,4 @@
1
- import { expect, it } from 'bun:test';
1
+ import { afterAll, expect, it } from 'bun:test';
2
2
  import { execFile, execFileSync } from 'node:child_process';
3
3
  import { appendFile, mkdir, mkdtemp, readFile, realpath, rm, stat, symlink, utimes, writeFile } from 'node:fs/promises';
4
4
  import { tmpdir } from 'node:os';
@@ -19,6 +19,7 @@ import {
19
19
  withEnvironment,
20
20
  } from './__tests__/counted-cargo.js';
21
21
  import { useFixtureCargoHome } from './__tests__/fixture-cargo-home.js';
22
+ import { testFileInstallation } from './__tests__/owned-installation.js';
22
23
  import { runtimeInputValue } from './__tests__/runtime-input.js';
23
24
  import { CARGO_CLOSURE_INPUT, indexedCargoManifests } from './cargo-closure-input.js';
24
25
  import { hashCargoPathInputs } from './cargo-source-hash.js';
@@ -28,6 +29,10 @@ const repositoryRoot = join(import.meta.dir, '../../..');
28
29
 
29
30
  useFixtureCargoHome();
30
31
 
32
+ /** The Nx installation this file's fixtures share; none may write into it. */
33
+ const installation = testFileInstallation('cargo-closure-installation-');
34
+ afterAll(() => installation.retire());
35
+
31
36
  /**
32
37
  * An Nx workspace that is also the Cargo workspace. `app` reaches `leaf`
33
38
  * through `bridge`, and `external` — outside the Nx workspace — through
@@ -85,7 +90,7 @@ async function closureFixture(
85
90
  await writeFile(join(root, path), text);
86
91
  }
87
92
  execFileSync('git', ['init', '--quiet', workspace], { stdio: 'pipe' });
88
- await symlink(join(repositoryRoot, 'node_modules'), join(workspace, 'node_modules'), 'dir');
93
+ await symlink(await installation.nodeModules(), join(workspace, 'node_modules'), 'dir');
89
94
  execFileSync('cargo', ['generate-lockfile', '--offline', '--manifest-path', join(workspace, 'Cargo.toml')], {
90
95
  stdio: 'pipe',
91
96
  });
@@ -150,7 +155,7 @@ it('keys a custom target on exactly its Cargo closure, inside the workspace and
150
155
  } finally {
151
156
  await rm(root, { recursive: true, force: true });
152
157
  }
153
- }, 120_000);
158
+ });
154
159
 
155
160
  it('keys literal compiled-in data inside and outside crate directories without keying comments or unrelated crates', async () => {
156
161
  const root = await realpath(await mkdtemp(join(tmpdir(), 'cargo-compiled-data-')));
@@ -208,7 +213,51 @@ it('keys literal compiled-in data inside and outside crate directories without k
208
213
  } finally {
209
214
  await rm(root, { recursive: true, force: true });
210
215
  }
211
- }, 120_000);
216
+ });
217
+
218
+ it('names no compiled-in build output, so a producer run leaves the closure it was hashed under unchanged', async () => {
219
+ const root = await realpath(await mkdtemp(join(tmpdir(), 'cargo-compiled-output-')));
220
+ try {
221
+ const { workspace } = await closureFixture(
222
+ root,
223
+ 'node_modules/\ntarget/\ndist/\n.nx/\ncrates/leaf/src/generated/\n',
224
+ {
225
+ 'workspace/crates/leaf/src/lib.rs': [
226
+ 'pub fn answer() -> u8 { 1 }',
227
+ 'pub const TABLE: &[u8] = include_bytes!("generated/table.bin");',
228
+ 'pub const SKILL: &str = include_str!("../../../skills/SKILL.md");',
229
+ ].join('\n'),
230
+ 'workspace/skills/SKILL.md': 'skill-one',
231
+ },
232
+ );
233
+ // A producer's run: ignored outputs, content-named ones among them, and a generated source including those.
234
+ const generated = join(workspace, 'crates/leaf/src/generated');
235
+ const produce = async (content: string) => {
236
+ await rm(generated, { recursive: true, force: true });
237
+ await mkdir(generated, { recursive: true });
238
+ await writeFile(join(generated, 'table.bin'), content);
239
+ await writeFile(join(generated, `chunk-${content}.js`), content);
240
+ await writeFile(
241
+ join(generated, 'vocabulary.rs'),
242
+ `pub const CHUNK: &str = include_str!("chunk-${content}.js");\n`,
243
+ );
244
+ };
245
+ const closure = async () => {
246
+ resetWorkspaceContext();
247
+ return closureOf(byFile(await graphComputation(workspace)()), 'packages/app');
248
+ };
249
+
250
+ const unproduced = await closure();
251
+ expect(unproduced).toContain('{workspaceRoot}/skills/SKILL.md');
252
+ expect(JSON.stringify(unproduced)).not.toContain('generated/');
253
+ await produce('one');
254
+ expect(await closure()).toEqual(unproduced);
255
+ await produce('two');
256
+ expect(await closure()).toEqual(unproduced);
257
+ } finally {
258
+ await rm(root, { recursive: true, force: true });
259
+ }
260
+ });
212
261
 
213
262
  it('refuses a closure member in an ignored directory, which no fileset can see, instead of hashing the whole workspace', async () => {
214
263
  const root = await realpath(await mkdtemp(join(tmpdir(), 'cargo-closure-ignored-')));
@@ -226,7 +275,7 @@ it('refuses a closure member in an ignored directory, which no fileset can see,
226
275
  } finally {
227
276
  await rm(root, { recursive: true, force: true });
228
277
  }
229
- }, 120_000);
278
+ });
230
279
 
231
280
  it('leaves a closure inside the workspace to Nx: no process runs when its tasks are hashed', async () => {
232
281
  const root = await realpath(await mkdtemp(join(tmpdir(), 'cargo-closure-inferred-')));
@@ -257,7 +306,7 @@ it('leaves a closure inside the workspace to Nx: no process runs when its tasks
257
306
  } finally {
258
307
  await rm(root, { recursive: true, force: true });
259
308
  }
260
- }, 120_000);
309
+ });
261
310
 
262
311
  /** `leaf` as the fixture writes it, and the dependency that draws `unrelated` into every closure reaching `leaf`. */
263
312
  const LEAF_MANIFEST = '[package]\nname="leaf"\nversion="0.1.0"\nedition="2021"\n';
@@ -333,7 +382,7 @@ it('delegates counted Cargo through the caller launcher without re-entering its
333
382
  await fixtureCargo?.release();
334
383
  await rm(root, { recursive: true, force: true });
335
384
  }
336
- }, 30_000);
385
+ });
337
386
 
338
387
  it('shares one Cargo child among overlapping graph computations, and an unchanged workspace never asks Cargo again', async () => {
339
388
  const root = await realpath(await mkdtemp(join(tmpdir(), 'cargo-closure-overlap-')));
@@ -388,7 +437,7 @@ it('shares one Cargo child among overlapping graph computations, and an unchange
388
437
  await fixtureCargo?.release();
389
438
  await rm(root, { recursive: true, force: true });
390
439
  }
391
- }, 120_000);
440
+ });
392
441
 
393
442
  it('refuses with a typed error what Cargo refuses, and follows an edit made while a child holds its answer with a resolution after it', async () => {
394
443
  const root = await realpath(await mkdtemp(join(tmpdir(), 'cargo-closure-pending-')));
@@ -454,7 +503,7 @@ it('refuses with a typed error what Cargo refuses, and follows an edit made whil
454
503
  await fixtureCargo?.release();
455
504
  await rm(root, { recursive: true, force: true });
456
505
  }
457
- }, 120_000);
506
+ });
458
507
 
459
508
  it("indexes a source tree's Cargo manifests and none of the runtime state a cowshed keeps in it", async () => {
460
509
  const root = await realpath(await mkdtemp(join(tmpdir(), 'cargo-closure-runtime-state-')));
@@ -477,7 +526,7 @@ it("indexes a source tree's Cargo manifests and none of the runtime state a cows
477
526
  } finally {
478
527
  await rm(root, { recursive: true, force: true });
479
528
  }
480
- }, 120_000);
529
+ });
481
530
 
482
531
  const SOURCE_FILE = 'src/lib.rs';
483
532
 
@@ -551,4 +600,4 @@ it("keeps a cowshed's runtime state from waking the watcher that recomputes the
551
600
  const paths = await watchedPaths(await readFile(join(repositoryRoot, '.nxignore'), 'utf8'));
552
601
  expect(paths).toContain(SOURCE_FILE);
553
602
  expect(paths.filter((path) => path.startsWith('.cowshed'))).toEqual([]);
554
- }, 120_000);
603
+ });
@@ -60,6 +60,8 @@ const GLOB_SYNTAX = /[*?[\]{}()!,]/;
60
60
  */
61
61
  export interface CargoClosureSource {
62
62
  readonly manifest: string;
63
+ /** The Nx workspace root as the computation names it, which Nx's file index is keyed by. */
64
+ readonly workspaceRoot: string;
63
65
  /** The canonical Nx workspace root. */
64
66
  readonly root: string;
65
67
  readonly cargo: CargoResolve;
@@ -90,7 +92,7 @@ export async function resolveCargoClosureSource(
90
92
  ): Promise<CargoClosureSource> {
91
93
  const [root, index] = await Promise.all([realpath(workspaceRoot), indexed]);
92
94
  const cargo = await readCargoResolve(join(root, manifest), root, index);
93
- return { manifest, root, cargo, indexed: index, compiledFilesCache };
95
+ return { manifest, workspaceRoot, root, cargo, indexed: index, compiledFilesCache };
94
96
  }
95
97
 
96
98
  /**
@@ -112,6 +114,16 @@ export async function resolveCargoClosureSource(
112
114
  * An in-workspace member missing from Nx's file index is a typed refusal,
113
115
  * never a whole-workspace runtime hash. Only outside-workspace members need
114
116
  * the external-only runtime input.
117
+ *
118
+ * A compiled-in file is named only when Nx's file index holds both it and the
119
+ * source that includes it. An ignored one is a build output: no fileset can
120
+ * hash its bytes, which reach a consumer through its producer's dependency
121
+ * outputs instead, so naming it would add nothing to any task's key except
122
+ * the names of whatever output last ran. That state is exactly what a project
123
+ * graph must not read (`globIndexedFiles`): a producer that regenerates
124
+ * content-named files would otherwise move every key of the graph it was
125
+ * hashed under, and the run that compiled a tree would leave its verdict
126
+ * under a key no later run of the same tree computes.
115
127
  */
116
128
  export async function cargoClosureInputs(
117
129
  projectRoot: string,
@@ -140,6 +152,7 @@ async function workspaceClosureInputs(projectRoot: string, source: CargoClosureS
140
152
  const { root, cargo, indexed } = source;
141
153
  const packageDirectories: string[] = [];
142
154
  const files: string[] = [];
155
+ const compiledIn: { readonly declaring: string; readonly file: string }[] = [];
143
156
  const compiledFiles = new Set<string>();
144
157
  let external = false;
145
158
  try {
@@ -154,10 +167,13 @@ async function workspaceClosureInputs(projectRoot: string, source: CargoClosureS
154
167
  if (!indexed.has(posix.join(directory, 'Cargo.toml'))) {
155
168
  throw new Error(`the Cargo package ${directory} is not in Nx's file index (an ignored directory)`);
156
169
  }
157
- for (const { file } of compiledInFiles(pkg.directory, source.compiledFilesCache)) {
158
- const path = indexablePath(root, file);
159
- if (path === null) throw new Error(`${directory} compiles ${file}, which Nx's file index cannot hold`);
160
- compiledFiles.add(path);
170
+ for (const compiled of compiledInFiles(pkg.directory, source.compiledFilesCache)) {
171
+ const file = indexablePath(root, compiled.file);
172
+ if (file === null) throw new Error(`${directory} compiles ${compiled.file}, which Nx's file index cannot hold`);
173
+ // The scan starts inside this package's indexable directory, so its sources can always be named.
174
+ const declaring = indexablePath(root, compiled.source);
175
+ if (declaring === null) throw new Error(`${compiled.source} was scanned outside ${directory}`);
176
+ compiledIn.push({ declaring, file });
161
177
  }
162
178
  packageDirectories.push(directory);
163
179
  for (const file of [...pkg.sources, pkg.governingManifest]) {
@@ -166,8 +182,14 @@ async function workspaceClosureInputs(projectRoot: string, source: CargoClosureS
166
182
  files.push(path);
167
183
  }
168
184
  }
169
- const unglobbable = [...packageDirectories, ...files, ...compiledFiles].find((path) => GLOB_SYNTAX.test(path));
185
+ const compiledPaths = [...new Set(compiledIn.flatMap(({ declaring, file }) => [declaring, file]))];
186
+ const unglobbable = [...packageDirectories, ...files, ...compiledPaths].find((path) => GLOB_SYNTAX.test(path));
170
187
  if (unglobbable !== undefined) throw new Error(`${unglobbable} contains glob syntax, so no fileset can name it`);
188
+ // Literal paths, so each matches exactly itself in the index.
189
+ const held = new Set(compiledPaths.length === 0 ? [] : await globIndexedFiles(source.workspaceRoot, compiledPaths));
190
+ for (const { declaring, file } of compiledIn) {
191
+ if (held.has(declaring) && held.has(file)) compiledFiles.add(file);
192
+ }
171
193
  } catch (error) {
172
194
  throw new CargoClosureInputError(projectRoot, error);
173
195
  }