@namzu/sandbox 13.0.0 → 15.0.0

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 (104) hide show
  1. package/CHANGELOG.md +1147 -0
  2. package/README.md +447 -0
  3. package/dist/backends/aci-standby-pool/index.d.ts.map +1 -1
  4. package/dist/backends/aci-standby-pool/index.js +13 -1
  5. package/dist/backends/aci-standby-pool/index.js.map +1 -1
  6. package/dist/backends/docker/index.d.ts.map +1 -1
  7. package/dist/backends/docker/index.js +19 -1
  8. package/dist/backends/docker/index.js.map +1 -1
  9. package/dist/backends/firecracker/index.d.ts.map +1 -1
  10. package/dist/backends/firecracker/index.js +12 -2
  11. package/dist/backends/firecracker/index.js.map +1 -1
  12. package/dist/backends/firecracker/protocol.d.ts +481 -8
  13. package/dist/backends/firecracker/protocol.d.ts.map +1 -1
  14. package/dist/backends/firecracker/protocol.js +136 -0
  15. package/dist/backends/firecracker/protocol.js.map +1 -1
  16. package/dist/backends/firecracker/transport.d.ts +642 -14
  17. package/dist/backends/firecracker/transport.d.ts.map +1 -1
  18. package/dist/backends/firecracker/transport.js +1307 -34
  19. package/dist/backends/firecracker/transport.js.map +1 -1
  20. package/dist/backends/kubernetes/egress-policy.d.ts +1296 -0
  21. package/dist/backends/kubernetes/egress-policy.d.ts.map +1 -0
  22. package/dist/backends/kubernetes/egress-policy.js +2458 -0
  23. package/dist/backends/kubernetes/egress-policy.js.map +1 -0
  24. package/dist/backends/kubernetes/identity.d.ts +193 -0
  25. package/dist/backends/kubernetes/identity.d.ts.map +1 -0
  26. package/dist/backends/kubernetes/identity.js +147 -0
  27. package/dist/backends/kubernetes/identity.js.map +1 -0
  28. package/dist/backends/kubernetes/index.d.ts +1019 -0
  29. package/dist/backends/kubernetes/index.d.ts.map +1 -0
  30. package/dist/backends/kubernetes/index.js +1756 -0
  31. package/dist/backends/kubernetes/index.js.map +1 -0
  32. package/dist/backends/kubernetes/ingress-policy.d.ts +375 -0
  33. package/dist/backends/kubernetes/ingress-policy.d.ts.map +1 -0
  34. package/dist/backends/kubernetes/ingress-policy.js +1050 -0
  35. package/dist/backends/kubernetes/ingress-policy.js.map +1 -0
  36. package/dist/backends/kubernetes/k8s-client.d.ts +334 -0
  37. package/dist/backends/kubernetes/k8s-client.d.ts.map +1 -0
  38. package/dist/backends/kubernetes/k8s-client.js +553 -0
  39. package/dist/backends/kubernetes/k8s-client.js.map +1 -0
  40. package/dist/backends/kubernetes/lease.d.ts +145 -0
  41. package/dist/backends/kubernetes/lease.d.ts.map +1 -0
  42. package/dist/backends/kubernetes/lease.js +201 -0
  43. package/dist/backends/kubernetes/lease.js.map +1 -0
  44. package/dist/backends/kubernetes/objects.d.ts +702 -0
  45. package/dist/backends/kubernetes/objects.d.ts.map +1 -0
  46. package/dist/backends/kubernetes/objects.js +518 -0
  47. package/dist/backends/kubernetes/objects.js.map +1 -0
  48. package/dist/backends/kubernetes/per-sandbox-policy.d.ts +219 -0
  49. package/dist/backends/kubernetes/per-sandbox-policy.d.ts.map +1 -0
  50. package/dist/backends/kubernetes/per-sandbox-policy.js +407 -0
  51. package/dist/backends/kubernetes/per-sandbox-policy.js.map +1 -0
  52. package/dist/backends/kubernetes/privilege-probe.d.ts +136 -0
  53. package/dist/backends/kubernetes/privilege-probe.d.ts.map +1 -0
  54. package/dist/backends/kubernetes/privilege-probe.js +185 -0
  55. package/dist/backends/kubernetes/privilege-probe.js.map +1 -0
  56. package/dist/backends/kubernetes/rbac.d.ts +153 -0
  57. package/dist/backends/kubernetes/rbac.d.ts.map +1 -0
  58. package/dist/backends/kubernetes/rbac.js +177 -0
  59. package/dist/backends/kubernetes/rbac.js.map +1 -0
  60. package/dist/backends/kubernetes/sandbox.d.ts +190 -0
  61. package/dist/backends/kubernetes/sandbox.d.ts.map +1 -0
  62. package/dist/backends/kubernetes/sandbox.js +433 -0
  63. package/dist/backends/kubernetes/sandbox.js.map +1 -0
  64. package/dist/backends/kubernetes/transport.d.ts +1048 -0
  65. package/dist/backends/kubernetes/transport.d.ts.map +1 -0
  66. package/dist/backends/kubernetes/transport.js +2093 -0
  67. package/dist/backends/kubernetes/transport.js.map +1 -0
  68. package/dist/backends/kubernetes/workspace.d.ts +1512 -0
  69. package/dist/backends/kubernetes/workspace.d.ts.map +1 -0
  70. package/dist/backends/kubernetes/workspace.js +3703 -0
  71. package/dist/backends/kubernetes/workspace.js.map +1 -0
  72. package/dist/backends/remote-execution-controller.d.ts +14 -0
  73. package/dist/backends/remote-execution-controller.d.ts.map +1 -1
  74. package/dist/backends/remote-execution-controller.js.map +1 -1
  75. package/dist/index.d.ts +350 -2
  76. package/dist/index.d.ts.map +1 -1
  77. package/dist/index.js +344 -34
  78. package/dist/index.js.map +1 -1
  79. package/dist/testing/sandbox-conformance.d.ts +227 -0
  80. package/dist/testing/sandbox-conformance.d.ts.map +1 -0
  81. package/dist/testing/sandbox-conformance.js +896 -0
  82. package/dist/testing/sandbox-conformance.js.map +1 -0
  83. package/package.json +5 -4
  84. package/src/backends/aci-standby-pool/index.ts +16 -1
  85. package/src/backends/docker/index.ts +22 -1
  86. package/src/backends/firecracker/index.ts +14 -2
  87. package/src/backends/firecracker/protocol.ts +541 -6
  88. package/src/backends/firecracker/transport.ts +1687 -64
  89. package/src/backends/kubernetes/egress-policy.ts +3448 -0
  90. package/src/backends/kubernetes/identity.ts +261 -0
  91. package/src/backends/kubernetes/index.ts +2670 -0
  92. package/src/backends/kubernetes/ingress-policy.ts +1344 -0
  93. package/src/backends/kubernetes/k8s-client.ts +742 -0
  94. package/src/backends/kubernetes/lease.ts +254 -0
  95. package/src/backends/kubernetes/objects.ts +983 -0
  96. package/src/backends/kubernetes/per-sandbox-policy.ts +542 -0
  97. package/src/backends/kubernetes/privilege-probe.ts +261 -0
  98. package/src/backends/kubernetes/rbac.ts +192 -0
  99. package/src/backends/kubernetes/sandbox.ts +593 -0
  100. package/src/backends/kubernetes/transport.ts +2895 -0
  101. package/src/backends/kubernetes/workspace.ts +5640 -0
  102. package/src/backends/remote-execution-controller.ts +14 -0
  103. package/src/index.ts +838 -35
  104. package/src/testing/sandbox-conformance.ts +1202 -0
