@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
@@ -0,0 +1,113 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { mkdir, stat, symlink, utimes, writeFile } from 'node:fs/promises';
3
+ import { dirname, join } from 'node:path';
4
+
5
+ import type { CreateNodesResultV2 } from 'nx/src/devkit-exports.js';
6
+ import { CARGO_CLOSURE_INPUT } from '../cargo-closure-input.js';
7
+ import { createNodesV2 } from '../index.js';
8
+ import type { TestFileInstallation } from '../owned-installation.js';
9
+
10
+ /**
11
+ * An Nx workspace that is also the Cargo workspace. `app` reaches `leaf`
12
+ * through `bridge`, and `external` — outside the Nx workspace — through
13
+ * `bridge` too. `unrelated` is a member nothing depends on. `app` declares a
14
+ * custom cached target keyed on its closure.
15
+ * `extraFiles` (paths relative to `root`) are written with the rest, last.
16
+ * `installation` is the calling test file's own Nx installation.
17
+ */
18
+ export async function closureFixture(
19
+ installation: TestFileInstallation,
20
+ root: string,
21
+ gitignore = 'node_modules/\ntarget/\ndist/\n.nx/\n',
22
+ extraFiles: Record<string, string> = {},
23
+ ) {
24
+ const workspace = join(root, 'workspace');
25
+ const files: Record<string, string> = {
26
+ 'workspace/.gitignore': gitignore,
27
+ 'workspace/package.json':
28
+ '{"name":"cargo-closure-fixture","private":true,"workspaces":["packages/*","crates/*"]}\n',
29
+ 'workspace/nx.json': JSON.stringify({
30
+ plugins: ['@smoothbricks/nx-plugin'],
31
+ namedInputs: { externalRustCrates: [] },
32
+ }),
33
+ 'workspace/Cargo.toml':
34
+ '[workspace]\nmembers=["packages/app","crates/bridge","crates/leaf","crates/unrelated"]\nresolver="2"\n',
35
+ 'workspace/packages/app/package.json': JSON.stringify({
36
+ name: 'app',
37
+ private: true,
38
+ nx: {
39
+ targets: {
40
+ compile: {
41
+ executor: 'nx:run-commands',
42
+ cache: true,
43
+ inputs: [CARGO_CLOSURE_INPUT],
44
+ options: { command: 'cargo build --quiet --locked --offline --manifest-path packages/app/Cargo.toml' },
45
+ },
46
+ },
47
+ },
48
+ }),
49
+ 'workspace/packages/app/Cargo.toml':
50
+ '[package]\nname="app"\nversion="0.1.0"\nedition="2021"\n[dependencies]\nbridge={path="../../crates/bridge"}\n',
51
+ 'workspace/packages/app/src/main.rs': 'fn main() { println!("{}", bridge::answer()); }\n',
52
+ 'workspace/crates/bridge/Cargo.toml':
53
+ '[package]\nname="bridge"\nversion="0.1.0"\nedition="2021"\n[dependencies]\nleaf={path="../leaf"}\nexternal={path="../../../external"}\n',
54
+ 'workspace/crates/bridge/src/lib.rs': 'pub fn answer() -> u8 { leaf::answer() + external::answer() }\n',
55
+ 'workspace/crates/leaf/package.json': '{"name":"leaf","private":true}\n',
56
+ 'workspace/crates/leaf/Cargo.toml': '[package]\nname="leaf"\nversion="0.1.0"\nedition="2021"\n',
57
+ 'workspace/crates/leaf/src/lib.rs': 'pub fn answer() -> u8 { 1 }\n',
58
+ 'workspace/crates/unrelated/Cargo.toml': '[package]\nname="unrelated"\nversion="0.1.0"\nedition="2021"\n',
59
+ 'workspace/crates/unrelated/src/lib.rs': 'pub fn unrelated() -> u8 { 3 }\n',
60
+ 'external/Cargo.toml': '[package]\nname="external"\nversion="0.1.0"\nedition="2021"\n[workspace]\n',
61
+ 'external/src/lib.rs': 'pub fn answer() -> u8 { 10 }\n',
62
+ ...extraFiles,
63
+ };
64
+ for (const [path, text] of Object.entries(files)) {
65
+ await mkdir(dirname(join(root, path)), { recursive: true });
66
+ await writeFile(join(root, path), text);
67
+ }
68
+ execFileSync('git', ['init', '--quiet', workspace], { stdio: 'pipe' });
69
+ await symlink(await installation.nodeModules(), join(workspace, 'node_modules'), 'dir');
70
+ execFileSync('cargo', ['generate-lockfile', '--offline', '--manifest-path', join(workspace, 'Cargo.toml')], {
71
+ stdio: 'pipe',
72
+ });
73
+
74
+ /**
75
+ * Rewrite a fixture file as an edit Nx can see. Nx keeps each file's hash
76
+ * beside its mtime in whole seconds and reuses the hash until that second
77
+ * changes, so a rewrite inside the second the file was last hashed in is
78
+ * invisible to every fileset input. A fast host runs this whole fixture in
79
+ * about a second; the edit is dated at least a second past the old mtime.
80
+ */
81
+ async function edit(path: string, text: string): Promise<void> {
82
+ const file = join(root, path);
83
+ const { mtimeMs } = await stat(file);
84
+ await writeFile(file, text);
85
+ const edited = new Date(Math.max(Date.now(), mtimeMs + 1000));
86
+ await utimes(file, edited, edited);
87
+ }
88
+ return { workspace, edit };
89
+ }
90
+
91
+ /** One project-graph computation over the fixture: the plugin's `createNodes`, as Nx runs it for each recomputation. */
92
+ export function graphComputation(workspace: string) {
93
+ const [, infer] = createNodesV2;
94
+ return async () =>
95
+ infer(['package.json', 'packages/app/package.json', 'crates/leaf/package.json'], undefined, {
96
+ workspaceRoot: workspace,
97
+ nxJsonConfiguration: { namedInputs: { externalRustCrates: [] } },
98
+ });
99
+ }
100
+
101
+ /** The computation's nodes in file order: the plugin pushes them as their projects finish. */
102
+ export function byFile(graph: CreateNodesResultV2): CreateNodesResultV2 {
103
+ return [...graph].sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));
104
+ }
105
+
106
+ /** The `cargoClosure` definition the computation gave the project at `projectRoot`. */
107
+ export function closureOf(graph: CreateNodesResultV2, projectRoot: string) {
108
+ return (
109
+ graph.find(([file]) => dirname(file) === projectRoot)?.[1].projects?.[projectRoot]?.namedInputs?.[
110
+ CARGO_CLOSURE_INPUT
111
+ ] ?? []
112
+ );
113
+ }
@@ -11,6 +11,7 @@ import { type QueryableSpan, querySpan } from '@smoothbricks/lmao/testing';
11
11
  import { useTestSpan } from '@smoothbricks/lmao/testing/bun';
