@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
@@ -0,0 +1,242 @@
1
+ import {
2
+ call,
3
+ guestModule,
4
+ i32,
5
+ notify,
6
+ store,
7
+ wait32,
8
+ wait32Result,
9
+ wait64Result,
10
+ } from "./threads-guest-module.js";
11
+
12
+ export const spawnImport = { module: "wasi", name: "thread-spawn", params: [0x7f] };
13
+ const readImport = { name: "fd_read", params: [0x7f, 0x7f, 0x7f, 0x7f] };
14
+ const writeImport = { ...readImport, name: "fd_write" };
15
+ const exitImport = { name: "proc_exit", params: [0x7f], result: false };
16
+ const drop = [0x1a];
17
+ const local = (index: number) => [0x20, index];
18
+ const load = (address: number) => i32(address).concat([0x28, 2, 0]);
19
+ const loadFlag = (address: number) => i32(address).concat([0xfe, 0x10, 2, 0]);
20
+ function signal(address: number) {
21
+ return i32(address).concat(i32(1), [0xfe, 0x17, 2, 0], notify(address));
22
+ }
23
+ function when(condition: number[], body: number[]) {
24
+ return condition.concat([0x04, 0x40], body, [0x0b]);
25
+ }
26
+ function role(argument: number, body: number[]) {
27
+ return when(local(1).concat(i32(argument), [0x46]), body.concat([0x0f]));
28
+ }
29
+ function requireEqual(value: number[], expected: number) {
30
+ return when(value.concat(i32(expected), [0x47]), [0x00]);
31
+ }
32
+ function spawn(argument: number) {
33
+ return i32(argument).concat(call(0));
34
+ }
35
+ function setupIo(iov: number, data: number, length: number) {
36
+ return store(iov, i32(data)).concat(store(iov + 4, i32(length)));
37
+ }
38
+ function io(index: number, fd: number, iov: number, count: number) {
39
+ return i32(fd).concat(i32(iov), i32(1), i32(count), call(index));
40
+ }
41
+ const waitHangCapNs = 60_000_000_000n;
42
+
43
+ export const fatalLayout = {
44
+ main: 0,
45
+ timer: 8,
46
+ exit: 16,
47
+ sentinels: 32,
48
+ iov: 64,
49
+ bytes: 72,
50
+ count: 76,
51
+ } as const;
52
+ export const fatalReadSentinels = { payload: 0x11223344, count: 0x55667788 } as const;
53
+
54
+ export function fatalThreadModule() {
55
+ const p = fatalLayout;
56
+ return guestModule({
57
+ imports: [spawnImport, readImport, exitImport],
58
+ initial: requireEqual(spawn(1), 2).concat(
59
+ requireEqual(spawn(2), 3),
60
+ requireEqual(spawn(3), 4),
61
+ wait32(p.main),
62
+ store(p.sentinels, i32(1)),
63
+ ),
64
+ secondary: role(
65
+ 1,
66
+ setupIo(p.iov, p.bytes, 1).concat(
67
+ store(p.bytes, i32(fatalReadSentinels.payload)),
68
+ store(p.count, i32(fatalReadSentinels.count)),
69
+ io(1, 0, p.iov, p.count),
70
+ drop,
71
+ store(p.sentinels + 4, i32(1)),
72
+ ),
73
+ ).concat(
74
+ role(2, wait64Result(p.timer, waitHangCapNs).concat(drop, store(p.sentinels + 8, i32(1)))),
75
+ wait32(p.exit),
76
+ i32(23),
77
+ call(2),
78
+ store(p.sentinels + 12, i32(1)),
79
+ ),
80
+ });
81
+ }
82
+
83
+ export const overlapLayout = {
84
+ canaryGate: 0,
85
+ finish: 4,
86
+ waits: [8, 16],
87
+ launchSecond: 24,
88
+ results: [64, 72],
89
+ canaryCount: 88,
90
+ } as const;
91
+
92
+ export function overlappingWaitModule() {
93
+ const p = overlapLayout;
94
+ return guestModule({
95
+ imports: [spawnImport, writeImport],
96
+ initial: requireEqual(spawn(1), 2).concat(
97
+ wait32(p.launchSecond),
98
+ requireEqual(spawn(2), 3),
99
+ wait32(p.canaryGate),
100
+ setupIo(96, 104, 1),
101
+ store(104, i32(87)),
102
+ requireEqual(io(1, 1, 96, p.canaryCount), 0),
103
+ wait32(p.finish),
104
+ ),
105
+ secondary: role(
106
+ 1,
107
+ store(p.results[0], wait32Result(p.waits[0], waitHangCapNs)).concat(
108
+ store(p.results[0] + 4, wait32Result(p.waits[0], 1_000_000n)),
109
+ ),
110
+ ).concat(
111
+ store(p.results[1], wait64Result(p.waits[1], waitHangCapNs)),
112
+ store(p.results[1] + 4, wait64Result(p.waits[1], 1_000_000n)),
113
+ ),
114
+ });
115
+ }
116
+
117
+ export const admissionLayout = {
118
+ holdStart: 0,
119
+ startGate: 4,
120
+ returnGate: 8,
121
+ finish: 12,
122
+ firstRefusal: 16,
123
+ secondRefusal: 20,
124
+ retry: 24,
125
+ admitted: 28,
126
+ pendingResult: 32,
127
+ runningResult: 36,
128
+ replacementResult: 40,
129
+ returned: 44,
130
+ replacementEntry: 48,
131
+ canary: 52,
132
+ canaryCount: 56,
133
+ } as const;
134
+
135
+ export function admissionThreadModule() {
136
+ const p = admissionLayout;
137
+ return guestModule({
138
+ imports: [spawnImport, writeImport],
139
+ start: when(loadFlag(p.holdStart), wait32(p.startGate)),
140
+ initial: requireEqual(spawn(1), 2).concat(
141
+ requireEqual(spawn(2), 3),
142
+ signal(p.holdStart),
143
+ store(p.admitted, spawn(3)),
144
+ wait32(p.finish),
145
+ ),
146
+ secondary: role(
147
+ 1,
148
+ wait32(p.firstRefusal).concat(
149
+ store(p.pendingResult, spawn(5)),
150
+ wait32(p.secondRefusal),
151
+ store(p.runningResult, spawn(5)),
152
+ wait32(p.retry),
153
+ store(p.replacementResult, spawn(4)),
154
+ wait32(p.finish),
155
+ ),
156
+ ).concat(
157
+ role(2, wait32(p.returnGate).concat(signal(p.returned))),
158
+ role(
159
+ 3,
160
+ wait32(p.canary).concat(
161
+ setupIo(96, 104, 1),
162
+ store(104, i32(65)),
163
+ requireEqual(io(1, 1, 96, p.canaryCount), 0),
164
+ wait32(p.finish),
165
+ ),
166
+ ),
167
+ role(4, store(p.replacementEntry, local(0)).concat(wait32(p.finish))),
168
+ [0x00],
169
+ ),
170
+ });
171
+ }
172
+
173
+ export const maxThreadId = 0x1fffffff;
174
+ export const tidLayout = {
175
+ gates: [0, 4, 8, 12],
176
+ results: [16, 20, 24, 28],
177
+ entries: [32, 36, 40, 44],
178
+ finish: 48,
179
+ } as const;
180
+
181
+ export function threadIdModule() {
182
+ const p = tidLayout;
183
+ return guestModule({
184
+ imports: [spawnImport],
185
+ initial: p.gates
186
+ .flatMap((gate, index) => wait32(gate).concat(store(p.results[index]!, spawn(index))))
187
+ .concat(wait32(p.finish)),
188
+ secondary: p.entries.flatMap((address, index) => role(index, store(address, local(0)))),
189
+ });
190
+ }
191
+
192
+ const page = 65536;
193
+ export const growthLayout = {
194
+ launch: 0,
195
+ holdStart: 4,
196
+ startWaiting: 8,
197
+ startGate: 12,
198
+ entryWaiting: 16,
199
+ entryGate: 20,
200
+ finished: 24,
201
+ first: 2 * page + 64,
202
+ second: 3 * page + 64,
203
+ } as const;
204
+ function grow(previous: number) {
205
+ return requireEqual(i32(1).concat([0x40, 0]), previous);
206
+ }
207
+ function growthIo(address: number, pages: number, byte: number) {
208
+ return requireEqual([0x3f, 0], pages).concat(
209
+ requireEqual(load(address), byte),
210
+ setupIo(address + 8, address, 1),
211
+ requireEqual(io(1, 1, address + 8, address + 16), 0),
212
+ requireEqual(load(address + 16), 1),
213
+ );
214
+ }
215
+ export function receivingGrowthModule() {
216
+ const p = growthLayout;
217
+ return guestModule({
218
+ imports: [spawnImport, writeImport],
219
+ start: when(
220
+ loadFlag(p.holdStart),
221
+ signal(p.startWaiting).concat(wait32(p.startGate), growthIo(p.first, 3, 65)),
222
+ ),
223
+ initial: requireEqual(spawn(1), 2).concat(
224
+ signal(p.holdStart),
225
+ signal(p.launch),
226
+ wait32(p.startWaiting),
227
+ grow(2),
228
+ store(p.first, i32(65)),
229
+ signal(p.startGate),
230
+ wait32(p.entryWaiting),
231
+ grow(3),
232
+ store(p.second, i32(66)),
233
+ signal(p.entryGate),
234
+ wait32(p.finished),
235
+ ),
236
+ secondary: role(1, wait32(p.launch).concat(requireEqual(spawn(2), 3))).concat(
237
+ signal(p.entryWaiting),
238
+ wait32(p.entryGate),
239
+ growthIo(p.second, 4, 66),
240
+ ),
241
+ });
242
+ }
@@ -45,5 +45,12 @@ self.onmessage = ({
45
45
  void command.then(() => event("drain-command-resolved"), failure).catch(failure);
46
46
  return;
47
47
  }
48
- void threadServiceCommand(data).catch(failure);
48
+ const pending = threadServiceCommand(data);
49
+ if (data.kind === "call" && data.request.kind === "read" && data.request.fd === 0) {
50
+ const { pid, tid } = data.call.thread;
51
+ event("fixture-stdin-pending", { pid, tid });
52
+ void pending.then(() => event("fixture-stdin-settled", { pid, tid }), failure);
53
+ return;
54
+ }
55
+ void pending.catch(failure);
49
56
  };
