@waffle-os/runtime 0.0.145 → 0.0.146

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 (133) hide show
  1. package/README.md +32 -0
  2. package/browser/command-input.ts +86 -0
  3. package/browser/command-owner.ts +5 -0
  4. package/browser/display/guest.ts +2 -18
  5. package/browser/display/surface-info.ts +19 -0
  6. package/browser/operations/cells.ts +90 -0
  7. package/browser/operations/guest.ts +94 -0
  8. package/browser/operations/owner.ts +201 -0
  9. package/browser/operations/protocol.ts +16 -0
  10. package/browser/operations/types.ts +41 -0
  11. package/browser/operations/writer.ts +106 -0
  12. package/browser/preview1-worker.ts +8 -1
  13. package/browser/process-broker.ts +372 -22
  14. package/browser/process-start.ts +5 -2
  15. package/browser/run-command.ts +388 -0
  16. package/browser/shared-fs.ts +20 -3
  17. package/browser/worker-memory.ts +6 -0
  18. package/browser/worker.ts +121 -27
  19. package/dist/browser/command-input.js +82 -0
  20. package/dist/browser/command-owner.js +2 -0
  21. package/dist/browser/display/guest.js +2 -18
  22. package/dist/browser/display/surface-info.js +18 -0
  23. package/dist/browser/operations/cells.js +80 -0
  24. package/dist/browser/operations/guest.js +67 -0
  25. package/dist/browser/operations/owner.js +175 -0
  26. package/dist/browser/operations/protocol.js +0 -0
  27. package/dist/browser/operations/types.js +0 -0
  28. package/dist/browser/operations/writer.js +98 -0
  29. package/dist/browser/preview1-worker.js +4 -0
  30. package/dist/browser/process-broker.js +317 -18
  31. package/dist/browser/process-start.js +3 -0
  32. package/dist/browser/run-command.js +377 -0
  33. package/dist/browser/shared-fs.js +8 -3
  34. package/dist/browser/worker-memory.js +10 -1
  35. package/dist/browser/worker.js +83 -28
  36. package/dist/fs/client.js +81 -18
  37. package/dist/fs/resolve-observation.js +11 -0
  38. package/dist/fs/service.js +51 -4
  39. package/dist/proc/command-transfer.js +72 -0
  40. package/dist/proc/directory.js +9 -1
  41. package/dist/proc/intrinsics/host.js +4 -1
  42. package/dist/proc/intrinsics.js +1 -0
  43. package/dist/proc/pipes.js +37 -4
  44. package/dist/proc/registry.js +25 -14
  45. package/dist/proc/start-command.js +101 -0
  46. package/dist/proc/supervisor.js +34 -10
  47. package/dist/proc/worker-broker.js +86 -31
  48. package/dist/proc/worker-client.js +67 -31
  49. package/dist/programs/collection.js +2 -0
  50. package/dist/runtime.js +14 -1
  51. package/dist/tooling/program/program-transformer.json +1 -1
  52. package/fs/client.ts +113 -17
  53. package/fs/resolve-observation.ts +25 -0
  54. package/fs/service.ts +63 -4
  55. package/index.ts +5 -0
  56. package/package.json +9 -1
  57. package/proc/command-transfer.ts +96 -0
  58. package/proc/directory.ts +10 -1
  59. package/proc/intrinsics/host.ts +5 -1
  60. package/proc/intrinsics.ts +1 -0
  61. package/proc/pipes.ts +39 -6
  62. package/proc/registry.ts +52 -17
  63. package/proc/start-command.ts +157 -0
  64. package/proc/supervisor.ts +34 -9
  65. package/proc/worker-broker.ts +100 -38
  66. package/proc/worker-client.ts +84 -31
  67. package/programs/collection.ts +4 -0
  68. package/runtime.ts +44 -3
  69. package/scripts/test-browser.ts +49 -29
  70. package/tests/browser-controls-discovery.test.ts +2 -10
  71. package/tests/browser-matrix.test.ts +105 -59
  72. package/tests/browser-navigation.test.ts +1 -1
  73. package/tests/browser-runner-lifecycle.ts +23 -13
  74. package/tests/command-input.test.ts +40 -0
  75. package/tests/command-scope.test.ts +422 -0
  76. package/tests/filesystem-client-intrinsics.test.ts +2 -0
  77. package/tests/filesystem-refcount.test.ts +2 -0
  78. package/tests/filesystem-resolve-observation.test.ts +185 -0
  79. package/tests/fixtures/command-bounded-admission.ts +31 -0
  80. package/tests/fixtures/command-disposal.ts +47 -0
  81. package/tests/fixtures/command-guests.ts +123 -0
  82. package/tests/fixtures/operation-fs-worker.ts +114 -0
  83. package/tests/fixtures/operation-observer-worker.ts +41 -0
  84. package/tests/fixtures/operation-page.ts +522 -0
  85. package/tests/fixtures/process-start-worker.ts +32 -0
  86. package/tests/link-browser-runner.ts +95 -22
  87. package/tests/node-exports.test.ts +29 -0
  88. package/tests/operation-diagnostics-browser.ts +192 -0
  89. package/tests/operation-diagnostics.test.ts +291 -0
  90. package/tests/page-runner/browser-controls-process-fixture.ts +24 -0
  91. package/tests/page-runner/browser-controls-runner.test.ts +20 -0
  92. package/tests/page-runner/browser-controls-runner.ts +1 -0
  93. package/tests/page-runner/browser-controls-suite.ts +20 -3
  94. package/tests/page-runner/control-run.ts +9 -1
  95. package/tests/page-runner/driver.ts +2 -0
  96. package/tests/page-runner/playwright-driver.ts +1 -1
  97. package/tests/page-runner/suite-host.ts +26 -1
  98. package/tests/page-runner/suite-startup.test.ts +39 -0
  99. package/tests/page-runner/threads-runtime-browser.test.ts +4 -6
  100. package/tests/page-runner/threads-runtime-suite.test.ts +14 -5
  101. package/tests/page-runner/worker-capability-controls.ts +174 -15
  102. package/tests/pipe-reader-reuse-races.test.ts +44 -0
  103. package/tests/process-start-browser-runner.ts +12 -4
  104. package/tests/process-start-browser.ts +66 -5
  105. package/tests/program-build-tools.test.ts +1 -1
  106. package/tests/runtime-facade.test.ts +5 -0
  107. package/tests/start-command.test.ts +109 -0
  108. package/tests/threads-guest-fixture.ts +1 -1
  109. package/tests/threads-guest-module.ts +6 -3
  110. package/tests/threads-guest.test.ts +25 -0
  111. package/tests/threads-runtime-browser-runner.ts +36 -13
  112. package/tests/threads-runtime-browser.ts +231 -92
  113. package/tests/threads-runtime-cases.ts +18 -1
  114. package/tests/threads-runtime-cleanup.ts +5 -1
  115. package/tests/threads-runtime-fd-browser.ts +247 -0
  116. package/tests/threads-runtime-fd-control.ts +3 -385
  117. package/tests/threads-runtime-fd-descriptors.test.ts +15 -13
  118. package/tests/threads-runtime-fd-module.ts +13 -2
  119. package/tests/threads-runtime-fd-service.ts +23 -2
  120. package/tests/threads-runtime-growth-worker.ts +61 -0
  121. package/tests/threads-runtime-host.ts +17 -4
  122. package/tests/threads-runtime-modules.ts +23 -5
  123. package/tests/threads-runtime-regression-controls.ts +386 -0
  124. package/tests/threads-runtime-regression-modules.ts +242 -0
  125. package/tests/threads-runtime-service-barrier.ts +8 -1
  126. package/tests/webkit-diagnostics.ts +125 -0
  127. package/tests/webkit-error-output.test.ts +118 -0
  128. package/tests/worker-memory-bootstrap.test.ts +19 -1
  129. package/tests/worker-memory-broker.test.ts +16 -8
  130. package/tooling/ci-paths.test.ts +329 -61
  131. package/tooling/private-authority.ts +14 -0
  132. package/tooling/program/program-transformer.json +1 -1
  133. package/tooling/tarball-smoke.ts +3 -1