12
12
  import { AggregateCreateNodesError } from 'nx/src/project-graph/error-types.js';
13
13
  import { CargoMetadataError } from '../cargo-source-hash.js';
14
+ import { BOUNDED_TEST_IDLE_TIMEOUT_MS } from '../test-backstop.js';
14
15
  import { bindListener } from '../testing.js';
15
16
  import { BROKER_HOST, encodeOrder, type ProcessReport, parseReport, readLines } from './counted-cargo-process.js';
16
17
 
@@ -63,19 +64,6 @@ export function cargoMetadataRuns(events: readonly CargoMetadataEvent[]): CargoM
63
64
  return { spawned: pids.length, read, peak, pids, grandchildren };
64
65
  }
65
66
 
66
- /**
67
- * How long an awaited event may take before its guard says what is still open: inside the tests'
68
- * own 20 s budgets, so the report reaches the test before the runner's timeout does. A guard only
69
- * ever fails a wait; nothing advances on it.
70
- */
71
- const GUARD_MS = 15_000;
72
-
73
- /**
74
- * The guard over the real Cargo: above the slowest real resolution seen behind a contended package
75
- * cache (21 s), below Bun's 30 s default test timeout, which those tests run under or exceed.
76
- */
77
- const REAL_CARGO_GUARD_MS = 25_000;
78
-
79
67
  /** The test spans still open under `span`, itself included: the work a hung test is still inside. */
