@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
package/proc/pipes.ts CHANGED
@@ -719,10 +719,13 @@ class PipeState {
719
719
  ? this.writers[index]!
720
720
  : this.readers[index - this.writers.length]!;
721
721
  const pid = ring.owner;
722
+ const reader = index >= this.writers.length;
722
723
  if (
723
- pid &&
724
- (pid === RECLAIMING || !this.registry?.isRevoked(Math.abs(pid))) &&
725
- (pid < 0 ? !ring.closed : ring.references > 0)
724
+ reader
725
+ ? this.readerPending(ring)
726
+ : pid &&
727
+ (pid === RECLAIMING || !this.registry?.isRevoked(Math.abs(pid))) &&
728
+ (pid < 0 ? !ring.closed : ring.references > 0)
726
729
  ) {
727
730
  alive = true;
728
731
  break;
@@ -752,6 +755,22 @@ class PipeState {
752
755
  hasReaders(): boolean {
753
756
  return ringSome(this.readers, (ring) => this.readerAlive(ring));
754
757
  }
758
+ /** A reservation or reclaiming slot may still publish a reader after the last close. */
759
+ readerHangup(): boolean {
760
+ const changed = atomicsLoad(this.changed, 0);
761
+ const generation = atomicsLoad(this.control, 5);
762
+ if (ringSome(this.readers, (ring) => this.readerPending(ring))) return false;
763
+ if (atomicsLoad(this.control, 5) === generation && atomicsLoad(this.changed, 0) === changed)
764
+ return true;
765
+ this.signal();
766
+ return false;
767
+ }
768
+ private readerPending(ring: Ring): boolean {
769
+ const pid = ring.owner;
770
+ if (pid === RECLAIMING) return true;
771
+ if (pid === 0 || this.registry?.isRevoked(Math.abs(pid))) return false;
772
+ return pid < 0 || ring.references > 0;
773
+ }
755
774
  eof(): boolean {
756
775
  const generation = atomicsLoad(this.control, 5);
757
776
  if (!ringEvery(this.writers, (ring) => ring.owner === 0 || ring.closed)) return false;
@@ -950,6 +969,7 @@ class PipeState {
950
969
  if (atomicsCompareExchange(ring.pid, 0, owner, RECLAIMING) !== owner) return undefined;
951
970
  if (!ring.advance(incarnation)) {
952
971
  atomicsStore(ring.pid, 0, owner);
972
+ this.signal();
953
973
  return undefined;
954
974
  }
955
975
  try {
@@ -1120,7 +1140,8 @@ export class PipeEndpoint implements Stream {
1120
1140
  tryWrite(chunks: readonly Uint8Array[]): number {
1121
1141
  if (this.mode !== "write" || !this.live) return -PipeErrno.BADF;
1122
1142
  if (!length(chunks)) return 0;
1123
- if (!this.state.hasReaders()) return -PipeErrno.PIPE;
1143
+ if (!this.state.hasReaders())
1144
+ return this.state.readerHangup() ? -PipeErrno.PIPE : -PipeErrno.AGAIN;
1124
1145
  const result = this.ring.write(
1125
1146
  chunks,
1126
1147
  () => this.live,
@@ -1178,13 +1199,25 @@ export class PipeEndpoint implements Stream {
1178
1199
  if (!this.live)
1179
1200
  return { readable: this.mode === "read", writable: false, hangup: true, nbytes: 0 };
1180
1201
  if (this.mode === "write") {
1181
- const hangup = !this.state.hasReaders();
1182
- return { readable: false, writable: !hangup && this.ring.writable, hangup, nbytes: 0 };
1202
+ const writable = this.state.hasReaders() && this.ring.writable;
1203
+ return {
1204
+ readable: false,
1205
+ writable,
1206
+ hangup: !writable && this.state.readerHangup(),
1207
+ nbytes: 0,
1208
+ };
1183
1209
  }
1184
1210
  const nbytes = this.state.relay ? this.state.relayAvailable() : this.state.queued();
1185
1211
  const hangup = this.state.relay ? this.ring.closed : this.state.eof();
1186
1212
  return { readable: nbytes > 0 || hangup, writable: false, hangup, nbytes };
1187
1213
  }
1214
+ async waitReaderHangup(): Promise<void> {
1215
+ for (;;) {
1216
+ const observed = atomicsLoad(this.notification, 0);
1217
+ if (!this.live || this.state.readerHangup()) return;
1218
+ await waitChanged(this.notification, observed);
1219
+ }
1220
+ }
1188
1221
  waitReadable(): Promise<void> {
1189
1222
  return this.wait("readable");
1190
1223
  }
package/proc/registry.ts CHANGED
@@ -133,6 +133,8 @@ export class ExecutableNotRunnable extends Error {
133
133
  /** Generic names -> compiled module + adapter, with one compilation per module source.
134
134
  * Instances and used workers are deliberately not cached.
135
135
  */
136
+ type AdmissionMode = "access" | "execute" | "byte-backed-guest";
137
+
136
138
  export class ExecutableRegistry {
137
139
  private readonly entries = new Map<string, RegisteredExecutable | ScriptExecutable>();
138
140
  private readonly modules = new WeakMap<Executable["module"], Promise<WebAssembly.Module>>();
@@ -179,8 +181,15 @@ export class ExecutableRegistry {
179
181
  cwd = "/",
180
182
  assertActive: () => void = () => {},
181
183
  argv?: readonly string[],
184
+ byteBackedGuestOnly = false,
182
185
  ): Promise<ResolvedExecutable> {
183
- const admitted = await this.admit(name, cwd, assertActive, argv, "execute");
186
+ const admitted = await this.admit(
187
+ name,
188
+ cwd,
189
+ assertActive,
190
+ argv,
191
+ byteBackedGuestOnly ? "byte-backed-guest" : "execute",
192
+ );
184
193
  const entry = admitted.entry;
185
194
  assertActive();
186
195
  if ("command" in entry) return this.resolveCommand(entry, admitted.argv, assertActive);
@@ -269,7 +278,7 @@ export class ExecutableRegistry {
269
278
  cwd: string,
270
279
  assertActive: () => void,
271
280
  argv: readonly string[] | undefined,
272
- mode: "access" | "execute",
281
+ mode: AdmissionMode,
273
282
  ): Promise<AdmittedExecutable> {
274
283
  const seen = new Set<string>();
275
284
  return this.admitScript(name, cwd, assertActive, argv, mode, 0, seen, 0);
@@ -280,7 +289,7 @@ export class ExecutableRegistry {
280
289
  cwd: string,
281
290
  assertActive: () => void,
282
291
  argv: readonly string[] | undefined,
283
- mode: "access" | "execute",
292
+ mode: AdmissionMode,
284
293
  depth: number,
285
294
  seen: Set<string>,
286
295
  symlinks: number,
@@ -306,17 +315,7 @@ export class ExecutableRegistry {
306
315
  symlinks,
307
316
  scriptName,
308
317
  );
309
- let file;
310
- try {
311
- file = await this.lookup(absolute);
312
- } catch (error) {
313
- assertActive();
314
- const errno =
315
- error !== null && typeof error === "object" && "errno" in error ? error.errno : undefined;
316
- if (errno === 44) throw new ExecutableNotFound(absolute);
317
- if (errno === 54) throw new ExecutableNotRunnable(absolute, false, "ENOTDIR");
318
- throw error;
319
- }
318
+ const file = await this.lookupFile(this.lookup, absolute, assertActive);
320
319
  assertActive();
321
320
  if (!file) throw new ExecutableNotFound(absolute);
322
321
  rejectNonExecutableNode(file);
@@ -338,6 +337,12 @@ export class ExecutableRegistry {
338
337
  );
339
338
  }
340
339
  const resolved = file.path === predicted ? registered : this.entries.get(file.path);
340
+ if (mode === "byte-backed-guest")
341
+ return this.admitByteBackedGuest(
342
+ file.kind === "file" ? resolved : undefined,
343
+ file.path,
344
+ argv,
345
+ );
341
346
  const admitted =
342
347
  resolved &&
343
348
  !(
@@ -385,18 +390,32 @@ export class ExecutableRegistry {
385
390
  );
386
391
  }
387
392
 
393
+ private async lookupFile(lookup: ExecutableLookup, path: string, assertActive: () => void) {
394
+ try {
395
+ return await lookup(path);
396
+ } catch (error) {
397
+ assertActive();
398
+ const errno =
399
+ error !== null && typeof error === "object" && "errno" in error ? error.errno : undefined;
400
+ if (errno === 44) throw new ExecutableNotFound(path);
401
+ if (errno === 54) throw new ExecutableNotRunnable(path, false, "ENOTDIR");
402
+ throw error;
403
+ }
404
+ }
405
+
388
406
  private async admitEntry(
389
407
  entry: RegisteredExecutable | ScriptExecutable | undefined,
390
408
  path: string,
391
409
  cwd: string,
392
410
  assertActive: () => void,
393
411
  argv: readonly string[] | undefined,
394
- mode: "access" | "execute",
412
+ mode: AdmissionMode,
395
413
  depth: number,
396
414
  seen: Set<string>,
397
415
  symlinks: number,
398
416
  scriptName: string,
399
417
  ): Promise<AdmittedExecutable> {
418
+ if (mode === "byte-backed-guest") return this.admitByteBackedGuest(entry, path, argv);
400
419
  if (!entry) throw new ExecutableNotFound(path);
401
420
  if ("script" in entry)
402
421
  return this.admitRegisteredScript(
@@ -415,13 +434,29 @@ export class ExecutableRegistry {
415
434
  return { entry, ...(argv ? { argv } : {}) };
416
435
  }
417
436
 
437
+ private admitByteBackedGuest(
438
+ entry: RegisteredExecutable | ScriptExecutable | undefined,
439
+ path: string,
440
+ argv?: readonly string[],
441
+ ): AdmittedExecutable {
442
+ if (
443
+ !entry ||
444
+ "script" in entry ||
445
+ "command" in entry ||
446
+ !entry.interruptible ||
447
+ entry.execution?.kind !== "guest"
448
+ )
449
+ throw new ExecutableNotRunnable(path, false);
450
+ return { entry, ...(argv ? { argv } : {}) };
451
+ }
452
+
418
453
  private async admitRegisteredScript(
419
454
  executable: ScriptExecutable,
420
455
  path: string,
421
456
  cwd: string,
422
457
  assertActive: () => void,
423
458
  argv: readonly string[] | undefined,
424
- mode: "access" | "execute",
459
+ mode: AdmissionMode,
425
460
  depth: number,
426
461
  seen: Set<string>,
427
462
  symlinks: number,
@@ -471,7 +506,7 @@ export class ExecutableRegistry {
471
506
  return bytes?.length === marker.length && bytes.every((byte, index) => byte === marker[index]);
472
507
  }
473
508
 
474
- private notRunnable(path: string, mode: "access" | "execute", invalid = false): Error {
509
+ private notRunnable(path: string, mode: AdmissionMode, invalid = false): Error {
475
510
  if (mode === "access") return new ExecutableNotRunnable(path, false);
476
511
  return invalid
477
512
  ? new ExecutableFormatError(`invalid executable: ${path}`)
@@ -0,0 +1,157 @@
1
+ import type { Runtime } from "../runtime.js";
2
+ import type { ProcessExit, ProcessSignal } from "./types.js";
3
+
4
+ export interface CommandOutputOptions {
5
+ readonly limitBytes?: number;
6
+ readonly onChunk?: (bytes: Uint8Array) => undefined;
7
+ }
8
+
9
+ export interface CommandOptions {
10
+ readonly filesystem: "runtime-root";
11
+ readonly args?: readonly string[];
12
+ readonly cwd?: string;
13
+ readonly env?: Readonly<Record<string, string>>;
14
+ readonly stdin?: Uint8Array | ReadableStream<Uint8Array> | "closed";
15
+ readonly stdout?: CommandOutputOptions | "closed";
16
+ readonly stderr?: CommandOutputOptions | "closed";
17
+ readonly deadlineMs?: number;
18
+ }
19
+
20
+ export interface CommandOutput {
21
+ readonly bytes: Uint8Array;
22
+ readonly truncated: boolean;
23
+ }
24
+
25
+ type StopRequest = "kill" | "deadline";
26
+
27
+ export type CommandResult = Readonly<{
28
+ stdout: CommandOutput;
29
+ stderr: CommandOutput;
30
+ }> &
31
+ (
32
+ | Readonly<{ exit: ProcessExit; stopRequested?: StopRequest }>
33
+ | Readonly<{ exit: null; stopRequested: StopRequest }>
34
+ );
35
+
36
+ export interface RunningCommand {
37
+ readonly result: Promise<CommandResult>;
38
+ signal(signal: ProcessSignal): Promise<void>;
39
+ kill(): Promise<CommandResult>;
40
+ }
41
+
42
+ function text(value: unknown): value is string {
43
+ return (
44
+ typeof value === "string" &&
45
+ !value.includes("\0") &&
46
+ !/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(value)
47
+ );
48
+ }
49
+
50
+ function path(value: unknown): value is string {
51
+ return text(value) && value.startsWith("/");
52
+ }
53
+
54
+ function output(value: CommandOutputOptions | "closed" | undefined) {
55
+ if (value === "closed" || value === undefined) return value;
56
+ if (!value || typeof value !== "object") throw new TypeError("Invalid command output");
57
+ const { limitBytes, onChunk } = value;
58
+ if (limitBytes !== undefined && (!Number.isSafeInteger(limitBytes) || limitBytes < 0))
59
+ throw new RangeError("Command output limit must be a nonnegative integer");
60
+ if (onChunk !== undefined && typeof onChunk !== "function")
61
+ throw new TypeError("Command output callback must be a function");
62
+ return { limitBytes, onChunk };
63
+ }
64
+
65
+ function snapshot(executable: string, options: CommandOptions): CommandOptions {
66
+ if (options?.filesystem !== "runtime-root")
67
+ throw new TypeError('Commands require filesystem: "runtime-root"');
68
+ if (!path(executable)) throw new TypeError("Command executable must be an absolute path");
69
+ const { args, cwd = "/", env, stdin, stdout, stderr, deadlineMs } = options;
70
+ if (!path(cwd)) throw new TypeError("Command cwd must be an absolute path");
71
+ if (args !== undefined && !Array.isArray(args)) throw new TypeError("Invalid command args");
72
+ const argv = Array.from(args ?? []);
73
+ if (!argv.every(text)) throw new TypeError("Invalid command argument");
74
+ if (env !== undefined && (!env || typeof env !== "object" || Array.isArray(env)))
75
+ throw new TypeError("Invalid command environment");
76
+ const entries = Object.entries(env ?? {});
77
+ if (entries.some(([key, value]) => !text(key) || !text(value) || !key || key.includes("=")))
78
+ throw new TypeError("Invalid command environment entry");
79
+ if (
80
+ stdin !== undefined &&
81
+ stdin !== "closed" &&
82
+ !(stdin instanceof Uint8Array) &&
83
+ !(stdin instanceof ReadableStream)
84
+ )
85
+ throw new TypeError("Invalid command stdin");
86
+ if (stdin instanceof ReadableStream && stdin.locked)
87
+ throw new TypeError("Command stdin is already locked");
88
+ if (
89
+ deadlineMs !== undefined &&
90
+ (!Number.isInteger(deadlineMs) || deadlineMs < 1 || deadlineMs > 0x7fffffff)
91
+ )
92
+ throw new RangeError("Command deadline must be between 1 and 2147483647 ms");
93
+ return {
94
+ filesystem: "runtime-root",
95
+ args: argv,
96
+ cwd,
97
+ env: Object.fromEntries(entries),
98
+ stdin: stdin instanceof Uint8Array ? new Uint8Array(stdin) : stdin,
99
+ stdout: output(stdout),
100
+ stderr: output(stderr),
101
+ deadlineMs,
102
+ };
103
+ }
104
+
105
+ /** Run an installed, byte-backed Wasm program in the caller's runtime. */
106
+ export function startCommand(
107
+ runtime: Runtime,
108
+ executable: string,
109
+ options: CommandOptions,
110
+ ): RunningCommand {
111
+ const started = performance.now();
112
+ const input = snapshot(executable, options);
113
+ const stopped = new AbortController();
114
+ let stopRequested: StopRequest | undefined;
115
+ let settled = false;
116
+ const stop = (reason: StopRequest) => {
117
+ if (settled || stopRequested) return;
118
+ stopRequested = reason;
119
+ stopped.abort();
120
+ };
121
+ let timer: ReturnType<typeof setTimeout> | undefined;
122
+ if (input.deadlineMs !== undefined) {
123
+ const remaining = input.deadlineMs - (performance.now() - started);
124
+ if (remaining <= 0) stop("deadline");
125
+ else timer = setTimeout(() => stop("deadline"), Math.ceil(remaining));
126
+ }
127
+ const running = import("../browser/run-command.js").then(({ runCommand }) =>
128
+ runCommand(runtime, executable, input, stopped.signal),
129
+ );
130
+ let active: typeof running | undefined = running;
131
+ const result: Promise<CommandResult> = running
132
+ .then((command) => command.result)
133
+ .then(({ exit, stdout, stderr }) => {
134
+ if (exit) return { exit, stdout, stderr, ...(stopRequested ? { stopRequested } : {}) };
135
+ if (!stopRequested) throw new Error("Command did not reserve its leader");
136
+ return { exit: null, stdout, stderr, stopRequested };
137
+ })
138
+ .finally(() => {
139
+ settled = true;
140
+ active = undefined;
141
+ clearTimeout(timer);
142
+ });
143
+ return {
144
+ result,
145
+ async signal(signal) {
146
+ if (signal === 9) {
147
+ stop("kill");
148
+ return;
149
+ }
150
+ await (await active)?.signal(signal);
151
+ },
152
+ kill() {
153
+ stop("kill");
154
+ return result;
155
+ },
156
+ };
157
+ }
@@ -106,6 +106,7 @@ interface ProcessAccesses {
106
106
 
107
107
  export interface SupervisorOptions {
108
108
  registry: ExecutableRegistry;
109
+ byteBackedGuestOnly?(rootPid: number | undefined): boolean;
109
110
  launch(context: ProcessContext): ProcessHandle | Promise<ProcessHandle>;
110
111
  launchCommand?(context: CommandProcessContext): ProcessHandle | Promise<ProcessHandle>;
111
112
  /** Emit while inherited output is owned; an asynchronous sink must stop when active is false.
@@ -272,6 +273,19 @@ export class ProcessSupervisor {
272
273
  }
273
274
  return complete;
274
275
  }
276
+ /** A guest wait can consume its job while its physical stops remain in this owner. */
277
+ rootConsumersRetired(rootPid: number): boolean {
278
+ let complete = true;
279
+ for (const records of this.consumers.values()) {
280
+ for (const record of records) {
281
+ if (record.rootPid !== rootPid || record.pid === rootPid) continue;
282
+ if (record.retirement?.kind === "failed") throw record.retirement.error;
283
+ if (!record.retirement) complete = false;
284
+ }
285
+ }
286
+ return complete;
287
+ }
288
+
275
289
  cwd(pid: number): string {
276
290
  return this.accessOwner(pid).image.cwd;
277
291
  }
@@ -834,6 +848,7 @@ export class ProcessSupervisor {
834
848
  throw new Error("process exited before executable admission completed");
835
849
  },
836
850
  image.request!.argv,
851
+ this.options.byteBackedGuestOnly?.(record.rootPid),
837
852
  );
838
853
  if (record.result || record.revoked) return;
839
854
  const settled = readOutcome(record.outcome);
@@ -930,7 +945,7 @@ export class ProcessSupervisor {
930
945
  descriptors: DescriptorTable;
931
946
  complete(result: number, error?: unknown): void;
932
947
  install(): void;
933
- discard(): void | Promise<void>;
948
+ discard(descriptors: DescriptorTable): void | Promise<void>;
934
949
  },
935
950
  ): ProcessReplacement {
936
951
  const record = this.accessOwner(pid);
@@ -956,10 +971,7 @@ export class ProcessSupervisor {
956
971
  },
957
972
  discard: () => {
958
973
  if (transferred) return Promise.resolve();
959
- return (discarded ??= Promise.resolve().then(async () => {
960
- this.disposeDescriptors(staged.descriptors);
961
- await staged.discard();
962
- }));
974
+ return (discarded ??= Promise.resolve().then(() => staged.discard(staged.descriptors)));
963
975
  },
964
976
  cancel: async (error = new ProcessError(ProcessErrno.SRCH, "replacement cancelled")) => {
965
977
  if (replacement.state.phase === "done") return;
@@ -1007,6 +1019,7 @@ export class ProcessSupervisor {
1007
1019
  replacement.request.cwd,
1008
1020
  active,
1009
1021
  replacement.request.argv,
1022
+ this.options.byteBackedGuestOnly?.(record.rootPid),
1010
1023
  );
1011
1024
  active();
1012
1025
  if (record.processKind === "thread")
@@ -1086,7 +1099,8 @@ export class ProcessSupervisor {
1086
1099
  if (image.stopping) return image.stopping;
1087
1100
  const stop = async () => {
1088
1101
  this.revokeImage(image);
1089
- this.disposeDescriptors(image.descriptors);
1102
+ if (this.options.byteBackedGuestOnly?.(record.rootPid)) image.descriptors.dispose();
1103
+ else this.disposeDescriptors(image.descriptors);
1090
1104
  await this.options.stopImage!(record.pid, image.generation, () =>
1091
1105
  this.replacementActive(record, replacement),
1092
1106
  );
@@ -1543,7 +1557,14 @@ export class ProcessSupervisor {
1543
1557
  record.revocations.clear();
1544
1558
  for (const hook of hooks) this.safely(hook);
1545
1559
  this.revokeImage(record.image);
1546
- this.disposeDescriptors(record.image.descriptors);
1560
+ this.disposeDescriptors(record.image.descriptors, (error) => {
1561
+ if (!this.options.byteBackedGuestOnly?.(record.rootPid)) {
1562
+ this.report(error);
1563
+ return;
1564
+ }
1565
+ fenceFailed = true;
1566
+ this.failRetirementFence(record, error);
1567
+ });
1547
1568
  // Invoke the fence while broker child/identity records are still present. Every observer
1548
1569
  // must wait for admitted filesystem and adapter work (for example a terminal section),
1549
1570
  // independently of the physical worker's potentially delayed termination.
@@ -1826,13 +1847,17 @@ export class ProcessSupervisor {
1826
1847
  // already have retired it while its separately captured physical stop was pending.
1827
1848
  if (this.table.job(job.id) === job) this.reapJob(owner, job.id);
1828
1849
  }
1829
- private disposeDescriptors(descriptors: DescriptorTable): void {
1850
+ private disposeDescriptors(
1851
+ descriptors: DescriptorTable,
1852
+ onError?: (error: unknown) => void,
1853
+ ): void {
1830
1854
  // dispose drains every entry before reporting release errors. These errors are diagnostics,
1831
1855
  // not transient work: report once and continue to the explicit host quiescence fence.
1832
1856
  try {
1833
1857
  descriptors.dispose();
1834
1858
  } catch (error) {
1835
- this.report(error);
1859
+ if (onError) onError(error);
1860
+ else this.report(error);
1836
1861
  }
1837
1862
  }
1838
1863
  private safely(operation: () => void): void {