@@ -0,0 +1,896 @@
1
+ /**
2
+ * The {@link Sandbox} contract, as a suite a backend author runs against
3
+ * their own implementation.
4
+ *
5
+ * ## Why this exists
6
+ *
7
+ * `@namzu/sdk`'s `Sandbox` interface is the one thing every backend in this
8
+ * package promises to implement the same way — `exec`'s exit codes, the
9
+ * `AbortSignal` contract, a `writeFile`/`readFile` round trip, terminal
10
+ * ownership on `destroy()` — and until now nothing PROVED that two backends
11
+ * agreed on any of it. Each backend carried its own bespoke test file
12
+ * (`sandbox-surface.test.ts`, `backend.test.ts`, …), written by whoever
13
+ * built that backend, checking whatever that author thought to check. A
14
+ * shared contract can be silently narrower than either file: this suite is
15
+ * the thing that would have caught it.
16
+ *
17
+ * ## Why it takes its runner as an argument
18
+ *
19
+ * The same shape as `@namzu/sdk/testing`'s checkpoint-store and provider
20
+ * driver suites, and for the same two reasons: `@namzu/sandbox` gains no
21
+ * test dependency from publishing it, and a caller can pass a RECORDING
22
+ * `describe`/`it` and run the whole contract as ordinary code — which is
23
+ * how `testing/__tests__/conformance-fails-a-broken-sandbox.test.ts`
24
+ * proves a deliberately wrong `Sandbox` fails it.
25
+ *
26
+ * ## What is asserted, and what deliberately is not
27
+ *
28
+ * Contract behaviour only — never a backend-specific object, field or
29
+ * error string. A case never inspects `sandbox.constructor.name`, never
30
+ * matches an error message, and never assumes a particular
31
+ * {@link SandboxEnvironment}. `openTerminal`, `openTcpConnection` and
32
+ * `walkFiles` are OPTIONAL on {@link Sandbox} by the SDK's own contract — a
33
+ * backend that cannot honour one must omit it rather than accept and ignore
34
+ * it — so a factory whose sandbox omits any of them skips that section rather
35
+ * than failing it. Every other section runs against every sandbox.
36
+ *
37
+ * ## Where it runs today
38
+ *
39
+ * Both `backends/kubernetes/__tests__/conformance.test.ts` and
40
+ * `backends/firecracker/__tests__/conformance.test.ts` call this against a
41
+ * real `agent/agent.cjs` on a loopback socket — proving the suite is
42
+ * backend-agnostic rather than one backend's tests wearing a new name.
43
+ * `packages/sandbox/k8s/scripts/contract-suite.mjs` runs it a third time,
44
+ * against a live cluster.
45
+ *
46
+ * ## Not published from `@namzu/sandbox`'s entry point
47
+ *
48
+ * The package has no `testing` subpath today (unlike `@namzu/sdk`), and
49
+ * this batch does not add one — promoting this to a public import path is
50
+ * a deliberate, separate decision. Within the monorepo a caller imports it
51
+ * by relative path, exactly as the two files above do:
52
+ *
53
+ * ```ts sketch
54
+ * import { defineSandboxConformance } from '../../../testing/sandbox-conformance.js'
55
+ *
56
+ * defineSandboxConformance({
57
+ * describe, it, expect,
58
+ * label: 'my-backend',
59
+ * makeSandbox: async () => ({ sandbox: await myBackend.create(), dispose: async () => {} }),
60
+ * })
61
+ * ```
62
+ */
63
+ import { createHash } from 'node:crypto';
64
+ /**
65
+ * The contract revision these assertions express. Carried on the describe
66
+ * label so a failure is legible on sight as "the sandbox contract", the
67
+ * same convention `PROVIDER_DRIVER_CONTRACT_VERSION` uses — raised only
68
+ * when a case is ADDED or TIGHTENED, never on a rewording.
69
+ *
70
+ * 3 is the `walkFiles`, concurrent-`exec` and `exec`-timeout sections, none
71
+ * of which needs a guest feature that did not already exist.
72
+ *
73
+ * **The ranged and streamed read cases deliberately did NOT raise it
74
+ * further.** Raising it for them would assert that every backend this suite
75
+ * runs against implements them, and one does not: the Firecracker tier's
76
+ * guest lives in a golden rootfs image that is NOT built from this
77
+ * repository — nothing here builds one, `packages/sandbox/package.json#files`
78
+ * does not even ship `agent/`, and `README.md` documents the image as
79
+ * something the operator builds and canaries on their own schedule. A
80
+ * deployment therefore runs whatever agent its last image build baked in,
81
+ * and a contract version that claimed otherwise would be a claim about
82
+ * images this repository cannot see. Those two cases are gated on
83
+ * {@link SandboxConformanceOptions.supportsRangedAndStreamedReads}
84
+ * instead, and skip by name when a backend does not declare them.
85
+ */
86
+ export const SANDBOX_CONTRACT_VERSION = 3;
87
+ /** Assert `call()` rejects. The contract cares that admission was refused, never the message. */
88
+ async function expectRejects(expect, call) {
89
+ let rejected = false;
90
+ try {
91
+ await call();
92
+ }
93
+ catch {
94
+ rejected = true;
95
+ }
96
+ expect(rejected).toBe(true);
97
+ }
98
+ /** Assert `call()` resolves — the inverse check, for the rare case a rejection is the defect. */
99
+ async function expectResolves(expect, call) {
100
+ let threw;
101
+ try {
102
+ await call();
103
+ }
104
+ catch (error) {
105
+ threw = error;
106
+ }
107
+ expect(threw === undefined).toBe(true);
108
+ }
109
+ function sleep(ms) {
110
+ return new Promise((resolve) => setTimeout(resolve, ms));
111
+ }
112
+ /**
113
+ * `size` bytes of deterministic pseudo-random content (xorshift32 from a
114
+ * fixed seed).
115
+ *
116
+ * Pseudo-random rather than a repeated byte because the large-body case
117
+ * below is about whether every byte survived in the right ORDER: a body of
118
+ * one repeated value passes a length check and a content check even if the
119
+ * transport shipped its pieces out of order, duplicated one, or dropped
120
+ * one and padded. Deterministic rather than `randomBytes` so a failure is
121
+ * reproducible from the size alone.
122
+ */
123
+ function deterministicBytes(size) {
124
+ const out = Buffer.allocUnsafe(size);
125
+ let x = 0x9e3779b9;
126
+ for (let i = 0; i < size; i += 1) {
127
+ x ^= x << 13;
128
+ x >>>= 0;
129
+ x ^= x >> 17;
130
+ x ^= x << 5;
131
+ x >>>= 0;
132
+ out[i] = x & 0xff;
133
+ }
134
+ return out;
135
+ }
136
+ /** `sha256` of a buffer, hex — a byte-exact comparison that prints short. */
137
+ function digest(buffer) {
138
+ return createHash('sha256').update(buffer).digest('hex');
139
+ }
140
+ /** What {@link nodeGuestListener} has its script print once it is bound. */
141
+ const NODE_LISTENER_MARKER = 'namzu-conformance-listening:';
142
+ /**
143
+ * The default {@link GuestListenerCommand}: `node -e` binding an ephemeral
144
+ * port on the GUEST's own loopback, echoing `conformance-reply:<payload>`
145
+ * back for the first chunk of the one connection it accepts, then reporting
146
+ * the bound port on its own stdout — the only way the host, which cannot
147
+ * inspect a real remote guest's open ports any other way, learns which port
148
+ * to dial.
149
+ *
150
+ * Every backend this suite ships against runs `agent/agent.cjs` in the
151
+ * guest, which is itself node — so node on the guest's `PATH` is not an
152
+ * extra requirement this suite invents, it is a precondition of the agent
153
+ * existing at all. A backend whose guest genuinely cannot run node (or
154
+ * cannot run `openTerminal`) declares that through
155
+ * {@link SandboxConformanceOptions.guestCanRunNode} or supplies its own
156
+ * command via {@link SandboxConformanceOptions.guestListenerCommand}.
157
+ */
158
+ export function nodeGuestListener() {
159
+ const script = [
160
+ "const net = require('node:net');",
161
+ 'const server = net.createServer((socket) => {',
162
+ " socket.once('data', (chunk) => {",
163
+ " socket.end(Buffer.concat([Buffer.from('conformance-reply:'), chunk]));",
164
+ ' });',
165
+ '});',
166
+ "server.listen(0, '127.0.0.1', () => {",
167
+ ` process.stdout.write(${JSON.stringify(NODE_LISTENER_MARKER)} + server.address().port + '\\n');`,
168
+ '});',
169
+ ].join('\n');
170
+ return {
171
+ command: 'node',
172
+ args: ['-e', script],
173
+ parsePort(output) {
174
+ const marker = output.indexOf(NODE_LISTENER_MARKER);
175
+ if (marker === -1)
176
+ return undefined;
177
+ const match = /\d+/.exec(output.slice(marker + NODE_LISTENER_MARKER.length));
178
+ return match ? Number(match[0]) : undefined;
179
+ },
180
+ };
181
+ }
182
+ /**
183
+ * Start `listener` through `openTerminal`, and resolve once it has reported
184
+ * the port it bound.
185
+ *
186
+ * The returned `stop()` kills the terminal's owned process tree — the exact
187
+ * ownership guarantee the `openTerminal` section above already proves
188
+ * `destroy()` gets for free, used here to tear the listener down without
189
+ * waiting for the whole sandbox to go away.
190
+ *
191
+ * Takes `openTerminal` as a plain function rather than a `Sandbox`, so a
192
+ * unit test can exercise the port-parsing and exit-races above without a
193
+ * `Sandbox` fixture — see `__tests__/guest-listener.test.ts`.
194
+ */
195
+ export async function startGuestListener(openTerminal, listener) {
196
+ const terminal = await openTerminal({
197
+ command: listener.command,
198
+ args: listener.args,
199
+ size: { cols: 80, rows: 24 },
200
+ });
201
+ let output = '';
202
+ const port = await new Promise((resolve, reject) => {
203
+ const unsubscribe = terminal.onData((chunk) => {
204
+ output += chunk;
205
+ const found = listener.parsePort(output);
206
+ if (found !== undefined) {
207
+ unsubscribe();
208
+ resolve(found);
209
+ }
210
+ });
211
+ void terminal.exited.then((result) => {
212
+ // A settled promise ignores a later resolve/reject, so this is a
213
+ // no-op on the path where the port was already found and `stop()`
214
+ // is what causes this exit — it only fires the rejection when the
215
+ // listener died before ever reporting a port.
216
+ if (listener.parsePort(output) === undefined) {
217
+ unsubscribe();
218
+ reject(new Error(`guest listener exited before reporting a port (exit code ${result.exitCode}): ${output || '<no output>'}`));
219
+ }
220
+ });
221
+ });
222
+ return {
223
+ port,
224
+ async stop() {
225
+ terminal.kill();
226
+ await terminal.exited.catch(() => { });
227
+ },
228
+ };
229
+ }
230
+ /**
231
+ * Register the {@link Sandbox} contract against one backend.
232
+ *
233
+ * Call it once per backend. It registers cases through the supplied
234
+ * `describe`/`it`; it does not run them.
235
+ */
236
+ export function defineSandboxConformance(options) {
237
+ const { describe, it, expect, makeSandbox } = options;
238
+ const label = options.label ?? 'sandbox';
239
+ const guestCanRunNode = options.guestCanRunNode ?? true;
240
+ const guestListenerCommand = options.guestListenerCommand ?? nodeGuestListener;
241
+ const supportsRangedAndStreamedReads = options.supportsRangedAndStreamedReads ?? false;
242
+ /**
243
+ * Run `body` against a sandbox built for this case alone.
244
+ *
245
+ * Destroys the sandbox itself (idempotent, so a body that already
246
+ * destroyed it costs nothing extra) before calling `dispose`, so a
247
+ * case that forgets to release a pod/microVM does not leak one — the
248
+ * same reasoning `withStore`'s `finally` states for a leaked temp
249
+ * directory: a suite that is expensive to run red is a suite people
250
+ * stop running.
251
+ */
252
+ const withSandbox = (body) => async () => {
253
+ const handle = await makeSandbox();
254
+ try {
255
+ await body(handle.sandbox);
256
+ }
257
+ finally {
258
+ await handle.sandbox.destroy().catch(() => { });
259
+ await handle.dispose?.();
260
+ }
261
+ };
262
+ /**
263
+ * A case that needs {@link SandboxConformanceOptions.supportsRangedAndStreamedReads}.
264
+ *
265
+ * The skip is deliberately visible: the reason is in the case's TITLE and
266
+ * the case still runs and is counted in the runner's totals, which is what
267
+ * {@link SANDBOX_CONTRACT_VERSION}'s note asks for. What it does not do is
268
+ * build a sandbox to skip inside — `withSandbox` is applied only on the
269
+ * branch that uses one, so a backend without the capability pays nothing
270
+ * per skipped case.
271
+ */
272
+ const rangedReadCase = (title, body) => supportsRangedAndStreamedReads
273
+ ? [title, withSandbox(body)]
274
+ : [`${title} (skipped: supportsRangedAndStreamedReads is false)`, async () => { }];
275
+ describe(`${label} — sandbox contract v${SANDBOX_CONTRACT_VERSION}`, () => {
276
+ describe('exec', () => {
277
+ it('reports the exit code and streams stdout/stderr as the command runs', withSandbox(async (sandbox) => {
278
+ const chunks = [];
279
+ const result = await sandbox.exec('/bin/sh', ['-c', 'echo conformance-out; echo conformance-err 1>&2; exit 7'], { onOutput: (chunk) => chunks.push({ ...chunk }) });
280
+ expect(result.exitCode).toBe(7);
281
+ expect(result.timedOut).toBe(false);
282
+ expect(result.stdout).toMatch(/conformance-out/);
283
+ expect(result.stderr).toMatch(/conformance-err/);
284
+ // Streamed, not just present in the final string: a backend
285
+ // that buffers everything until exit and calls `onOutput`
286
+ // once at the end would satisfy the two checks above and
287
+ // fail this one.
288
+ expect(chunks.some((c) => c.stream === 'stdout' && c.data.includes('conformance-out'))).toBe(true);
289
+ expect(chunks.some((c) => c.stream === 'stderr' && c.data.includes('conformance-err'))).toBe(true);
290
+ }));
291
+ it('reports busy while a command is in flight and ready once it settles', withSandbox(async (sandbox) => {
292
+ let observedBusy = false;
293
+ await sandbox.exec('/bin/sh', ['-c', 'echo started; sleep 0.2'], {
294
+ onOutput: (chunk) => {
295
+ if (chunk.data.includes('started'))
296
+ observedBusy = sandbox.status === 'busy';
297
+ },
298
+ });
299
+ expect(observedBusy).toBe(true);
300
+ expect(sandbox.status).toBe('ready');
301
+ }));
302
+ it('honours an AbortSignal: the process is really terminated, never a partial success', withSandbox(async (sandbox) => {
303
+ // The contract (`SandboxExecOptions.signal`'s own doc comment):
304
+ // a backend that accepts the signal must terminate the process
305
+ // it owns, or prove admission never happened; it must never
306
+ // silently ignore the signal and let the command run to
307
+ // completion while reporting as though it had been cancelled.
308
+ // The command below writes a marker file a moment after
309
+ // printing "ready" — if the process is genuinely killed on
310
+ // abort, that write never happens. That is the decisive
311
+ // check; whatever the settled promise looks like is a second,
312
+ // weaker one.
313
+ const marker = 'conformance-abort-marker.txt';
314
+ const caller = new AbortController();
315
+ let signalReady;
316
+ const ready = new Promise((resolve) => {
317
+ signalReady = resolve;
318
+ });
319
+ const running = sandbox.exec('/bin/sh', [
320
+ '-c',
321
+ `trap '' TERM; (trap '' TERM; sleep 0.4; printf late > ${marker}) & echo ready; wait`,
322
+ ], {
323
+ signal: caller.signal,
324
+ onOutput: (chunk) => {
325
+ if (chunk.stream === 'stdout' && chunk.data.includes('ready'))
326
+ signalReady?.();
327
+ },
328
+ });
329
+ await ready;
330
+ caller.abort(new Error('conformance suite cancelled this command'));
331
+ // Resolve OR reject are both compliant — a backend that cannot
332
+ // confirm the kill may refuse instead of reporting a result it
333
+ // is not sure of. What is never compliant is reporting a clean,
334
+ // unaborted-looking success.
335
+ let settled;
336
+ try {
337
+ settled = await running;
338
+ }
339
+ catch {
340
+ settled = undefined;
341
+ }
342
+ if (settled !== undefined) {
343
+ expect(settled.exitCode === 0 && settled.signal === undefined).toBe(false);
344
+ }
345
+ // Long enough that an un-killed process would have finished its
346
+ // sleep and written the file.
347
+ await sleep(900);
348
+ await expectRejects(expect, () => sandbox.readFile(marker));
349
+ }));
350
+ });
351
+ describe('file IO', () => {
352
+ it('round-trips a UTF-8 string through writeFile/readFile', withSandbox(async (sandbox) => {
353
+ await sandbox.writeFile('conformance-notes.txt', 'héllo wörld');
354
+ const read = await sandbox.readFile('conformance-notes.txt');
355
+ expect(read.toString('utf8')).toBe('héllo wörld');
356
+ }));
357
+ it('round-trips arbitrary binary content byte for byte', withSandbox(async (sandbox) => {
358
+ const payload = Buffer.from([0x00, 0xff, 0x10, 0x00, 0x42, 0xfe, 0x7f, 0x80, 0x01]);
359
+ await sandbox.writeFile('nested/conformance/blob.bin', payload);
360
+ const read = await sandbox.readFile('nested/conformance/blob.bin');
361
+ // Compared as base64 rather than through a deep-equality
362
+ // matcher: the four matchers this suite is allowed to assume
363
+ // (`toBe`/`toEqual`/`toBeGreaterThan`/`toMatch`) do not
364
+ // guarantee byte-exact `Buffer` comparison across every
365
+ // runner a caller might wire in, and a corrupted byte belongs
366
+ // in the string this failure prints.
367
+ expect(read.toString('base64')).toBe(payload.toString('base64'));
368
+ }));
369
+ /**
370
+ * A body too large to cross the wire in ONE message.
371
+ *
372
+ * 7 MiB is chosen against a real number rather than a round one:
373
+ * a `write-file` body travels base64-encoded inside the request
374
+ * envelope, so 7 MiB of content is ~9.3 MiB of frame — past the
375
+ * 8 MiB ceiling the guest agent enforces on an unauthenticated
376
+ * connection's first frame, which on a transport that dials
377
+ * fresh per call is EVERY frame. That ceiling used to make this
378
+ * case a documented refusal on the kubernetes backend while the
379
+ * host-local backends served it without noticing, which is
380
+ * exactly the shape of divergence a contract suite exists to
381
+ * catch: `Sandbox.writeFile` promises to write a file, and a
382
+ * caller seeding a repository archive into a workspace cannot
383
+ * be told that the promise holds below a number nothing in the
384
+ * interface names.
385
+ *
386
+ * Compared by digest, not by content: a mismatch here belongs in
387
+ * the failure message as a short string, and 7 MiB of base64
388
+ * does not.
389
+ */
390
+ it('round-trips a body larger than one wire frame', withSandbox(async (sandbox) => {
391
+ const payload = deterministicBytes(7 * 1024 * 1024);
392
+ await sandbox.writeFile('conformance-large/archive.bin', payload);
393
+ const read = await sandbox.readFile('conformance-large/archive.bin');
394
+ expect(read.length).toBe(payload.length);
395
+ expect(digest(read)).toBe(digest(payload));
396
+ }));
397
+ /**
398
+ * A read ABOVE the ceiling the case above sits below.
399
+ *
400
+ * 7 MiB is chosen for what the WRITE costs — 9.3 MiB of base64
401
+ * envelope, past the guest's 8 MiB pre-auth frame limit — and a
402
+ * reply frame is not measured against that limit at all, so that
403
+ * case proves nothing about the read side. 9 MiB is above the
404
+ * number on both sides of the wire, which is the only way to tell
405
+ * a backend that reads a file in bounded pieces from one that
406
+ * hands back a single reply and hopes.
407
+ *
408
+ * Skipped by NAME, and counted in the runner's totals as a case,
409
+ * for a backend that has not declared the capability — see
410
+ * {@link SandboxConformanceOptions.supportsRangedAndStreamedReads}
411
+ * and the note on {@link SANDBOX_CONTRACT_VERSION}.
412
+ */
413
+ it(...rangedReadCase('reads a file larger than one wire frame back in bounded pieces', async (sandbox) => {
414
+ const payload = deterministicBytes(9 * 1024 * 1024);
415
+ await sandbox.writeFile('conformance-large/wide.bin', payload);
416
+ const whole = await sandbox.readFile('conformance-large/wide.bin');
417
+ expect(whole.length).toBe(payload.length);
418
+ expect(digest(whole)).toBe(digest(payload));
419
+ // A backend declaring the capability must expose the stream
420
+ // too: the whole point is that a caller can read a file it
421
+ // could not hold, and `readFile` hands back one buffer.
422
+ const readFileStream = sandbox.readFileStream;
423
+ if (!readFileStream) {
424
+ throw new Error('supportsRangedAndStreamedReads is true but this sandbox has no readFileStream. ' +
425
+ 'A backend that honours offset/length but cannot stream must pass ' +
426
+ 'supportsRangedAndStreamedReads: false and state why.');
427
+ }
428
+ const chunks = [];
429
+ for await (const chunk of readFileStream.call(sandbox, 'conformance-large/wide.bin')) {
430
+ chunks.push(Buffer.from(chunk));
431
+ }
432
+ // More than one chunk is what "bounded pieces" means; a
433
+ // backend yielding the whole file once satisfies the
434
+ // signature and none of the promise.
435
+ expect(chunks.length > 1).toBe(true);
436
+ expect(digest(Buffer.concat(chunks))).toBe(digest(payload));
437
+ }));
438
+ /**
439
+ * A slice, and the three things a slice has to get right: the
440
+ * bytes, a range that runs off the end, and the fact that asking
441
+ * for one must not hand back the whole file.
442
+ */
443
+ it(...rangedReadCase('reads an explicit byte range, and clips it to the end of the file', async (sandbox) => {
444
+ const payload = deterministicBytes(64 * 1024);
445
+ await sandbox.writeFile('conformance-range/slice.bin', payload);
446
+ const middle = await sandbox.readFile('conformance-range/slice.bin', {
447
+ offset: 1_000,
448
+ length: 256,
449
+ });
450
+ expect(middle.length).toBe(256);
451
+ expect(middle.toString('base64')).toBe(payload.subarray(1_000, 1_256).toString('base64'));
452
+ // Past the end returns what exists rather than failing: a
453
+ // caller resuming from a remembered offset cannot be made to
454
+ // know the answer before it asks.
455
+ const straddling = await sandbox.readFile('conformance-range/slice.bin', {
456
+ offset: payload.length - 10,
457
+ length: 500,
458
+ });
459
+ expect(straddling.length).toBe(10);
460
+ expect(straddling.toString('base64')).toBe(payload.subarray(-10).toString('base64'));
461
+ }));
462
+ });
463
+ describe('listFiles', () => {
464
+ it('lists written files as absolute paths with their sizes', withSandbox(async (sandbox) => {
465
+ const contentA = '123456789';
466
+ const contentB = '42 bytes worth of fixed content!!';
467
+ await sandbox.writeFile('conformance-list/a.txt', contentA);
468
+ await sandbox.writeFile('conformance-list/b.txt', contentB);
469
+ const dir = `${sandbox.rootDir}/conformance-list`;
470
+ const files = await sandbox.listFiles(dir);
471
+ const byPath = new Map(files.map((f) => [f.path, f.size]));
472
+ expect(byPath.get(`${dir}/a.txt`)).toBe(Buffer.byteLength(contentA));
473
+ expect(byPath.get(`${dir}/b.txt`)).toBe(Buffer.byteLength(contentB));
474
+ }));
475
+ it('reports a root that does not exist as empty rather than failing', withSandbox(async (sandbox) => {
476
+ const files = await sandbox.listFiles(`${sandbox.rootDir}/conformance-never-created`);
477
+ expect(files.length).toBe(0);
478
+ }));
479
+ });
480
+ /**
481
+ * Optional on {@link Sandbox} by the SDK's own contract: a backend that
482
+ * cannot provide a real pseudo-terminal must OMIT the method rather
483
+ * than hand back a pipe masquerading as one. So a factory whose
484
+ * sandbox has no `openTerminal` is not in violation of anything — the
485
+ * case below passes vacuously for it, which is the documented
486
+ * skip-if-unavailable this suite promises rather than a silent hole:
487
+ * both shipped backends (kubernetes, firecracker) DO implement it, so
488
+ * in CI this case only ever runs vacuously against a fixture that
489
+ * deliberately declines the capability.
490
+ */
491
+ describe('openTerminal', () => {
492
+ it('is owned by the sandbox: destroy() kills and awaits every terminal it returned', withSandbox(async (sandbox) => {
493
+ if (!sandbox.openTerminal)
494
+ return;
495
+ const terminal = await sandbox.openTerminal({
496
+ command: '/bin/sh',
497
+ args: ['-c', 'sleep 30'],
498
+ size: { cols: 80, rows: 24 },
499
+ });
500
+ let exited = false;
501
+ void terminal.exited.then(() => {
502
+ exited = true;
503
+ });
504
+ await sandbox.destroy();
505
+ // Nothing awaited in between: awaiting `terminal.exited` here
506
+ // would rescue a `destroy()` that only fired the kill and
507
+ // returned without waiting for it, which is exactly the
508
+ // defect this case exists to catch.
509
+ expect(exited).toBe(true);
510
+ await terminal.exited;
511
+ }));
512
+ });
513
+ /**
514
+ * Same optionality and the same documented skip as `openTerminal`,
515
+ * above: a factory whose sandbox has no `openTcpConnection` passes
516
+ * vacuously. The positive case below adds a second, independent skip
517
+ * axis on top of that — see `guestCanRunNode` and
518
+ * `guestListenerCommand` on {@link SandboxConformanceOptions} — because
519
+ * proving the forward really crosses into a REMOTE guest needs a
520
+ * listener running there, and not every guest can start one the same
521
+ * way.
522
+ */
523
+ describe('openTcpConnection', () => {
524
+ // The reason for a title, rather than a console message, printing
525
+ // the skip: `ConformanceIt` promises only `(name, body) => unknown`
526
+ // (`contract-suite.mjs`'s own flat recorder has no skip concept
527
+ // either), so the one channel a skip can travel through every
528
+ // runner this suite is ever handed is the case's own name — decided
529
+ // once, here, from options given synchronously to
530
+ // `defineSandboxConformance`, not from anything discovered at run
531
+ // time.
532
+ const positiveCaseTitle = guestCanRunNode
533
+ ? 'forwards a bidirectional stream to a service started inside the guest'
534
+ : 'forwards a bidirectional stream to a service started inside the guest (skipped: guestCanRunNode is false)';
535
+ it(positiveCaseTitle, withSandbox(async (sandbox) => {
536
+ if (!sandbox.openTcpConnection)
537
+ return;
538
+ if (!guestCanRunNode)
539
+ return;
540
+ const openTerminal = sandbox.openTerminal;
541
+ if (!openTerminal) {
542
+ // A backend offering `openTcpConnection` without
543
+ // `openTerminal` has no portable way for this suite to
544
+ // start a guest-side listener — declare the skip
545
+ // explicitly (`guestCanRunNode: false`) rather than
546
+ // leaving the default to discover it here as a failure.
547
+ throw new Error('openTcpConnection conformance: starting a guest-side listener needs openTerminal, ' +
548
+ 'which this sandbox does not implement. Pass guestCanRunNode: false to ' +
549
+ 'defineSandboxConformance to skip this case with a stated reason, or supply ' +
550
+ 'guestListenerCommand for a guest that can run a listener some other way.');
551
+ }
552
+ // Called through `.call(sandbox, …)` rather than passed as
553
+ // a bare reference: `openTerminal` may be an ordinary
554
+ // method relying on `this` (a class-based fixture, for
555
+ // instance), and detaching it from `sandbox` would drop
556
+ // that binding.
557
+ const listener = await startGuestListener((terminalOptions) => openTerminal.call(sandbox, terminalOptions), guestListenerCommand());
558
+ try {
559
+ const connection = await sandbox.openTcpConnection({ port: listener.port });
560
+ let received = '';
561
+ const unsubscribe = connection.onData((chunk) => {
562
+ received += Buffer.from(chunk).toString('utf8');
563
+ });
564
+ connection.write('conformance-hello');
565
+ await connection.closed;
566
+ expect(received).toBe('conformance-reply:conformance-hello');
567
+ unsubscribe();
568
+ }
569
+ finally {
570
+ await listener.stop();
571
+ }
572
+ }));
573
+ it('refuses a non-loopback host', withSandbox(async (sandbox) => {
574
+ if (!sandbox.openTcpConnection)
575
+ return;
576
+ // `SandboxTcpConnectOptions.host` types as loopback-only; the
577
+ // cast is deliberate — this proves the refusal is enforced at
578
+ // RUNTIME, not merely by the type checker a compliant caller
579
+ // could route around with the same cast.
580
+ const nonLoopback = {
581
+ port: 9,
582
+ host: '203.0.113.10',
583
+ };
584
+ await expectRejects(expect, () => sandbox.openTcpConnection?.(nonLoopback) ?? Promise.reject(new Error('unreachable')));
585
+ }));
586
+ });
587
+ describe('destroy', () => {
588
+ it('is idempotent, however many times or however concurrently it is called', withSandbox(async (sandbox) => {
589
+ await Promise.all([sandbox.destroy(), sandbox.destroy()]);
590
+ expect(sandbox.status).toBe('destroyed');
591
+ await expectResolves(expect, () => sandbox.destroy());
592
+ expect(sandbox.status).toBe('destroyed');
593
+ }));
594
+ it('refuses every call once destroyed, rather than admitting one', withSandbox(async (sandbox) => {
595
+ await sandbox.destroy();
596
+ await expectRejects(expect, () => sandbox.exec('/bin/sh', ['-c', 'true']));
597
+ await expectRejects(expect, () => sandbox.writeFile('x.txt', 'x'));
598
+ await expectRejects(expect, () => sandbox.readFile('x.txt'));
599
+ await expectRejects(expect, () => sandbox.listFiles(sandbox.rootDir));
600
+ // `?.()` rather than an `if` guard around the assertion: it is
601
+ // type-correct whether or not the capability exists, and when
602
+ // it does not exist there is nothing to refuse — the
603
+ // documented skip-if-unavailable this suite promises for
604
+ // every optional capability.
605
+ if (sandbox.openTerminal) {
606
+ await expectRejects(expect, () => sandbox.openTerminal?.({ size: { cols: 80, rows: 24 } }) ??
607
+ Promise.reject(new Error('unreachable')));
608
+ }
609
+ if (sandbox.openTcpConnection) {
610
+ await expectRejects(expect, () => sandbox.openTcpConnection?.({ port: 9 }) ??
611
+ Promise.reject(new Error('unreachable')));
612
+ }
613
+ }));
614
+ });
615
+ /**
616
+ * Optional on {@link Sandbox} by the SDK's own contract, and the same
617
+ * documented skip as `openTerminal`: a factory whose sandbox omits
618
+ * `walkFiles` passes every case below vacuously. It is not a small
619
+ * omission to make, though — the SDK's `glob` and `grep` builtins
620
+ * REFUSE a sandbox that has no `walkFiles`, so a host that registers
621
+ * the default builtin set and moves to such a backend loses both
622
+ * tools with no change on its own side.
623
+ *
624
+ * What is asserted here is the contract's own wording: absolute paths,
625
+ * regular files only, symlinks not followed, the bounds honoured by
626
+ * whoever does the walking, and — the one that is easy to get wrong —
627
+ * an exhausted examined-entry budget raising an error carrying
628
+ * `ERR_FILE_WALK_LIMIT` rather than handing back a short list a caller
629
+ * would read as complete.
630
+ */
631
+ describe('walkFiles', () => {
632
+ /**
633
+ * Every path this walk yielded, sorted.
634
+ *
635
+ * `walkFiles` is called through `.call(sandbox, …)` for the same
636
+ * reason `openTerminal` is above: it may be an ordinary method
637
+ * relying on `this`, and detaching it would drop that binding.
638
+ */
639
+ const walkPaths = async (sandbox, root, options) => {
640
+ const walk = sandbox.walkFiles;
641
+ if (!walk)
642
+ throw new Error('unreachable: every case guards on walkFiles first');
643
+ const paths = [];
644
+ for await (const entry of walk.call(sandbox, root, options))
645
+ paths.push(entry.path);
646
+ return paths.sort();
647
+ };
648
+ it('yields written files as absolute paths with their sizes, bounded by maxEntries', withSandbox(async (sandbox) => {
649
+ if (!sandbox.walkFiles)
650
+ return;
651
+ await sandbox.writeFile('conformance-walk/a.txt', '1');
652
+ await sandbox.writeFile('conformance-walk/b.txt', '22');
653
+ await sandbox.writeFile('conformance-walk/c.txt', '333');
654
+ const dir = `${sandbox.rootDir}/conformance-walk`;
655
+ const sizes = new Map();
656
+ const walk = sandbox.walkFiles;
657
+ for await (const entry of walk.call(sandbox, dir, { maxEntries: 10 })) {
658
+ sizes.set(entry.path, entry.size);
659
+ }
660
+ expect([...sizes.keys()].sort()).toEqual([`${dir}/a.txt`, `${dir}/b.txt`, `${dir}/c.txt`]);
661
+ expect(sizes.get(`${dir}/c.txt`)).toBe(3);
662
+ // The bound is on what is EMITTED, so a walk asked for two
663
+ // entries yields two and stops — it does not yield three and
664
+ // leave the caller to discard one.
665
+ expect((await walkPaths(sandbox, dir, { maxEntries: 2 })).length).toBe(2);
666
+ }));
667
+ it('bounds the descent with maxDepth, counting direct children as depth 1', withSandbox(async (sandbox) => {
668
+ if (!sandbox.walkFiles)
669
+ return;
670
+ await sandbox.writeFile('conformance-depth/top.txt', 'top');
671
+ await sandbox.writeFile('conformance-depth/one/mid.txt', 'mid');
672
+ await sandbox.writeFile('conformance-depth/one/two/deep.txt', 'deep');
673
+ const dir = `${sandbox.rootDir}/conformance-depth`;
674
+ expect(await walkPaths(sandbox, dir, { maxEntries: 50, maxDepth: 1 })).toEqual([
675
+ `${dir}/top.txt`,
676
+ ]);
677
+ expect(await walkPaths(sandbox, dir, { maxEntries: 50, maxDepth: 2 })).toEqual([
678
+ `${dir}/one/mid.txt`,
679
+ `${dir}/top.txt`,
680
+ ]);
681
+ }));
682
+ it('keeps hidden names out of a wildcard unless includeHidden is set', withSandbox(async (sandbox) => {
683
+ if (!sandbox.walkFiles)
684
+ return;
685
+ await sandbox.writeFile('conformance-hidden/visible.txt', 'v');
686
+ await sandbox.writeFile('conformance-hidden/.secret.txt', 'h');
687
+ const dir = `${sandbox.rootDir}/conformance-hidden`;
688
+ expect(await walkPaths(sandbox, dir, { maxEntries: 50 })).toEqual([`${dir}/visible.txt`]);
689
+ expect(await walkPaths(sandbox, dir, { maxEntries: 50, includeHidden: true })).toEqual([
690
+ `${dir}/.secret.txt`,
691
+ `${dir}/visible.txt`,
692
+ ]);
693
+ }));
694
+ it('reports a root that does not exist as an empty walk rather than failing', withSandbox(async (sandbox) => {
695
+ if (!sandbox.walkFiles)
696
+ return;
697
+ const paths = await walkPaths(sandbox, `${sandbox.rootDir}/conformance-never-walked`, {
698
+ maxEntries: 10,
699
+ });
700
+ expect(paths.length).toBe(0);
701
+ }));
702
+ it('does not follow symbolic links, to a file or to a directory', withSandbox(async (sandbox) => {
703
+ if (!sandbox.walkFiles)
704
+ return;
705
+ await sandbox.writeFile('conformance-links/real/target.txt', 'target');
706
+ const dir = `${sandbox.rootDir}/conformance-links`;
707
+ const linked = await sandbox.exec('/bin/sh', [
708
+ '-c',
709
+ `cd ${dir} && ln -s real/target.txt link-to-file.txt && ln -s real link-to-dir`,
710
+ ]);
711
+ // Never a silent skip. A runtime discovery cannot travel
712
+ // through this suite's one skip channel — the case's own
713
+ // title, decided synchronously from the options — so a guest
714
+ // that cannot build the fixture says so out loud instead of
715
+ // passing a case that asserted nothing.
716
+ if (linked.exitCode !== 0) {
717
+ throw new Error(`walkFiles conformance: this case builds its fixture with POSIX \`ln -s\`, and the guest's shell answered ${linked.exitCode}: ${linked.stderr.trim()}. A guest image that cannot make a symbolic link is not held to "symlinks are not followed" by asserting nothing — ship \`ln\`, or raise the gap so the suite grows a declared skip rather than a quiet one.`);
718
+ }
719
+ // The real file, once, under its real path. Following the
720
+ // directory link would have reported it again through
721
+ // `link-to-dir/target.txt`, and the file link again as itself.
722
+ expect(await walkPaths(sandbox, dir, { maxEntries: 50 })).toEqual([
723
+ `${dir}/real/target.txt`,
724
+ ]);
725
+ }));
726
+ it('raises ERR_FILE_WALK_LIMIT when the examined-entry budget runs out', withSandbox(async (sandbox) => {
727
+ if (!sandbox.walkFiles)
728
+ return;
729
+ for (let index = 0; index < 12; index += 1) {
730
+ await sandbox.writeFile(`conformance-budget/f${index}.txt`, 'x');
731
+ }
732
+ // An incomplete search is an ERROR carrying a code, never a
733
+ // short list: a caller handed six of twelve files with no
734
+ // signal reads it as "that is all there is".
735
+ let code;
736
+ try {
737
+ await walkPaths(sandbox, `${sandbox.rootDir}/conformance-budget`, {
738
+ maxEntries: 50,
739
+ maxVisitedEntries: 4,
740
+ });
741
+ }
742
+ catch (error) {
743
+ code = error.code;
744
+ }
745
+ expect(code).toBe('ERR_FILE_WALK_LIMIT');
746
+ }));
747
+ it('refuses a walk once the sandbox has been destroyed', withSandbox(async (sandbox) => {
748
+ if (!sandbox.walkFiles)
749
+ return;
750
+ const root = sandbox.rootDir;
751
+ await sandbox.destroy();
752
+ // Consumed, not merely constructed: an async generator runs
753
+ // nothing until its first `next()`, so a case that built the
754
+ // iterator and stopped would pass against a sandbox that
755
+ // admits the walk happily.
756
+ await expectRejects(expect, () => walkPaths(sandbox, root, { maxEntries: 10 }));
757
+ }));
758
+ });
759
+ /**
760
+ * One sandbox, several commands at once.
761
+ *
762
+ * A supervisor and its sub-agents share a sandbox, so this is the
763
+ * ordinary case rather than an exotic one — and nothing in this suite
764
+ * used to exercise it. A backend that serialises executions behind one
765
+ * connection, or that lets two commands' output frames land in each
766
+ * other's result, passes every other case here.
767
+ *
768
+ * Overlap is proved by the commands themselves rather than by a clock:
769
+ * each appends its own mark to a shared file, waits for every other
770
+ * mark to appear, and then prints the whole file back. If the backend
771
+ * really ran them together every command sees every mark; if it ran
772
+ * them one at a time the first one waits out its ceiling and can only
773
+ * ever see its own.
774
+ */
775
+ describe('concurrent exec', () => {
776
+ it('runs several commands at once on one sandbox, with no cross-talk between their results', withSandbox(async (sandbox) => {
777
+ const count = 4;
778
+ await sandbox.writeFile('conformance-concurrent/marks', '');
779
+ const marks = `${sandbox.rootDir}/conformance-concurrent/marks`;
780
+ // A rendezvous rather than a sleep: each command appends its
781
+ // own mark and then WAITS for every other mark to appear
782
+ // before it prints. A backend that really runs them together
783
+ // settles as soon as the slowest one has started — no clock
784
+ // to tune, and nothing that gets tighter on a machine or a
785
+ // cluster where four dials cost more than a fixed pause. A
786
+ // backend that serialises them has the first command wait
787
+ // out the ceiling below and still print only its own mark,
788
+ // which is what the assertions catch.
789
+ const everyMark = Array.from({ length: count }, (_unused, index) => index).join(' ');
790
+ const rendezvous = (index) => [
791
+ `printf '[%s]' '${index}' >> "${marks}"`,
792
+ 'waited=0',
793
+ // 60 × 0.1 s. Only a backend that has already failed
794
+ // the case ever reaches it.
795
+ 'while [ "$waited" -lt 60 ]; do',
796
+ ` all=$(cat "${marks}")`,
797
+ ' seen=1',
798
+ ` for mark in ${everyMark}; do`,
799
+ ' case "$all" in *"[$mark]"*) ;; *) seen=0 ;; esac',
800
+ ' done',
801
+ ' [ "$seen" -eq 1 ] && break',
802
+ ' waited=$((waited + 1))',
803
+ ' sleep 0.1',
804
+ 'done',
805
+ `printf 'own:%s ' '${index}'`,
806
+ `cat "${marks}"`,
807
+ ].join('\n');
808
+ const running = Array.from({ length: count }, (_unused, index) => sandbox.exec('/bin/sh', ['-c', rendezvous(index)]));
809
+ // Attached BEFORE the first assertion, and that ordering is
810
+ // load-bearing: an assertion that threw with four commands
811
+ // still in flight would leave four promises nobody is
812
+ // handling, and a backend that then rejects one of them
813
+ // takes the runner down with an unhandled rejection instead
814
+ // of failing this case.
815
+ const settled = Promise.allSettled(running);
816
+ // Every one of them is in flight right now.
817
+ expect(sandbox.status).toBe('busy');
818
+ const results = [];
819
+ for (const outcome of await settled) {
820
+ if (outcome.status === 'rejected') {
821
+ throw outcome.reason instanceof Error
822
+ ? outcome.reason
823
+ : new Error(String(outcome.reason));
824
+ }
825
+ results.push(outcome.value);
826
+ }
827
+ for (let index = 0; index < count; index += 1) {
828
+ const result = results[index];
829
+ if (!result)
830
+ throw new Error('unreachable: one result per started command');
831
+ expect(result.exitCode).toBe(0);
832
+ // Its OWN identity, on its own result: a backend that
833
+ // mixed two commands' output frames fails here.
834
+ expect(result.stdout).toMatch(new RegExp(`own:${index} `));
835
+ // And every other command's mark, which only holds if
836
+ // they were all admitted before any of them finished.
837
+ for (let other = 0; other < count; other += 1) {
838
+ expect(result.stdout).toMatch(new RegExp(`\\[${other}\\]`));
839
+ }
840
+ }
841
+ expect(sandbox.status).toBe('ready');
842
+ }));
843
+ });
844
+ /**
845
+ * `SandboxExecOptions.timeout` and the `timedOut` flag it sets.
846
+ *
847
+ * `SandboxExecResult.timedOut` is REQUIRED on the contract, so every
848
+ * backend answers it on every result — and until now nothing checked
849
+ * that a backend ever sets it to `true`. A backend that accepts
850
+ * `timeout` and ignores it reports a clean, unaborted-looking success
851
+ * after however long the command felt like taking, which is the same
852
+ * defect class the `AbortSignal` case above exists for and reads the
853
+ * same way to a caller: a result that says the work is done.
854
+ */
855
+ describe('exec timeout', () => {
856
+ it('reports a command that outran its timeout as timedOut, and really terminates it', withSandbox(async (sandbox) => {
857
+ // The same shape as the abort case: the marker file is
858
+ // written a moment after "ready", so it only ever exists if
859
+ // the command was left running past its timeout. `trap ''
860
+ // TERM` on both the shell and the background job makes a
861
+ // polite TERM insufficient, exactly as a real runaway
862
+ // command would.
863
+ const marker = 'conformance-timeout-marker.txt';
864
+ const started = Date.now();
865
+ const result = await sandbox.exec('/bin/sh', [
866
+ '-c',
867
+ `trap '' TERM; (trap '' TERM; sleep 1.5; printf late > ${marker}) & echo ready; wait`,
868
+ ], { timeout: 400 });
869
+ const elapsed = Date.now() - started;
870
+ expect(result.timedOut).toBe(true);
871
+ // Settled on the timeout rather than on the command
872
+ // finishing: the script itself waits 1.5 s, and a generous
873
+ // ceiling still separates the two outcomes.
874
+ expect(elapsed < 10_000).toBe(true);
875
+ // Long enough that a command left running would have written.
876
+ await sleep(1_800);
877
+ await expectRejects(expect, () => sandbox.readFile(marker));
878
+ // And the sandbox is still usable: a timeout is one
879
+ // command's outcome, not the handle's.
880
+ expect(sandbox.status).toBe('ready');
881
+ const after = await sandbox.exec('/bin/sh', ['-c', 'echo conformance-after-timeout']);
882
+ expect(after.exitCode).toBe(0);
883
+ expect(after.stdout).toMatch(/conformance-after-timeout/);
884
+ }));
885
+ it('leaves timedOut false for a command that finishes inside its timeout', withSandbox(async (sandbox) => {
886
+ const result = await sandbox.exec('/bin/sh', ['-c', 'echo conformance-quick'], {
887
+ timeout: 30_000,
888
+ });
889
+ expect(result.timedOut).toBe(false);
890
+ expect(result.exitCode).toBe(0);
891
+ expect(result.stdout).toMatch(/conformance-quick/);
892
+ }));
893
+ });
894
+ });
895
+ }
896
+ //# sourceMappingURL=sandbox-conformance.js.map