80
68
  function openSpans<T extends LogSchema>(span: QueryableSpan<T>, open: string[]): string[] {
81
69
  // Row 1 holds a span's completion; its timestamp stays 0 until the span ends.
@@ -88,14 +76,17 @@ function openSpans<T extends LogSchema>(span: QueryableSpan<T>, open: string[]):
88
76
  * `operation`, settling exactly as it does, unless no event settles it within `timeoutMs`: then it
89
77
  * rejects with `what`, the test spans still open and `diagnostics()`. The test span is taken now, so
90
78
  * call this from the test's own async context. `signal` disarms the guard; the result still follows
91
- * `operation`.
79
+ * `operation`. The default is the leg's no-progress backstop: a guard that fires sooner races a
80
+ * loaded host (a 15 s and a 30 s guard failed slow but healthy daemon and Cargo waits), so it only
81
+ * names what was still open when a wait truly hangs. A guard only ever fails a wait; nothing advances
82
+ * on it.
92
83
  */
93
84
  export function guardEvent<T>(
94
85
  operation: Promise<T>,
95
86
  what: string,
96
87
  diagnostics: () => string | Promise<string>,
97
88
  signal?: AbortSignal,
98
- timeoutMs = GUARD_MS,
89
+ timeoutMs = BOUNDED_TEST_IDLE_TIMEOUT_MS,
99
90
  ): Promise<T> {
100
91
  let spans: () => string;
101
92
  try {
@@ -324,8 +315,6 @@ async function shim(
324
315
  root: string,
325
316
  forward: string,
326
317
  initial: string | null,
327
- /** How long the fixture's waits may take: longer over the real Cargo. */
328
- guardMs: number,
329
318
  ): Promise<{ cargo: CountedCargo; answer(text: string): void }> {
330
319
  const path = process.env.PATH ?? '';
331
320
  const real = Bun.which('cargo', { PATH: path });
@@ -542,8 +531,6 @@ async function shim(
542
531
  verdict(() => (connections.size === 0 ? true : null)),
543
532
  'releasing the counted Cargo',
544
533
  describe,
545
- undefined,
546
- guardMs,
547
534
  );
548
535
  } catch (error) {
549
536
  // A process still connected is still running, so its pid is still its own: kill it and, for a
@@ -616,8 +603,6 @@ async function shim(
616
603
  }),
617
604
  `waiting for ${what}`,
618
605
  describe,
619
- undefined,
620
- guardMs,
621
606
  ),
622
607
  waitForDisconnects: async (pids) => {
623
608
  await guardEvent(
@@ -634,8 +619,6 @@ async function shim(
634
619
  }),
635
620
  `waiting for ${pids.join(', ')} to die`,
636
621
  describe,
637
- undefined,
638
- guardMs,
639
622
  );
640
623
  },
641
624
  release: () => {
@@ -653,7 +636,7 @@ async function shim(
653
636
 
654
637
  /** The real Cargo, counted: `metadata` prints what the real `cargo metadata` prints. */
655
638
  export async function countedCargo(root: string): Promise<CountedCargo> {
656
- const { cargo } = await shim(root, 'exec "$real" "$@"', null, REAL_CARGO_GUARD_MS);
639
+ const { cargo } = await shim(root, 'exec "$real" "$@"', null);
657
640
  return cargo;
658
641
  }
659
642
 
@@ -663,7 +646,7 @@ export async function countedCargo(root: string): Promise<CountedCargo> {
663
646
  * not depend on.
664
647
  */
665
648
  export async function cannedCargo(root: string): Promise<CannedCargo> {
666
- const { cargo, answer } = await shim(root, 'exec env -u RUSTUP_TOOLCHAIN -u RUSTUP_HOME "$real" "$@"', '', GUARD_MS);
649
+ const { cargo, answer } = await shim(root, 'exec env -u RUSTUP_TOOLCHAIN -u RUSTUP_HOME "$real" "$@"', '');
667
650
  return {
668
651
  ...cargo,
669
652
  answerWith: async (document) => answer(JSON.stringify(document)),
@@ -0,0 +1,27 @@
1
+ import { watch } from 'node:fs';
2
+
3
+ /**
4
+ * Resolves once `ready` holds: checked when the watch is armed and again on every change in `directory`, so a change
5
+ * made before the watch exists is still seen. The wait ends on a filesystem event, never on a timer; one that never
6
+ * comes is the leg's no-progress bound to report.
7
+ */
8
+ export function whenChanged(directory: string, ready: () => boolean): Promise<void> {
9
+ const { promise, resolve, reject } = Promise.withResolvers<void>();
10
+ const watcher = watch(directory, () => check());
11
+ function check(): void {
12
+ try {
13
+ if (!ready()) return;
14
+ watcher.close();
15
+ resolve();
16
+ } catch (error) {
17
+ watcher.close();
18
+ reject(error);
19
+ }
20
+ }
21
+ watcher.once('error', (error) => {
22
+ watcher.close();
23
+ reject(error);
24
+ });
25
+ check();
26
+ return promise;
27
+ }
@@ -42,6 +42,12 @@ const repositoryRoot = join(import.meta.dir, '../../../..');
42
42
  * daemons of one workspace bind two paths. With the directory named, they bind
43
43
  * one: a test whose subject is two daemons on two socket paths names a second
44
44
  * directory for the second. Building the environment publishes nothing.
45
+ *
46
+ * NX_NATIVE_FILE_CACHE_DIRECTORY is the fixture's own too. Nx loads its native
47
+ * binding from a copy in that cache, by default `/tmp/.nx/<uid>/native-cache`,
48
+ * which every Nx on the host shares and any `nx reset` deletes. A load that loses
49
+ * that race falls back to Nx's WASI binding without a word, and fails later on
50
+ * what WASI lacks (`FileLock is not a constructor`, from a task output lease).
45
51
  */
46
52
  export function fixtureNxEnv(workspace: string, socketDirectory: string): Record<string, string> {
47
53
  const env: Record<string, string> = {};
@@ -59,6 +65,7 @@ export function fixtureNxEnv(workspace: string, socketDirectory: string): Record
59
65
  NX_SOCKET_DIR: socketDirectory,
60
66
  NX_WORKSPACE_DATA_DIRECTORY: join(workspace, '.nx/workspace-data'),
61
67
  NX_CACHE_DIRECTORY: join(workspace, '.nx/cache'),
68
+ NX_NATIVE_FILE_CACHE_DIRECTORY: join(workspace, '.nx/native-file-cache'),
62
69
  };
63
70
  }
64
71
 
@@ -0,0 +1,14 @@
1
+ /** This repository's fixtures own a copy of its Nx installation (`../owned-installation.ts`) in an Nx fixture root. */
2
+ import { join } from 'node:path';
3
+ import { ownedInstallation, type TestFileInstallation } from '../owned-installation.js';
4
+ import { nxFixtureRoot } from './fixture-nx-env.js';
5
+
6
+ const repositoryRoot = join(import.meta.dir, '../../../..');
7
+
8
+ /**
9
+ * The installation one test file owns, in a fixture root named by `prefix`. Call once per file, at module scope:
10
+ * Bun runs many test files in one process, and each must own its copy.
11
+ */
12
+ export function testFileInstallation(prefix: string): TestFileInstallation {
13
+ return ownedInstallation(repositoryRoot, () => nxFixtureRoot(prefix));
14
+ }
@@ -0,0 +1,12 @@
1
+ import { censusStart, SAME_TICK_NS } from '../ensure-built-witness.js';
2
+
3
+ /**
4
+ * Returns once a census started from then on proves every node that changed before the call: until then such a census
5
+ * records it unproven (ensure-built-witness.ts, `unproven`), and a reader distrusts its stamp. A node's change time is
6
+ * at most the wall clock at the call, which `censusStart` reads to the millisecond below, so the wait ends one
7
+ * millisecond and {@link SAME_TICK_NS} past that reading. It waits on the clock the rule reads, not a guessed delay.
8
+ */
9
+ export async function pastTick(): Promise<void> {
10
+ const proven = censusStart() + 1_000_000n + SAME_TICK_NS;
11
+ while (censusStart() < proven) await Bun.sleep(1);
12
+ }
@@ -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' });
@@ -0,0 +1,29 @@
1
+ #!/usr/bin/env node
2
+ import { findClockOracles, formatClockOracle, TEST_CLOCK_ORACLE } from '../test-clock-policy.js';
3
+ import { diffScope, upstreamBase } from '../test-walk-policy.js';
4
+
5
+ // TEST-CLOCK-ORACLE over the current directory's repository, judged on the cases changed since the upstream merge base
6
+ // (`upstreamBase`, the base `smoo-nx-test-walks --base` prints for the lint target's runtime input). Every finding
7
+ // prints `error[…]` and exits 1. Exit 2 when git cannot answer.
8
+ if (process.argv.length > 2) {
9
+ process.stderr.write('usage: smoo-nx-test-clocks\n');
10
+ process.exit(2);
11
+ }
12
+ const root = process.cwd();
13
+ const base = upstreamBase(root);
14
+ if (!base.ok) {
15
+ process.stderr.write(`${TEST_CLOCK_ORACLE.id} cannot find the upstream base: ${base.reason}\n`);
16
+ process.exit(2);
17
+ }
18
+ const scope = diffScope(root, base.value);
19
+ if (!scope.ok) {
20
+ process.stderr.write(`${TEST_CLOCK_ORACLE.id} cannot read the changes since ${base.value}: ${scope.reason}\n`);
21
+ process.exit(2);
22
+ }
23
+ const oracles = findClockOracles(root, scope.value.files, scope.value.changes);
24
+ for (const oracle of oracles) process.stderr.write(`${formatClockOracle(oracle)}\n`);
25
+ if (oracles.length > 0) process.exit(1);
26
+ process.stdout.write(
27
+ `${TEST_CLOCK_ORACLE.id} passed: no changed test case carries a runner deadline, bounds elapsed host time or races ` +
28
+ `a configured bound against a timer (base ${base.value}).\n`,
29
+ );
@@ -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,
@@ -10,22 +10,19 @@ import {
10
10
  } from './cargo-workspace.js';
11
11
  import { writeJsonFile } from './managed-files/managed-format.js';
12
12
  import type { PackageTargetPolicyOptions, ResolvedProjectTargets } from './package-target-policy.js';
13
+ import { BOUNDED_TEST_IDLE_TIMEOUT_MS, BOUNDED_TEST_KILL_AFTER_MS } from './test-backstop.js';
13
14
  import { isTestRunnerTargetName } from './workspace-config-policy.js';
14
15
 
16
+ export { BOUNDED_TEST_IDLE_TIMEOUT_MS, BOUNDED_TEST_KILL_AFTER_MS } from './test-backstop.js';
15
17
  export const BOUNDED_TEST_EXECUTOR = '@smoothbricks/nx-plugin:bounded-exec';
16
18
  /**
17
- * A test target's one bound: the `idleTimeoutMs` with which no test may go unfinished, the hang backstop of
18
- * specs/cowshed/08_testing.md. It is no wall-clock ceiling: a suite that keeps finishing tests runs as long as it
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`.
19
+ * Deletes Bun's per-test deadline: 5000 ms unless the command sets one, and Bun ignores a bunfig `[test] timeout`, so
20
+ * 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
21
+ * `spawnSync` and one sleeping 7 s both pass under `--timeout=0`). A test waits for the event it is waiting for, and
22
+ * the leg's `idleTimeoutMs` ends a test that never returns; no per-test bound kills a test, however long a loaded host
23
+ * makes its work take (specs/cowshed/08_testing.md).
21
24
  */
22
- export const BOUNDED_TEST_IDLE_TIMEOUT_MS = 180_000;
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;
25
+ export const BUN_TEST_TIMEOUT_FLAG = '--timeout=0';
29
26
 
30
27
  export interface BoundedTestPolicyPackageJson {
31
28
  name?: string;
@@ -428,7 +425,7 @@ function isBoundedExecutionTarget(executor: unknown, rawOptions: unknown, allowe
428
425
  // A test leg is bounded by progress alone: a wall-clock ceiling fails a suite that is only slow.
429
426
  rawOptions.timeoutMs === undefined &&
430
427
  isPositiveSafeInteger(rawOptions.idleTimeoutMs) &&
431
- bunTestTimeoutIsBounded(command, rawOptions.idleTimeoutMs) &&
428
+ bunTestHasNoDeadline(command) &&
432
429
  typeof rawOptions.cwd === 'string' &&
433
430
  // `bun test` walks its working directory looking for test files, so it must start where that walk is cheap: the
434
431
  // project root or its `src/`. Any other command names what it runs and has no walk to bound. A cargo workspace's
@@ -439,21 +436,14 @@ function isBoundedExecutionTarget(executor: unknown, rawOptions: unknown, allowe
439
436
  );
440
437
  }
441
438
 
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 {
439
+ /** A bun leg deletes Bun's per-test deadline with `BUN_TEST_TIMEOUT_FLAG` and sets no other. */
440
+ function bunTestHasNoDeadline(command: string): boolean {
444
441
  if (!BUN_TEST_PREFIX.test(command)) {
445
442
  return true;
446
443
  }
447
444
  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
- ) {
445
+ for (const match of command.matchAll(/(?:^|\s)(--timeout(?==|\s|$)\S*)/g)) {
446
+ if (match[1] !== BUN_TEST_TIMEOUT_FLAG) {
457
447
  return false;
458
448
  }
459
449
  found = true;
@@ -605,23 +595,19 @@ function resolveTargetCommand(existingTarget: unknown): string | null {
605
595
  const BUN_TEST_PREFIX = /^bun\s+test(?=\s|$)/;
606
596
  const EXISTING_BUN_TIMEOUT = /(^|\s)--timeout(?:=|\s+)(\S+)/;
607
597
 
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 {
598
+ // Normalize every `bun test` command to `BUN_TEST_TIMEOUT_FLAG`, the one place Bun honors a per-test bound.
599
+ export function ensureBunTestTimeoutFlag(command: string): string {
613
600
  if (!BUN_TEST_PREFIX.test(command)) {
614
601
  return command;
615
602
  }
616
- const flag = `--timeout=${timeoutMs}`;
617
603
  const existing = EXISTING_BUN_TIMEOUT.exec(command);
618
604
  if (!existing) {
619
- return command.replace(BUN_TEST_PREFIX, `bun test ${flag}`);
605
+ return command.replace(BUN_TEST_PREFIX, () => `bun test ${BUN_TEST_TIMEOUT_FLAG}`);
620
606
  }
621
- if (existing[2] === String(timeoutMs)) {
607
+ if (existing[0].trimStart() === BUN_TEST_TIMEOUT_FLAG) {
622
608
  return command;
623
609
  }
624
- return command.replace(EXISTING_BUN_TIMEOUT, `${existing[1]}${flag}`);
610
+ return command.replace(EXISTING_BUN_TIMEOUT, (_match, lead: string) => `${lead}${BUN_TEST_TIMEOUT_FLAG}`);
625
611
  }
626
612
 
627
613
  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 () => {
@@ -0,0 +1,50 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+ import fc from 'fast-check';
3
+
4
+ import { type CompiledInclusion, indexedCompiledFiles } from './cargo-closure-input.js';
5
+
6
+ // The pre-push key once moved with the disk rather than the tree: a compiled-in file was named whether or not Nx's
7
+ // file index held it, so a build output an `include_str!` reads keyed whatever run last wrote it. These inclusions and
8
+ // index answers are generated, with no workspace, Cargo or Nx in them.
9
+ describe('the compiled-in files a cargo closure key names', () => {
10
+ /** Under a directory no generated tree path names, so the index never holds what lies there. */
11
+ const OUTPUT = 'z-out/';
12
+ const path = fc
13
+ .array(fc.stringMatching(/^[a-y]{1,4}$/), { minLength: 1, maxLength: 3 })
14
+ .map((segments) => segments.join('/'));
15
+ const inclusion = fc.record({ declaring: path, file: path });
16
+ // A compiled-in file the index does not hold, or one only an unindexed source includes.
17
+ const offIndex = fc.oneof(
18
+ fc.record({ declaring: path, file: path.map((file) => `${OUTPUT}${file}`) }),
19
+ fc.record({ declaring: path.map((source) => `${OUTPUT}${source}`), file: path }),
20
+ );
21
+ const scenario = fc
22
+ .record({
23
+ inclusions: fc.array(inclusion, { maxLength: 8 }),
24
+ offIndex: fc.array(offIndex, { minLength: 1, maxLength: 4 }),
25
+ })
26
+ .chain(({ inclusions, offIndex }) => {
27
+ const tree = [...new Set([...inclusions, ...offIndex].flatMap(({ declaring, file }) => [declaring, file]))];
28
+ return fc
29
+ .subarray(tree.filter((candidate) => !candidate.startsWith(OUTPUT)))
30
+ .map((held) => ({ inclusions, offIndex, held: new Set(held) }));
31
+ });
32
+ const bothHeld =
33
+ (held: ReadonlySet<string>) =>
34
+ ({ declaring, file }: CompiledInclusion): boolean =>
35
+ held.has(declaring) && held.has(file);
36
+
37
+ it('names each held file a held source includes, nothing else, and no off-index include_str! target moves it', () => {
38
+ fc.assert(
39
+ fc.property(scenario, ({ inclusions, offIndex, held }) => {
40
+ const named = indexedCompiledFiles(inclusions, held);
41
+ for (const file of named) {
42
+ expect(inclusions.some((included) => included.file === file && bothHeld(held)(included))).toBe(true);
43
+ }
44
+ for (const included of inclusions.filter(bothHeld(held))) expect(named).toContain(included.file);
45
+ expect(indexedCompiledFiles([...offIndex, ...inclusions], held)).toEqual(named);
46
+ expect(indexedCompiledFiles([...inclusions, ...offIndex], held)).toEqual(named);
47
+ }),
48
+ );
49
+ });
50
+ });