@@ -0,0 +1,125 @@
1
+ import type { Page } from "playwright";
2
+ import { format } from "node:util";
3
+
4
+ type DebugLog = (this: { namespace?: string } | undefined, ...args: unknown[]) => void;
5
+ type PlaywrightDebug = {
6
+ enable(namespaces: string): void;
7
+ namespaces: string;
8
+ log: DebugLog;
9
+ };
10
+ const browserPrefix = "pw:browser ";
11
+ const colorReset = "\x1b[0m";
12
+ const nativeOutput = /^\[pid=\d+\]\[(?:out|err)\] /;
13
+ const nativeOutputLimit = 64 * 1024;
14
+ const nativeOutputTruncated = `pw:browser native stdout/stderr truncated (limit ${nativeOutputLimit} bytes)`;
15
+ const callLogDim = "\x1b[2m";
16
+ const callLogPrefix = /^ *(?:(?:-|\d+ ×) )?/;
17
+
18
+ function isNativeOutput(line: string): boolean {
19
+ const index = line.indexOf(browserPrefix);
20
+ if (index === -1) return false;
21
+ const start = index + browserPrefix.length;
22
+ return nativeOutput.test(
23
+ line.slice(start + (line.startsWith(colorReset, start) ? colorReset.length : 0)),
24
+ );
25
+ }
26
+
27
+ function isReplayedNativeOutput(line: string): boolean {
28
+ const plain = line.startsWith(callLogDim) ? line.slice(callLogDim.length) : line;
29
+ return nativeOutput.test(plain.replace(callLogPrefix, ""));
30
+ }
31
+
32
+ export function boundWebKitLogReplay(message: string): string {
33
+ if (!message.includes("[pid=")) return message;
34
+ let bytes = 0;
35
+ let truncated = false;
36
+ const lines: string[] = [];
37
+ for (const line of message.split("\n")) {
38
+ if (!isReplayedNativeOutput(line)) {
39
+ lines.push(line);
40
+ continue;
41
+ }
42
+ if (truncated) continue;
43
+ bytes += Buffer.byteLength(line) + 1;
44
+ truncated = bytes > nativeOutputLimit;
45
+ lines.push(truncated ? nativeOutputTruncated : line);
46
+ }
47
+ return truncated ? lines.join("\n") : message;
48
+ }
49
+
50
+ export function boundWebKitError(error: unknown): void {
51
+ if (!(error instanceof Error) || !error.message.includes("[pid=")) return;
52
+ const original = error.message;
53
+ const message = boundWebKitLogReplay(original);
54
+ if (message !== original) {
55
+ const stack = error.stack;
56
+ error.message = message;
57
+ if (stack) error.stack = boundWebKitLogReplay(stack);
58
+ }
59
+ if (original.includes("\nCall log:\n") && "log" in error && Array.isArray(error.log)) {
60
+ // Playwright puts the call log in the message and on the Error object.
61
+ error.log = error.log.filter(
62
+ (line: unknown) => typeof line !== "string" || !isReplayedNativeOutput(line),
63
+ );
64
+ }
65
+ }
66
+
67
+ export function captureWebKitDiagnostics(): () => void {
68
+ // Playwright's bundled debug instance supplies the namespace as the log receiver.
69
+ const { debug }: { debug: PlaywrightDebug } = require("playwright-core/lib/utilsBundle");
70
+ const { namespaces, log } = debug;
71
+ debug.enable(namespaces ? `${namespaces},pw:browser` : "pw:browser");
72
+ let bytes = 0;
73
+ let truncated = false;
74
+ debug.log = function (...args) {
75
+ const first = args[0];
76
+ if (this?.namespace !== "pw:browser" || typeof first !== "string" || !isNativeOutput(first)) {
77
+ log.apply(this, args);
78
+ return;
79
+ }
80
+ if (truncated) return;
81
+ const line = `${format(...args)}\n`;
82
+ bytes += Buffer.byteLength(line);
83
+ if (bytes <= nativeOutputLimit) process.stderr.write(line);
84
+ else {
85
+ truncated = true;
86
+ process.stderr.write(`${nativeOutputTruncated}\n`);
87
+ }
88
+ };
89
+ return () => {
90
+ debug.log = log;
91
+ debug.enable(namespaces ?? "");
92
+ };
93
+ }
94
+
95
+ export function observeWebKitPage(page: Page, control: string) {
96
+ let phase = "opened";
97
+ let shuttingDown = false;
98
+ const report = (event: "close" | "crash" | "failure") => {
99
+ console.error(
100
+ JSON.stringify({
101
+ webkitPage: control,
102
+ event,
103
+ phase,
104
+ url: page.url().split("?")[0],
105
+ closed: page.isClosed(),
106
+ browserConnected: page.context().browser()?.isConnected() ?? null,
107
+ }),
108
+ );
109
+ };
110
+ page.once("close", () => report("close"));
111
+ page.once("crash", () => report("crash"));
112
+ return {
113
+ enter(next: string) {
114
+ if (shuttingDown) return;
115
+ phase = next;
116
+ },
117
+ shutdown(next: string) {
118
+ shuttingDown = true;
119
+ phase = next;
120
+ },
121
+ fail() {
122
+ report("failure");
123
+ },
124
+ };
125
+ }
@@ -0,0 +1,118 @@
1
+ import { expect, test } from "bun:test";
2
+ import { chmod, mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { basename, dirname, join } from "node:path";
5
+ import { webkit } from "playwright";
6
+
7
+ async function installFailingLauncher(root: string): Promise<void> {
8
+ const executable = webkit.executablePath();
9
+ const directory = join(root, basename(dirname(executable)));
10
+ const launcher = join(directory, basename(executable));
11
+ await mkdir(directory);
12
+ await writeFile(
13
+ launcher,
14
+ `#!/bin/sh
15
+ for line in 1 2 3 4 5 6 7 8 9 10; do
16
+ printf 'NATIVE_LINE_%s %016384d\\n' "$line" "$line" >&2
17
+ done
18
+ exit 42
19
+ `,
20
+ );
21
+ await chmod(launcher, 0o700);
22
+ }
23
+
24
+ for (const runner of ["link", "controls"] as const) {
25
+ test.skipIf(process.platform === "win32")(
26
+ `${runner} reports a real Playwright launch failure with bounded native output`,
27
+ async () => {
28
+ const root = await mkdtemp(join(process.env.STORAGE_SCRATCH_ROOT ?? tmpdir(), "wke-"));
29
+ const scratch = join(root, "tmp");
30
+ const result = join(root, "controls.json");
31
+ try {
32
+ await mkdir(scratch);
33
+ await installFailingLauncher(root);
34
+ const args =
35
+ runner === "link"
36
+ ? [join(import.meta.dir, "link-browser-runner.ts"), "webkit"]
37
+ : [
38
+ join(import.meta.dir, "page-runner/browser-controls-runner.ts"),
39
+ "webkit",
40
+ "--prepared",
41
+ "--result",
42
+ result,
43
+ ];
44
+ const child = Bun.spawn([process.execPath].concat(args), {
45
+ env: {
46
+ ...process.env,
47
+ PLAYWRIGHT_BROWSERS_PATH: root,
48
+ PLAYWRIGHT_SKIP_VALIDATE_HOST_REQUIREMENTS: "1",
49
+ PAGE_RUNNER_CONTROL_FILTER: "worker-capability-success",
50
+ PROCESS_SCRATCH_ROOT: scratch,
51
+ SCRATCH: scratch,
52
+ STORAGE_SCRATCH_ROOT: scratch,
53
+ TMPDIR: scratch,
54
+ },
55
+ timeout: 20_000,
56
+ stdout: "pipe",
57
+ stderr: "pipe",
58
+ });
59
+ await assertFailure(child, runner, result);
60
+ expect(await readdir(scratch)).toEqual([]);
61
+ } finally {
62
+ await rm(root, { recursive: true, force: true });
63
+ }
64
+ },
65
+ 30_000,
66
+ );
67
+ }
68
+
69
+ async function assertFailure(
70
+ child: Bun.Subprocess<"ignore", "pipe", "pipe">,
71
+ runner: "link" | "controls",
72
+ result: string,
73
+ ): Promise<void> {
74
+ try {
75
+ const [code, stdout, stderr] = await Promise.all([
76
+ child.exited,
77
+ new Response(child.stdout).text(),
78
+ new Response(child.stderr).text(),
79
+ ]);
80
+ expect(code).toBe(1);
81
+ expect(stderr.includes("NATIVE_LINE_1 ")).toBe(true);
82
+ expect(stderr.includes("native stdout/stderr truncated")).toBe(true);
83
+ expect(stderr.includes("<process did exit: exitCode=42, signal=null>")).toBe(true);
84
+ const failure =
85
+ runner === "link" ? linkFailure(stderr) : await Bun.file(`${result}.controls.json`).text();
86
+ expect(failure.includes("NATIVE_LINE_10 ")).toBe(false);
87
+ expect(stdout.includes("NATIVE_LINE_10 ")).toBe(false);
88
+ expect(failure.includes("NATIVE_LINE_1 ")).toBe(true);
89
+ expect(failure.includes("native stdout/stderr truncated")).toBe(true);
90
+ expect(failure.includes("<process did exit: exitCode=42, signal=null>")).toBe(true);
91
+ expect(failure.includes("<launching>")).toBe(true);
92
+ expect(
93
+ failure.includes("Target page, context or browser has been closed") ||
94
+ failure.includes("Failed to launch the browser process"),
95
+ failure.replace(/\d{100,}/g, "[launcher payload]").slice(-2500),
96
+ ).toBe(true);
97
+ expect(nativeBytes(failure)).toBeLessThanOrEqual(64 * 1024);
98
+ } finally {
99
+ if (child.exitCode === null) child.kill();
100
+ await child.exited;
101
+ }
102
+ }
103
+
104
+ function linkFailure(stderr: string): string {
105
+ const [live, failure, ...extra] = stderr.split("Link browser failed\n");
106
+ expect(extra).toEqual([]);
107
+ if (failure === undefined) throw new Error("link runner did not print its failure report");
108
+ expect(nativeBytes(live ?? "")).toBeGreaterThan(32 * 1024);
109
+ expect(nativeBytes(live ?? "")).toBeLessThanOrEqual(64 * 1024);
110
+ return failure;
111
+ }
112
+
113
+ function nativeBytes(output: string): number {
114
+ return Array.from(output.matchAll(/NATIVE_LINE_\d+ \d+/g), ([line]) => line.length).reduce(
115
+ (sum, length) => sum + length,
116
+ 0,
117
+ );
118
+ }
@@ -64,10 +64,28 @@ for (const imported of [false, true])
64
64
  else {
65
65
  // No bytes were observable: the cell holds only the last bootstrap start step.
66
66
  expect(sample < 0n).toBe(true);
67
- expect(readStartProgress(sample)?.step).toBe("group-joined");
67
+ expect(readStartProgress(sample)?.step).toBe("instantiating");
68
68
  }
69
69
  });