@@ -182,3 +182,47 @@ test("a relay-mode read holds its incarnation through consumption and demand", (
182
182
  expect(next.tryRead([output])).toBe(1);
183
183
  expect(output[0]).toBe(9);
184
184
  });
185
+
186
+ for (const rollback of [false, true]) {
187
+ test(`writer hangup waits for a reclaiming reader to ${rollback ? "roll back" : "publish"}`, async () => {
188
+ const { pipe, reader, writer } = singleReader();
189
+ const { owner, epoch } = words(reader.handle());
190
+ reader.close();
191
+ const cas = A.compareExchange;
192
+ let hangup: Promise<void> | undefined;
193
+ let observed = 0;
194
+ let settled = false;
195
+ A.compareExchange = ((view: Int32Array, index: number, old: number, next: number) => {
196
+ if (rollback && sameWord(view, epoch) && hangup) return old + 1;
197
+ const previous = cas(view, index, old, next);
198
+ if (sameWord(view, owner) && next === -0x80000000 && previous === old) {
199
+ expect(writer.tryWrite([new Uint8Array([7])])).toBe(-PipeErrno.AGAIN);
200
+ expect(writer.readiness().hangup).toBe(false);
201
+ observed = Atomics.load(writer.notification, 0);
202
+ hangup = writer.waitReaderHangup().then(() => {
203
+ settled = true;
204
+ });
205
+ }
206
+ return previous;
207
+ }) as typeof A.compareExchange;
208
+ let inherited;
209
+ try {
210
+ if (rollback) expect(() => pipe.retain(4, "read")).toThrow("limit reached");
211
+ else inherited = pipe.retain(4, "read");
212
+ } finally {
213
+ A.compareExchange = cas;
214
+ }
215
+ expect(hangup).toBeDefined();
216
+ expect(Atomics.load(writer.notification, 0)).not.toBe(observed);
217
+ await Promise.resolve();
218
+ expect(settled).toBe(false);
219
+ if (inherited) {
220
+ expect(writer.tryWrite([new Uint8Array([7])])).toBe(1);
221
+ await Bun.sleep(0);
222
+ expect(settled).toBe(false);
223
+ inherited.close();
224
+ }
225
+ await hangup;
226
+ expect(writer.tryWrite([new Uint8Array([7])])).toBe(-PipeErrno.PIPE);
227
+ });
228
+ }
@@ -34,9 +34,17 @@ function failures(report: ProcessStartReport): string[] {
34
34
  else if (times.some((time, index) => index > 0 && time! < times[index - 1]!))
35
35
  found.push(`normal start steps out of order: ${JSON.stringify(normal?.at)}`);
36
36
  const posted = normal?.at["start-posted"] ?? Infinity;
37
- for (const step of ["runtime-loaded", "group-joined", "modules-loaded"] as const)
38
- if ((normal?.at[step] ?? posted) < posted)
39
- found.push(`worker step ${step} before start-posted: ${JSON.stringify(normal?.at)}`);
37
+ for (const [index, snapshot] of report.stages.entries()) {
38
+ const time = snapshot.at[snapshot.step] ?? -Infinity;
39
+ const previous = report.stages[index - 1];
40
+ if (
41
+ time < (previous?.at[previous.step] ?? posted) ||
42
+ time > (normal?.at["memory-bound"] ?? -Infinity)
43
+ )
44
+ found.push(`worker step ${snapshot.step} out of order: ${JSON.stringify(snapshot.at)}`);
45
+ if (snapshot.at["memory-bound"] !== undefined)
46
+ found.push(`memory came before ${snapshot.step}: ${JSON.stringify(snapshot.at)}`);
47
+ }
40
48
  if (report.held?.step !== "start-posted") found.push(`held start reached ${report.held?.step}`);
41
49
  if (report.heldLater?.step !== "start-posted")
42
50
  found.push(`held start later reached ${report.heldLater?.step}`);
@@ -52,7 +60,7 @@ await runIsolatedPages({
52
60
  port: 0,
53
61
  sources: {
54
62
  "/tests.js": "process-start-browser.ts",
55
- "/worker.js": "fixtures/stop-order-worker.ts",
63
+ "/worker.js": "fixtures/process-start-worker.ts",
56
64
  "/fs-worker.js": "../browser/fs-worker.ts",
57
65
  },
58
66
  route(path, headers) {
@@ -1,10 +1,15 @@
1
1
  import { createRuntime, type ProcessStartState } from "../runtime.js";
2
+ import { createRuntimeTerminalCodec } from "../browser/runtime-terminals.js";
3
+ import { WorkerProcessClient, workerProcessPipeRegistry } from "../proc/worker-client.js";
4
+ import { WorkerPipeHost } from "../proc/worker-pipes.js";
5
+ import type { ProcessStartWorkerRequest } from "./fixtures/process-start-worker.js";
2
6
  import { pageRootClient } from "./fixtures/page-root-client.js";
3
7
  import { stopOrderModule } from "./fixtures/stop-order-wasm.js";
4
8
 
5
9
  // docs/process-observation.md, "Start states", through the real runtime, broker and Worker.
6
10
 
7
11
  export interface ProcessStartReport {
12
+ readonly stages: readonly ProcessStartState[];
8
13
  /** A normal start, read once the guest's heartbeat moved. */
9
14
  readonly normal: ProcessStartState | undefined;
10
15
  /** A start whose worker script request never answered, read after it was posted. */
@@ -33,15 +38,26 @@ async function until<T>(read: () => T | undefined, label: string): Promise<T> {
33
38
  export async function processStarts(): Promise<ProcessStartReport> {
34
39
  const runtime = createRuntime({ filesystem: { workerURL: "/fs-worker.js", mode: "memory" } });
35
40
  const memories = new Map<number, WebAssembly.Memory>();
41
+ const stages = ["installing-bindings", "bindings-installed", "instantiating"] as const;
42
+ const gates = new Int32Array(new SharedArrayBuffer(stages.length * Int32Array.BYTES_PER_ELEMENT));
43
+ const release = (index: number) => {
44
+ Atomics.store(gates, index, 1);
45
+ Atomics.notify(gates, index);
46
+ };
36
47
  for (const [adapter, workerUrl] of [
37
48
  ["normal", "/worker.js"],
38
49
  ["held", "/held-worker.js"],
39
50
  ["missing", "/missing-worker.js"],
40
51
  ])
41
52
  runtime.registerAdapter(adapter!, (context, service) =>
42
- service.launchWorker(context, {
53
+ service.launchWorker<ProcessStartWorkerRequest>(context, {
43
54
  workerUrl: workerUrl!,
44
- request: { module: context.module, args: context.request.argv, env: {} },
55
+ request: {
56
+ module: context.module,
57
+ args: context.request.argv,
58
+ env: {},
59
+ gates: gates.buffer,
60
+ },
45
61
  onMessage(message) {
46
62
  const data = message as { type?: string; memory?: WebAssembly.Memory };
47
63
  if (data.type === "stop-order-memory" && data.memory)
@@ -53,16 +69,49 @@ export async function processStarts(): Promise<ProcessStartReport> {
53
69
  const module = await WebAssembly.compile(source);
54
70
  for (const adapter of ["normal", "held", "missing"])
55
71
  runtime.registerProgram(`/${adapter}`, { adapter, module, cooperative: true });
56
- const { root, client, descriptors, notices } = pageRootClient(runtime);
72
+ const { root, client: initialClient, descriptors, notices } = pageRootClient(runtime);
57
73
  const service = await runtime.processes();
58
74
  const flush = async () => {
59
75
  while (notices.length) await service.runtimeMessage(notices.shift()!, root.pid);
60
76
  };
61
77
  const state = (pid: number) => service.startStates().find((entry) => entry.pid === pid);
78
+ const waitForStage = (pid: number, step: (typeof stages)[number]) =>
79
+ until(() => {
80
+ const current = state(pid);
81
+ return current?.step === step ? current : undefined;
82
+ }, step);
62
83
  try {
63
84
  for (const adapter of ["normal", "held", "missing"])
64
85
  await runtime.filesystem.writeFile(`/${adapter}`, source);
65
86
  await service.adoptRuntimeRoot(root, { memory: [] });
87
+ const pipes = new WorkerPipeHost({
88
+ transport: root,
89
+ postMessage: initialClient.options.postMessage,
90
+ registry: workerProcessPipeRegistry(root),
91
+ });
92
+ const [reader, writer] = pipes.createPipe();
93
+ descriptors.openAt(0, reader, 2n, 0n, () => reader.close());
94
+ descriptors.openAt(1, writer, 64n, 0n, () => writer.close());
95
+ descriptors.openAt(
96
+ 2,
97
+ {
98
+ kind: "terminal",
99
+ read: () => 0,
100
+ write: () => 0,
101
+ readiness: () => ({ readable: false, writable: true, hangup: false }),
102
+ },
103
+ 64n,
104
+ 0n,
105
+ );
106
+ const client = new WorkerProcessClient({
107
+ ...initialClient.options,
108
+ codec: createRuntimeTerminalCodec({ descriptors, fallback: pipes.codec() }),
109
+ prepareSpawn: (pid) => {
110
+ const filesystem = runtime.filesystem.createIdentity();
111
+ pipes.registry.registerProcess(pid);
112
+ return { data: { filesystem }, cancel: () => pipes.registry.collectProcess(pid) };
113
+ },
114
+ });
66
115
  const supervisor = await service.ready();
67
116
  const spawn = async (executable: string) => {
68
117
  const pid = client.spawn(root.pid, {
@@ -71,7 +120,13 @@ export async function processStarts(): Promise<ProcessStartReport> {
71
120
  env: {},
72
121
  cwd: "/",
73
122
  job: -1,
74
- fds: [],
123
+ fds:
124
+ executable === "/normal"
125
+ ? [
126
+ { child: 1, parent: 1 },
127
+ { child: 2, parent: 2 },
128
+ ]
129
+ : [],
75
130
  });
76
131
  await flush();
77
132
  await supervisor.start(pid);
@@ -85,6 +140,11 @@ export async function processStarts(): Promise<ProcessStartReport> {
85
140
  };
86
141
 
87
142
  const normalPid = await spawn("/normal");
143
+ const observed: ProcessStartState[] = [];
144
+ for (const [index, step] of stages.entries()) {
145
+ observed.push(await waitForStage(normalPid, step));
146
+ release(index);
147
+ }
88
148
  await until(() => {
89
149
  const memory = memories.get(normalPid);
90
150
  return memory && Atomics.load(new Int32Array(memory.buffer), 0) > 2 ? true : undefined;
@@ -112,8 +172,9 @@ export async function processStarts(): Promise<ProcessStartReport> {
112
172
  () => (service.startStates().length === 0 ? true : undefined),
113
173
  "start states to empty",
114
174
  );
115
- return { normal, held, heldLater, heldKilled, missing };
175
+ return { stages: observed, normal, held, heldLater, heldKilled, missing };
116
176
  } finally {
177
+ for (const index of stages.keys()) release(index);
117
178
  descriptors.dispose();
118
179
  await runtime.dispose();
119
180
  }
@@ -222,7 +222,7 @@ test("packed build tools work without the repository in Node, Bun and a typed co
222
222
  } finally {
223
223
  rmSync(scratch, { recursive: true, force: true });
224
224
  }
225
- });
225
+ }, 30_000);
226
226
 
227
227
  test.each(["consumer", "waffle-monorepo"])(
228
228
  "workspace-shaped consumers preserve packaged tools (%s)",
@@ -1436,6 +1436,11 @@ test("facade initial browser graph keeps process services and interrupt compilat
1436
1436
  !/(?:^|\/)(identity|stub|outcome|signals|control|types|intrinsics)\.ts$/.test(path),
1437
1437
  );
1438
1438
  expect(processInputs).toEqual([]);
1439
+ expect(
1440
+ inputs.filter((path) =>
1441
+ /browser\/(?:run-command|command-input|process-broker)\.ts$/.test(path),
1442
+ ),
1443
+ ).toEqual([]);
1439
1444
  expect(inputs.filter((path) => /(?:^|\/)(?:network|native)\//.test(path))).toEqual([]);
1440
1445
  expect(
1441
1446
  inputs.filter((path) => /browser\/net\/(?:module|namespace|runtime)\.ts$/.test(path)),
@@ -0,0 +1,109 @@
1
+ import { expect, test } from "bun:test";
2
+ import {
3
+ BrowserProcessBroker,
4
+ type BrowserProcessBrokerOptions,
5
+ } from "../browser/process-broker.js";
6
+ import { startCommand } from "../proc/start-command.js";
7
+ import { createRuntime, type Runtime } from "../runtime.js";
8
+
9
+ const moduleBytes = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0]);
10
+ const fsWorker = new URL("../browser/fs-worker.ts", import.meta.url);
11
+ const options = { filesystem: "runtime-root" } as const;
12
+
13
+ async function install(runtime: Runtime, launch: Parameters<Runtime["registerAdapter"]>[1]) {
14
+ runtime.registerAdapter("control", launch);
15
+ runtime.registerProgram("/fixture", { adapter: "control", source: moduleBytes });
16
+ await runtime.filesystem.writeFile("/fixture", "");
17
+ }
18
+
19
+ test("kill drops an awaiting activation before it reserves any process", async () => {
20
+ const deferred = Promise.withResolvers<void>();
21
+ const entered = Promise.withResolvers<BrowserProcessBrokerOptions>();
22
+ const runtime = createRuntime({
23
+ filesystem: { mode: "memory", workerURL: fsWorker },
24
+ async processHost(options) {
25
+ entered.resolve(options);
26
+ await deferred.promise;
27
+ return new BrowserProcessBroker(options);
28
+ },
29
+ });
30
+ try {
31
+ const command = startCommand(runtime, "/fixture", options);
32
+ const { table } = await entered.promise;
33
+ expect(command.kill()).toBe(command.result);
34
+ expect(await command.result).toMatchObject({ exit: null, stopRequested: "kill" });
35
+ expect(Array.from(table.values())).toEqual([]);
36
+ await command.signal(2);
37
+ deferred.resolve();
38
+ await runtime.processes();
39
+ expect(Array.from(table.values())).toEqual([]);
40
+ } finally {
41
+ deferred.resolve();
42
+ await runtime.dispose();
43
+ }
44
+ });
45
+
46
+ test("kill joins a late adapter handle and its physical stop", async () => {
47
+ const entered = Promise.withResolvers<void>();
48
+ const releaseLaunch = Promise.withResolvers<void>();
49
+ const stopEntered = Promise.withResolvers<void>();
50
+ const releaseStop = Promise.withResolvers<void>();
51
+ const runtime = createRuntime({ filesystem: { mode: "memory", workerURL: fsWorker } });
52
+ try {
53
+ await install(runtime, async (context) => {
54
+ context.started();
55
+ entered.resolve();
56
+ await releaseLaunch.promise;
57
+ return {
58
+ async terminate() {
59
+ stopEntered.resolve();
60
+ await releaseStop.promise;
61
+ },
62
+ };
63
+ });
64
+ const command = startCommand(runtime, "/fixture", options);
65
+ let done = false;
66
+ void command.result.then(
67
+ () => {
68
+ done = true;
69
+ },
70
+ () => {
71
+ done = true;
72
+ },
73
+ );
74
+ await entered.promise;
75
+ const end = command.kill();
76
+ expect(end).toBe(command.result);
77
+ await Bun.sleep(0);
78
+ expect(done).toBe(false);
79
+ releaseLaunch.resolve();
80
+ await stopEntered.promise;
81
+ expect(done).toBe(false);
82
+ releaseStop.resolve();
83
+ expect(await end).toMatchObject({
84
+ exit: { kind: "signaled", code: 9, status: 137 },
85
+ stopRequested: "kill",
86
+ });
87
+ const service = await runtime.processes();
88
+ expect(Array.from((await service.ready()).table.values())).toEqual([]);
89
+ } finally {
90
+ releaseLaunch.resolve();
91
+ releaseStop.resolve();
92
+ await runtime.dispose();
93
+ }
94
+ });
95
+
96
+ test("a real generic command Worker can start within the bounded runtime and exit 130", () => {
97
+ // A fresh page ledger keeps backing retained by another test outside this budget.
98
+ const entry = new URL("./fixtures/command-bounded-admission.ts", import.meta.url).pathname;
99
+ const attempt = Bun.spawnSync([process.execPath, entry], { timeout: 30_000 });
100
+ expect(attempt.exitCode, attempt.stderr.toString()).toBe(0);
101
+ expect(attempt.stderr.toString()).toBe("");
102
+ }, 35_000);
103
+
104
+ test("runtime disposal failure rejects the command before broker disposal and cancels stdin", () => {
105
+ const entry = new URL("./fixtures/command-disposal.ts", import.meta.url).pathname;
106
+ const attempt = Bun.spawnSync([process.execPath, entry], { timeout: 5000 });
107
+ expect(attempt.stderr.toString()).toBe("");
108
+ expect(attempt.exitCode).toBe(0);
109
+ });
@@ -67,7 +67,7 @@ export async function guestFixture(
67
67
  return result;
68
68
  }
69
69
  const tid = await spawn(request.startArg);
70
- return tid > 0 ? { kind: "ok", value: tid } : { kind: "error", errno: -tid };
70
+ return tid >= 0 ? { kind: "ok", value: tid } : { kind: "error", errno: -tid };
71
71
  },
72
72
  };
73
73
  function launch(
@@ -28,10 +28,13 @@ export const i64 = (value: bigint) => [0x42].concat(signed(value));
28
28
  export const call = (index: number) => [0x10].concat(unsigned(index));
29
29
  export const store = (address: number, value: number[]) => i32(address).concat(value, [0x36, 2, 0]);
30
30
  export const notify = (address: number) => i32(address).concat(i32(8), [0xfe, 0, 2, 0, 0x1a]);
31
+ export const wait32Result = (address: number, timeout: bigint, expected = 0) =>
32
+ i32(address).concat(i32(expected), i64(timeout), [0xfe, 1, 2, 0]);
33
+ export const wait64Result = (address: number, timeout: bigint) =>
34
+ i32(address).concat(i64(0n), i64(timeout), [0xfe, 2, 3, 0]);
31
35
  export const wait32 = (address: number, expected = 0) =>
32
- i32(address).concat(i32(expected), i64(-1n), [0xfe, 1, 2, 0, 0x1a]);
33
- export const wait64 = (address: number) =>
34
- i32(address).concat(i64(0n), i64(-1n), [0xfe, 2, 3, 0, 0x1a]);
36
+ wait32Result(address, -1n, expected).concat([0x1a]);
37
+ export const wait64 = (address: number) => wait64Result(address, -1n).concat([0x1a]);
35
38
  export interface GuestFunctionImport {
36
39
  module?: string;
37
40
  name: string;
@@ -240,6 +240,31 @@ describe("thread guest bridge", () => {
240
240
  await fixture.dispose();
241
241
  }
242
242
  });
243
+
244
+ for (const invalid of [0, 0x20000000]) {
245
+ test(`compiled guest rejects out-of-range successful spawn value ${invalid}`, async () => {
246
+ const fixture = await guestFixture();
247
+ try {
248
+ fixture.setSpawn(async () => invalid);
249
+ const module = await compileThreadGuest(
250
+ guestModule({
251
+ imports: [{ module: "wasi", name: "thread-spawn", params: [0x7f] }],
252
+ initial: store(64, i32(88).concat(call(0))),
253
+ }),
254
+ );
255
+ new Int32Array(fixture.memory.buffer)[16] = 123;
256
+ const guest = fixture.launch(module, { kind: "initial" });
257
+ await guest.ready;
258
+ guest.enter();
259
+ await guest.idle;
260
+ expect(readOutcome(fixture.outcome)).toMatchObject({ kind: "exited", code: 1 });
261
+ expect(new Int32Array(fixture.memory.buffer)[16]).toBe(123);
262
+ expect(fixture.guests).toHaveLength(1);
263
+ } finally {
264
+ await fixture.dispose();
265
+ }
266
+ });
267
+ }
243
268
  });
244
269
 
245
270
  test("ordinary precompiled modules cannot bypass supervised wait admission", async () => {
@@ -7,14 +7,27 @@ import {
7
7
  } from "./threads-runtime-safari-packet.js";
8
8
  import {
9
9
  isRuntimeThreadCase,
10
+ isRuntimeThreadRegression,
10
11
  runtimeThreadCases,
11
- type RuntimeThreadCase,
12
+ runtimeThreadRegressions,
13
+ type BrowserRuntimeThreadCase,
12
14
  } from "./threads-runtime-cases.js";
13
15
 
14
16
  type RuntimeThreadCommand =
15
17
  | { kind: "native"; args: string[] }
16
18
  | { kind: "prepare"; directory: string }
17
- | { kind: "browser"; engines: string[]; cases: readonly RuntimeThreadCase[] };
19
+ | { kind: "browser"; engines: string[]; cases: readonly BrowserRuntimeThreadCase[] };
20
+
21
+ const browserCases: readonly BrowserRuntimeThreadCase[] =
22
+ Array.from<BrowserRuntimeThreadCase>(runtimeThreadCases).concat(runtimeThreadRegressions);
23
+
24
+ const browserRuntimeSources = {
25
+ ...runtimeSafariSources,
26
+ "/thread-fd-filesystem.js": new URL("./threads-runtime-fd-filesystem.ts", import.meta.url)
27
+ .pathname,
28
+ "/thread-fd-service.js": new URL("./threads-runtime-fd-service.ts", import.meta.url).pathname,
29
+ "/thread-growth.js": new URL("./threads-runtime-growth-worker.ts", import.meta.url).pathname,
30
+ };
18
31
 
19
32
  export function parseRuntimeThreadCommand(args: readonly string[]): RuntimeThreadCommand {
20
33
  if (args[0] === "ios-safari") return { kind: "native", args: args.slice(1) };
@@ -22,24 +35,34 @@ export function parseRuntimeThreadCommand(args: readonly string[]): RuntimeThrea
22
35
  if (args.length !== 2 || !args[1]) throw new Error("expected --prepare OUTPUT_DIRECTORY");
23
36
  return { kind: "prepare", directory: args[1] };
24
37
  }
25
- const names = args.slice();
26
- const caseIndex = names.indexOf("--case");
27
- let cases: readonly RuntimeThreadCase[] = runtimeThreadCases;
28
- if (caseIndex >= 0) {
29
- const selected = names.splice(caseIndex, 2)[1];
30
- if (!isRuntimeThreadCase(selected)) throw new Error("unknown Runtime case");
31
- cases = [selected];
38
+ const engines: string[] = [];
39
+ const focused: BrowserRuntimeThreadCase[] = [];
40
+ for (let index = 0; index < args.length; index++) {
41
+ const arg = args[index]!;
42
+ if (arg !== "--case") {
43
+ engines.push(arg);
44
+ continue;
45
+ }
46
+ const selected = args[++index];
47
+ if (!isRuntimeThreadCase(selected) && !isRuntimeThreadRegression(selected))
48
+ throw new Error("unknown Runtime case");
49
+ if (focused.includes(selected)) throw new Error(`duplicate Runtime case ${selected}`);
50
+ focused.push(selected);
32
51
  }
33
- if (names.some((name) => !["chromium", "firefox", "webkit"].includes(name)))
52
+ if (engines.some((name) => !["chromium", "firefox", "webkit"].includes(name)))
34
53
  throw new Error("expected chromium, firefox or webkit, with optional --case NAME");
35
- return { kind: "browser", engines: names.length ? names : ["chromium"], cases };
54
+ return {
55
+ kind: "browser",
56
+ engines: engines.length ? engines : ["chromium"],
57
+ cases: focused.length ? focused : browserCases,
58
+ };
36
59
  }
37
60
 
38
61
  async function evaluateRuntimeCase({
39
62
  selected,
40
63
  fixtureSha256,
41
64
  }: {
42
- selected: RuntimeThreadCase;
65
+ selected: BrowserRuntimeThreadCase;
43
66
  fixtureSha256: string;
44
67
  }) {
45
68
  const module = (await import(
@@ -70,7 +93,7 @@ async function main(): Promise<void> {
70
93
  scratchPrefix: "run-",
71
94
  port: Number(process.env.THREAD_RUNTIME_PORT ?? 19447),
72
95
  names: command.engines,
73
- sources: runtimeSafariSources,
96
+ sources: browserRuntimeSources,
74
97
  route: (path, headers) =>
75
98
  path === "/threads.wasm"
76
99
  ? new Response(fixture.wasm, {