70
70
 
71
+ test("failure preparing native imports stays before instantiating", async () => {
72
+ const ping = () => 42;
73
+ const f = run(namedMemoryImportGuest(), {
74
+ namespaces: () => ({ env: { ping } }),
75
+ imports: () => ({
76
+ env: {
77
+ get ping(): never {
78
+ throw new Error("import argument preparation failed");
79
+ },
80
+ },
81
+ }),
82
+ run: () => 0,
83
+ });
84
+ await f.pending;
85
+ expect(f.errors[0]).toContain("import argument preparation failed");
86
+ expect(readStartProgress(Atomics.load(f.bytes, 0))?.step).toBe("group-joined");
87
+ });
88
+
71
89
  test("cancellation fences late memory binding and completion", async () => {
72
90
  const entered = Promise.withResolvers<
73
91
  WorkerBindingsContext & { bindMemory(memory: WebAssembly.Memory): void }
@@ -25,6 +25,7 @@ import { FilesystemService } from "../fs/service.js";
25
25
  import { createFilesystemIdentity } from "../fs/protocol.js";
26
26
  import { ProcessIdentityAllocator } from "../proc/identity.js";
27
27
  import { ExecutableRegistry } from "../proc/registry.js";
28
+ import { markStarted } from "../proc/outcome.js";
28
29
  import { ProcessTable } from "../proc/table.js";
29
30
  import {
30
31
  createWorkerProcessTransport,
@@ -560,19 +561,15 @@ test("real nested and inherited-thread launches reuse the admitted compiled grou
560
561
  }
561
562
  });
562
563
 
563
- // Steps the page stamps itself, so their times are ordered. Worker bootstrap steps carry the
564
- // worker's own time and only follow start-posted.
565
- const pageStartOrder: readonly ProcessStartStep[] = [
564
+ // Port messages and shared observations can arrive in either order after start-posted.
565
+ const requiredPageStartOrder: readonly ProcessStartStep[] = [
566
566
  "launching",
567
567
  "worker-constructed",
568
568
  "start-posted",
569
- "worker-started",
570
- "memory-bound",
571
- "instantiated",
572
569
  "running",
573
570
  ];
574
571
 
575
- test("start states record every step of a real worker start in order", async () => {
572
+ test("start states report a real worker running even when intermediate observations coalesce", async () => {
576
573
  const stop = Promise.withResolvers<void>();
577
574
  const f = await fixture(true, stop.promise);
578
575
  try {
@@ -585,9 +582,15 @@ test("start states record every step of a real worker start in order", async ()
585
582
  generation: 1,
586
583
  executable: "fixture",
587
584
  });
588
- const times = pageStartOrder.map((step) => started.at[step]);
585
+ const times = requiredPageStartOrder.map((step) => started.at[step]);
589
586
  expect(times.every((time) => typeof time === "number")).toBe(true);
590
587
  expect(times).toEqual(times.toSorted((a, b) => a! - b!));
588
+ for (const step of ["worker-started", "memory-bound", "instantiated"] as const) {
589
+ const observed = started.at[step];
590
+ if (observed === undefined) continue;
591
+ expect(observed).toBeGreaterThanOrEqual(started.at["start-posted"]!);
592
+ expect(observed).toBeLessThanOrEqual(started.at.running!);
593
+ }
591
594
  for (const step of ["runtime-loaded", "group-joined", "modules-loaded"] as const)
592
595
  if (started.at[step] !== undefined)
593
596
  expect(started.at[step]).toBeGreaterThanOrEqual(started.at["start-posted"]!);
@@ -624,6 +627,11 @@ test("a start whose worker never answers stays at start-posted until its first m
624
627
  Atomics.store(new BigInt64Array(worker.request!.memoryObservation!), 0, 65536n);
625
628
  expect(state()?.step).toBe("memory-bound");
626
629
  expect(state()?.at["group-joined"]).toBe(joined.at["group-joined"]);
630
+ expect(markStarted(f.supervisor.get(f.pid)!.outcome)).toBe(true);
631
+ expect(state()).toMatchObject({ step: "running", pid: f.pid });
632
+ expect(state()?.at.instantiated).toBeUndefined();
633
+ worker.onmessage?.({ data: { type: "phase", name: "instantiate", duration: 0 } });
634
+ expect(state()?.step).toBe("running");
627
635
  worker.onmessage?.({ data: { type: "exit", code: 0 } });
628
636
  await f.supervisor.waitForExit(f.root.pid, f.pid);
629
637
  expect(state()).toBeUndefined();