@iso4/sandbox 0.5.2 → 0.6.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.
package/README.md CHANGED
@@ -162,6 +162,7 @@ Residency is bounded by memory, not by a count:
162
162
  const sandbox = await createSandbox({
163
163
  memoryMb: 128, // default heap cap per isolate (override per prefix at prepare())
164
164
  memoryBudgetMb: 2048, // RSS mark for the whole runtime process (0 = off)
165
+ hostReserveMb: 128, // container memory held back for this host process
165
166
  })
166
167
  ```
167
168
 
@@ -192,13 +193,64 @@ warm ones — prefix runs then execute on cold one-off isolates — until RSS fa
192
193
  back to 80 % of the mark. `maxConcurrentRuns` caps concurrent runs; this caps
193
194
  memory.
194
195
  The default is derived from the memory available to the process
195
- (container-aware), so most hosts never set it.
196
+ (container-aware), so most hosts never set it: 80 % of the container limit
197
+ minus `hostReserveMb`, which is headroom for this host process to grow into
198
+ (its current usage is already metered) — raise it when the host caches
199
+ heavily, `0` to hand the sandbox the whole limit.
200
+
201
+ Above the budget sits the admission line, and a run that needs a new isolate
202
+ whose heap ceiling would cross it fails with `ERR_CAPACITY_MEMORY` rather than
203
+ risking the container. That refusal is honest, not a bug to route around:
204
+ nothing ran, the telemetry is zero, and a retry a moment later usually
205
+ succeeds. The runtime does not evict warm instances to squeeze the refused
206
+ run in — eviction hands the freed pages to V8's pool, which the _next_
207
+ isolate draws from, so the measured usage the line compares against does not
208
+ move for seconds either way. Instead the budget mark sheds idle warmth
209
+ gradually while the line holds, and V8 returns what it no longer needs to the
210
+ operating system on its own. If refusals are routine rather than occasional,
211
+ the container is genuinely too small for `maxConcurrentRuns × memoryMb` —
212
+ `createSandbox` warns at startup when those two contradict each other.
196
213
 
197
214
  `sandbox.stats()` reports the live picture — active runs, queue depth, warm and
198
215
  idle instance counts, summed idle heap, `budgetBytes` / `rssBytes`, whether the
199
216
  runtime is currently `underPressure`, and per-prefix counts. It answers on a
200
217
  dedicated connection, so it works even when every run slot is busy.
201
218
 
219
+ ## Concurrency, and why shedding is yours
220
+
221
+ How many runs execute at once is the runtime's decision, not a constant. It
222
+ derives the number from the shape of the runs it is serving —
223
+ `5 × cores × wall^0.7 ÷ cpu^1.2` over the uncontended minimum wall and CPU
224
+ time of each prefix, recomputed every 32 completions — so a prefix that
225
+ waits 200 ms on an upstream call is granted thousands of slots while one
226
+ that burns a core for 3 ms is granted a handful. Callers beyond the current
227
+ number queue FIFO, `stats()` reports it as `slotLimit`, and a run that had
228
+ to wait carries `queueWaitMs` on its result.
229
+
230
+ ```ts
231
+ const sandbox = await createSandbox({
232
+ maxConcurrentRuns: 64, // pins the number — derivation is off entirely
233
+ maxQueuedRuns: 10_000, // waiters behind it; past this, ERR_QUEUE_FULL
234
+ })
235
+ ```
236
+
237
+ That number is about the sandbox, not about your process. For wait-heavy
238
+ work it grows into the thousands, and every one of those runs is also
239
+ promises, frames and host handlers on **your** Node event loop — the same
240
+ loop serving your own requests. Measured on an 8-core pod against runs that
241
+ wait 250 ms on a host call: ~8k concurrent runs sustain ~28k runs/s at ~43 ms
242
+ event-loop delay, while ~12k push that delay to ~286 ms and throughput _down_
243
+ to ~22k/s. Zero errors at either level — nothing fails, the process just gets
244
+ slow, your own request handling included.
245
+
246
+ Neither side refuses on that. The runtime grants without enforcing and never
247
+ looks at your event loop, so the ceiling is yours to impose: keep your own
248
+ in-flight bound upstream of `execute()` and reject or defer past it —
249
+ `perf_hooks.monitorEventLoopDelay()` is the signal to set it by — or pin
250
+ `maxConcurrentRuns` to a number you have measured this host at. A pin is a
251
+ fixed number, not a cap on the derived one: it opts out of derivation for
252
+ every workload the sandbox serves.
253
+
202
254
  ## Async context (`AsyncLocalStorage`)
203
255
 
204
256
  Run/postfix code can import a minimal, Node-compatible `AsyncLocalStorage` to
@@ -255,6 +307,39 @@ still reads cleanly. `sandbox.readExports({ code })` wraps that for the
255
307
  deploy path — load once, read the declaration exports, and get the skipped
256
308
  handler names back.
257
309
 
310
+ ### Batch event streams
311
+
312
+ Arguments cross as one blob per call, so a handler that takes an array of
313
+ events and returns an array of results pays one crossing per batch instead
314
+ of one per event. For event-shaped work this is the biggest throughput
315
+ lever available:
316
+
317
+ ```ts
318
+ export default {
319
+ transform(events) {
320
+ return events.map((event) => ({ id: event.eventId, bucket: event.type }))
321
+ },
322
+ }
323
+ ```
324
+
325
+ ```ts
326
+ const result = await prefix.call({
327
+ export: 'default.transform',
328
+ args: [events], // one array, not one call per event
329
+ })
330
+ ```
331
+
332
+ Measured on a warm prefix over an 8-slot pool with ~750 B analytics events
333
+ (`bench/warm.bench.ts`, "batched calls"): ~98k events/sec one at a time,
334
+ ~319k at 8 per call, ~365k at 32. That is 3.6× at the peak, and most of it
335
+ is already there at 8.
336
+
337
+ Two things bound it. One call runs on one slot, so a single batch of 128
338
+ comes out _slower_ than four batches of 32 running in parallel — size
339
+ batches so several are in flight across the pool. And a batch shares one
340
+ run's limits: `cpuTimeMs`, `wallTimeMs` and `memoryMb` cover the whole
341
+ array, so an oversized batch turns a per-event cost into a per-run timeout.
342
+
258
343
  ## Result shape
259
344
 
260
345
  ```ts
@@ -325,8 +410,9 @@ Thrown errors keep their identity across the bridge, in both directions:
325
410
  ## Architecture
326
411
 
327
412
  V8 runs in a separate Rust subprocess communicating over a Unix domain socket.
328
- A slot pool admits up to `maxConcurrentRuns` runs at once (the rest queue
329
- FIFO — an `AbortSignal`, e.g. `AbortSignal.timeout()`, bounds the wait);
413
+ A slot pool admits as many runs at once as the runtime currently grants (the
414
+ rest queue FIFO — an `AbortSignal`, e.g. `AbortSignal.timeout()`, bounds the
415
+ wait);
330
416
  connections to the subprocess open on demand and are reused, and `stats()`
331
417
  reports the live count as `openConnections`. Five concurrent
332
418
  `prefix.execute()` calls each get their own run slot and execute in
package/dist/index.d.mts CHANGED
@@ -80,8 +80,11 @@ interface OneOffResourceLimits extends ResourceLimits {
80
80
  }
81
81
  interface ResourceLimits {
82
82
  /**
83
- * Maximum *active* execution time in milliseconds. Time spent waiting on
84
- * host bridge calls (globals, host imports) is excluded.
83
+ * Maximum CPU time in milliseconds — what the run's own thread actually
84
+ * burns on a core. Time waiting on host bridge calls (globals, host
85
+ * imports) is excluded, and so is time the thread spends descheduled while
86
+ * co-resident runs use the cores: a run gets its full allowance however
87
+ * busy the host is, and `wallTimeMs` bounds how long that may take.
85
88
  * @default 5_000
86
89
  */
87
90
  cpuTimeMs?: number;
@@ -444,54 +447,40 @@ type RebindImports<M extends Record<string, ImportValue>> = Record<string, Impor
444
447
  type RebindHostModule<T> = T extends HostExportFunction ? T : T extends HostModuleObject ? { [K in keyof T as T[K] extends HostExportFunction ? K : T[K] extends HostModuleObject ? K : never]?: T[K] extends HostExportFunction ? T[K] : T[K] extends HostModuleObject ? RebindHostModule<T[K]> : never } : never;
445
448
  interface SandboxOptions {
446
449
  /**
447
- * Maximum number of runs executing at once. Additional callers queue FIFO
448
- * until a run finishes; a queued caller's `AbortSignal` is honoured while
449
- * it waits, so `AbortSignal.timeout()` composes as a queue-wait bound —
450
- * there is no separate timeout option.
450
+ * Pin how many runs execute at once, overriding the number the runtime
451
+ * derives for itself. Callers past it queue FIFO, honouring their
452
+ * `AbortSignal` while they wait (`AbortSignal.timeout()` composes as a
453
+ * queue-wait bound — there is no separate timeout option).
451
454
  *
452
- * This is an admission number, not a socket count: connections to the
453
- * runtime process open on demand as runs need them and are reused for the
454
- * process lifetime (`SandboxStats.openConnections` reports the live
455
- * count). Multiple MCP agents / concurrent callers run in parallel up to
456
- * this limit.
455
+ * **Leave this unset unless you have measured this workload on this
456
+ * hardware.** By default the runtime sizes concurrency from the shape of
457
+ * the runs it is serving and follows that shape as it changes; a fixed
458
+ * number cannot. Set it when you need a hard ceiling — to leave cores to
459
+ * the host app, or because you know the workload better than a
460
+ * measurement of it would.
457
461
  *
458
- * Overridable in both directions: lowering it leaves cores to the host
459
- * app; raising it above the core count pays only for workloads that spend
460
- * their time suspended on host calls rather than computing.
461
- *
462
- * This caps *concurrent runs* only. How many isolates stay resident
463
- * (warm instances included) is the memory budget's job — see
464
- * `memoryBudgetMb`. There is no instance-count cap of any kind, so
465
- * idle warm instances may outnumber the running count here, or fall below
466
- * it under memory pressure.
462
+ * An admission number, not a socket count and not an isolate count: the
463
+ * runs spread over a variable number of shared isolates, and co-resident
464
+ * runs share that isolate's `memoryMb` heap cap between them.
467
465
  *
468
466
  * Must be an integer ≥ 1 — anything else throws at `createSandbox()`
469
467
  * (`0` would queue every run forever).
470
- *
471
- * Defaults to `os.availableParallelism()`, bounded by memory: when that
472
- * many worst-case heaps (`memoryMb` each) would not fit inside the
473
- * memory budget, the default becomes `budget / memoryMb` instead (at
474
- * least 1) — the cores default must not promise more concurrent heaps
475
- * than the container can hold. With `memoryMb: 0` or `memoryBudgetMb: 0`
476
- * there is nothing to bound with and the default stays the core count.
477
468
  */
478
469
  maxConcurrentRuns?: number;
479
470
  /**
480
- * How many callers may wait for a run slot before new ones are shed.
481
- * Past the bound, a run fails immediately with `ERR_QUEUE_FULL` instead
482
- * of joining the queue: every queued caller holds memory (its serialized
483
- * arguments included), so an unbounded queue turns sustained overload
484
- * into a host out-of-memory crash. A hammered sandbox should fail some
485
- * requests cleanly and keep answering the rest.
486
- *
487
- * `0` is valid: no queue at all — every run past `maxConcurrentRuns`
488
- * fails immediately. Must be an integer ≥ 0.
471
+ * How many callers may wait for a run slot before new ones are shed with
472
+ * `ERR_QUEUE_FULL`. Every queued caller holds its serialized arguments,
473
+ * so an unbounded queue turns sustained overload into a host
474
+ * out-of-memory crash.
489
475
  *
490
- * This bounds queue *depth*; the wait *time* of an individual queued
491
- * caller is still bounded only by its own `AbortSignal`
492
- * (`AbortSignal.timeout()` composes — there is no timeout knob).
476
+ * A fixed bound, deliberately not a multiple of the concurrency: that
477
+ * number now moves with the workload, and a shed threshold moving with it
478
+ * would tighten exactly when load rises.
493
479
  *
494
- * Defaults to `100 × maxConcurrentRuns`.
480
+ * `0` is valid: no queue at all. Must be an integer ≥ 0. Bounds queue
481
+ * depth* only — a queued caller's wait *time* is bounded by its own
482
+ * `AbortSignal`.
483
+ * @default 10_000
495
484
  */
496
485
  maxQueuedRuns?: number;
497
486
  /**
@@ -532,7 +521,7 @@ interface SandboxOptions {
532
521
  * cgroup's working set, Node host included, the number the container's
533
522
  * OOM killer acts on (where no cgroup exists, e.g. macOS, it falls back
534
523
  * to the runtime child's own RSS). At/above the mark it evicts idle warm
535
- * instances by `heapUsed × idleTime` score (highest first) AND stops
524
+ * instances by `heapUsed × idleTime^1.2` score (highest first) AND stops
536
525
  * pooling new instances — prefix runs without an idle instance execute
537
526
  * on cold one-off isolates — until usage falls back to 80 % of the mark
538
527
  * (hysteresis, so eviction doesn't flap). Reusing an already-warm
@@ -543,8 +532,9 @@ interface SandboxOptions {
543
532
  *
544
533
  * Above the budget sits one more, non-configurable line: the runtime
545
534
  * never CREATES an isolate when measured usage plus the run's own
546
- * `memoryMb` would cross 90 % of the container limit (minus a 256 MB
547
- * host reserve) — such a run fails with `ERR_CAPACITY` instead, so the
535
+ * `memoryMb` would cross 90 % of the container limit (minus the
536
+ * `hostReserveMb` reserve, 128 MB by default) — such a run fails with
537
+ * `ERR_CAPACITY_MEMORY` instead, so the
548
538
  * newest admission can never be what tips the container into an OOM
549
539
  * kill. Runs with `memoryMb: 0` (uncapped) are refused already from the
550
540
  * budget mark — their worst case has no arithmetic.
@@ -553,8 +543,8 @@ interface SandboxOptions {
553
543
  * `dispose()`, and uncapped runs are never refused). Independent of
554
544
  * `memoryMb`: usage is measured, not derived from per-isolate caps.
555
545
  *
556
- * Default: 80 % of what remains of the container limit after a 256 MB
557
- * reserve for the Node host — container/cgroup-aware via
546
+ * Default: 80 % of what remains of the container limit after the
547
+ * `hostReserveMb` reserve (128 MB) — container/cgroup-aware via
558
548
  * `process.constrainedMemory()`, falling back to `os.totalmem()`.
559
549
  * Services with a large host-side footprint should set this lower.
560
550
  * On a host too small for that subtraction the default floors at 64 MB
@@ -567,6 +557,23 @@ interface SandboxOptions {
567
557
  */
568
558
  memoryBudgetMb?: number;
569
559
  /**
560
+ * Megabytes of the container limit reserved for the host process before
561
+ * either capacity line is drawn — the default budget is 80 % of what
562
+ * remains after it, and the runtime's admission line 90 %.
563
+ *
564
+ * It is headroom for the host's own GROWTH, not its current usage: the
565
+ * runtime meters global container memory, so whatever Node holds right
566
+ * now is already counted. Raise it when the host caches heavily (a
567
+ * request-driven cache, parsed specs, a large in-memory index) — the
568
+ * reserve is what keeps that growth from colliding with an admission the
569
+ * runtime already granted. Lower it for a thin host that does little but
570
+ * drive the sandbox; `0` gives the sandbox the whole limit.
571
+ *
572
+ * Must be an integer ≥ 0.
573
+ * @default 128
574
+ */
575
+ hostReserveMb?: number;
576
+ /**
570
577
  * Override the path to the Rust V8 binary.
571
578
  * Default: auto-detect from \@iso4/v8-* platform packages.
572
579
  */
@@ -592,6 +599,11 @@ interface SandboxStats {
592
599
  */
593
600
  queueDepth: number;
594
601
  /**
602
+ * Runs admitted concurrently right now. Follows the runtime's own figure
603
+ * as the workload changes, unless `maxConcurrentRuns` pinned it.
604
+ */
605
+ slotLimit: number;
606
+ /**
595
607
  * Host-side count of runtime connections as the pool tracks them (the
596
608
  * dedicated `stats()` control connection not included). Runs are
597
609
  * multiplexed onto shared connections — several concurrent runs per
@@ -615,7 +627,9 @@ interface SandboxStats {
615
627
  idleInstances: number;
616
628
  /**
617
629
  * Summed heap of the idle instances in bytes, each measured after its
618
- * last call (a busy instance's current heap is unknown mid-call).
630
+ * last call — or, where the runtime's idle settle is switched on, after
631
+ * the collection a parked instance runs, which is the smaller and truer
632
+ * number (a busy instance's current heap is unknown mid-call).
619
633
  */
620
634
  idleHeapBytes: number;
621
635
  /**
@@ -640,7 +654,7 @@ interface SandboxStats {
640
654
  /**
641
655
  * The isolate admission line in bytes: 90 % of the container limit minus
642
656
  * the host reserve. A run needing a new isolate whose `memoryMb` would
643
- * not fit under it fails with `ERR_CAPACITY`. 0 = no container limit
657
+ * not fit under it fails with `ERR_CAPACITY_MEMORY`. 0 = no container limit
644
658
  * readable, line disabled.
645
659
  */
646
660
  hardLineBytes: number;
@@ -1111,9 +1125,16 @@ interface CallSuccess {
1111
1125
  */
1112
1126
  wallTimeMs: number;
1113
1127
  /**
1114
- * Active V8 execution only; bridge waits excluded (itemized in `bridgeCalls`).
1128
+ * CPU burned on the run's own thread; bridge waits excluded (itemized in
1129
+ * `bridgeCalls`), as is time spent descheduled under contention — so this
1130
+ * does not grow with how many runs share the host. V8's background threads
1131
+ * (GC, compilation) are not attributable to a run and are not included.
1115
1132
  */
1116
1133
  cpuTimeMs: number;
1134
+ /**
1135
+ * See {@link RunSuccess.queueWaitMs}.
1136
+ */
1137
+ queueWaitMs?: number;
1117
1138
  bridgeCalls: BridgeCallEntry[];
1118
1139
  /**
1119
1140
  * `used_heap_size` of the isolate that served this call, measured after
@@ -1201,7 +1222,7 @@ interface WaitUntilResult {
1201
1222
  */
1202
1223
  wallTimeMs: number;
1203
1224
  /**
1204
- * Active V8 execution time during the grace phase, ms.
1225
+ * CPU burned on the instance thread during the grace phase, ms.
1205
1226
  */
1206
1227
  cpuTimeMs: number;
1207
1228
  /**
@@ -1278,11 +1299,24 @@ interface RunSuccess {
1278
1299
  */
1279
1300
  wallTimeMs: number;
1280
1301
  /**
1281
- * Active V8 execution time — time spent waiting on host bridge calls is
1282
- * excluded. Milliseconds with microsecond resolution.
1302
+ * CPU burned on the run's own thread — time waiting on host bridge calls,
1303
+ * and time descheduled under contention, are excluded. Milliseconds with
1304
+ * microsecond resolution.
1283
1305
  */
1284
1306
  cpuTimeMs: number;
1285
1307
  /**
1308
+ * How long this run waited on the host for a free run slot
1309
+ * (`maxConcurrentRuns`), before its frame was sent. Absent when a slot was
1310
+ * free and the run went straight out. Milliseconds with microsecond
1311
+ * resolution.
1312
+ *
1313
+ * The wait sits outside the other three clocks, which the runtime measures
1314
+ * from dispatch onwards — end to end, a caller sees this plus
1315
+ * {@link durationMs} plus frame transit. Rising `queueWaitMs` is the sign
1316
+ * that admission, not the code, is the bottleneck.
1317
+ */
1318
+ queueWaitMs?: number;
1319
+ /**
1286
1320
  * One entry per bridge call the sandbox attempted, in attempt order —
1287
1321
  * including attempts blocked by limits ({@link BridgeCallEntry.blocked}).
1288
1322
  * Recorded by the Rust runtime.
@@ -1316,6 +1350,11 @@ interface RunFailure {
1316
1350
  */
1317
1351
  wallTimeMs: number;
1318
1352
  cpuTimeMs: number;
1353
+ /**
1354
+ * See {@link RunSuccess.queueWaitMs}. Absent on a run that failed before
1355
+ * admission — `ERR_QUEUE_FULL` is refused at the bound without waiting.
1356
+ */
1357
+ queueWaitMs?: number;
1319
1358
  bridgeCalls: BridgeCallEntry[];
1320
1359
  /**
1321
1360
  * `used_heap_size` of the isolate that served this run, measured after the
@@ -1401,7 +1440,7 @@ interface RunError {
1401
1440
  * `RunError.resetCause`.
1402
1441
  */
1403
1442
  type ResetCause = "cpu" | "memory" | "wall" | "abort" | "internal";
1404
- type RunErrorCode = "ERR_USER_CODE" | "ERR_MEMORY_LIMIT" | "ERR_CPU_TIMEOUT" | "ERR_WALL_TIMEOUT" | "ERR_ABORTED" | "ERR_MODULE_NOT_FOUND" | "ERR_COMPILE" | "ERR_FUNCTION_ARGUMENT_NOT_SUPPORTED" | "ERR_EXPORT_NOT_SERIALIZABLE" | "ERR_TYPE_NOT_SERIALIZABLE" | "ERR_EXPORT_TOO_LARGE" | "ERR_CALL_TARGET_NOT_FOUND" | "ERR_HOST_BRIDGE" | "ERR_BRIDGE_PAYLOAD_TOO_LARGE" | "ERR_BRIDGE_CALL_LIMIT_EXCEEDED" | "ERR_INSTANCE_RESET" | "ERR_CAPACITY" | "ERR_QUEUE_FULL" | "ERR_UNDECLARED_BINDING" | "ERR_RESERVED_NAME" | "ERR_FROZEN_BINDING" | "ERR_INVALID_REBIND" | "ERR_PREFIX_DID_NOT_SETTLE" | "ERR_PREFIX_BRIDGE_CALL" | "ERR_WARMUP_LIMIT" | "ERR_PREFIX_DISPOSED" | "ERR_PROTOCOL_DESYNC" | "ERR_INTERNAL";
1443
+ type RunErrorCode = "ERR_USER_CODE" | "ERR_MEMORY_LIMIT" | "ERR_CPU_TIMEOUT" | "ERR_WALL_TIMEOUT" | "ERR_ABORTED" | "ERR_MODULE_NOT_FOUND" | "ERR_COMPILE" | "ERR_FUNCTION_ARGUMENT_NOT_SUPPORTED" | "ERR_EXPORT_NOT_SERIALIZABLE" | "ERR_TYPE_NOT_SERIALIZABLE" | "ERR_EXPORT_TOO_LARGE" | "ERR_CALL_TARGET_NOT_FOUND" | "ERR_HOST_BRIDGE" | "ERR_BRIDGE_PAYLOAD_TOO_LARGE" | "ERR_BRIDGE_CALL_LIMIT_EXCEEDED" | "ERR_INSTANCE_RESET" | "ERR_CAPACITY_MEMORY" | "ERR_QUEUE_FULL" | "ERR_UNDECLARED_BINDING" | "ERR_RESERVED_NAME" | "ERR_FROZEN_BINDING" | "ERR_INVALID_REBIND" | "ERR_PREFIX_DID_NOT_SETTLE" | "ERR_PREFIX_BRIDGE_CALL" | "ERR_WARMUP_LIMIT" | "ERR_PREFIX_DISPOSED" | "ERR_PROTOCOL_DESYNC" | "ERR_INTERNAL";
1405
1444
  //#endregion
1406
1445
  //#region src/index.d.ts
1407
1446
  declare function createSandbox(options?: SandboxOptions): Promise<Sandbox>;
package/dist/index.mjs CHANGED
@@ -1515,8 +1515,8 @@ function encodeStreamCancelPayload(runId, streamId, reason) {
1515
1515
  * @param payload the raw Result frame payload
1516
1516
  */
1517
1517
  function peekRunCompletionBackgroundFlags(payload) {
1518
- if (payload.byteLength < 7) return 0;
1519
- return payload[4] === 1 ? payload[payload.byteLength - 2] : 0;
1518
+ if (payload.byteLength < 11) return 0;
1519
+ return payload[8] === 1 ? payload[payload.byteLength - 2] : 0;
1520
1520
  }
1521
1521
  /**
1522
1522
  * Read just the `runId` off a `Result` frame payload, without decoding the rest.
@@ -1535,9 +1535,19 @@ function peekRunCompletionRunId(buf) {
1535
1535
  if (buf.byteLength < 4) return void 0;
1536
1536
  return (buf[0] << 24 | buf[1] << 16 | buf[2] << 8 | buf[3]) >>> 0;
1537
1537
  }
1538
+ /**
1539
+ * Read just the runtime's concurrency allowance, the second field. Applied
1540
+ * on every completion, so it must not decode the rest. `0` = no opinion.
1541
+ * @param buf
1542
+ */
1543
+ function peekRunCompletionSlotAllowance(buf) {
1544
+ if (buf.byteLength < 8) return 0;
1545
+ return (buf[4] << 24 | buf[5] << 16 | buf[6] << 8 | buf[7]) >>> 0;
1546
+ }
1538
1547
  function decodeRunCompletionPayload(buf, resultKind) {
1539
1548
  const reader = new PayloadReader(buf);
1540
1549
  const runId = reader.readU32();
1550
+ const slotAllowance = reader.readU32();
1541
1551
  if (reader.readBool()) {
1542
1552
  if (reader.readU8() !== 1) throw new PayloadDecodeError("expected success present byte = 1 when ok = true");
1543
1553
  const valueRaw = reader.readValueBlob();
@@ -1554,6 +1564,7 @@ function decodeRunCompletionPayload(buf, resultKind) {
1554
1564
  reader.assertDone();
1555
1565
  if (resultKind === "call") return {
1556
1566
  runId,
1567
+ slotAllowance,
1557
1568
  backgroundFlags,
1558
1569
  result: {
1559
1570
  status: "completed",
@@ -1570,6 +1581,7 @@ function decodeRunCompletionPayload(buf, resultKind) {
1570
1581
  };
1571
1582
  return {
1572
1583
  runId,
1584
+ slotAllowance,
1573
1585
  backgroundFlags,
1574
1586
  result: {
1575
1587
  status: "completed",
@@ -1604,6 +1616,7 @@ function decodeRunCompletionPayload(buf, resultKind) {
1604
1616
  reader.assertDone();
1605
1617
  return {
1606
1618
  runId,
1619
+ slotAllowance,
1607
1620
  backgroundFlags: 0,
1608
1621
  result: {
1609
1622
  status: "failed",
@@ -2131,16 +2144,29 @@ var RuntimeIpcClient = class RuntimeIpcClient {
2131
2144
  */
2132
2145
  runs = /* @__PURE__ */ new Map();
2133
2146
  /**
2134
- * Everything routed on this connection that a connection-level failure
2135
- * would take down: runs (executing AND grace-phase — an entry lives until
2136
- * its final frame) plus in-flight control requests. The pool's
2137
- * per-connection cap reads this, so the blast-radius bound covers all of
2138
- * it. Both counts move synchronously from the call that adds them
2139
- * (`runRawCode`/`prefixRun`/`precompile`), which keeps the pool's
2140
- * same-tick load observation exact.
2147
+ * How many of {@link runs} are in their `waitUntil` grace phase. A counter
2148
+ * rather than a scan so {@link load} stays O(1).
2149
+ */
2150
+ graceRuns = 0;
2151
+ /**
2152
+ * What the pool's per-connection cap bounds: foreground runs plus in-flight
2153
+ * control requests. Grace-phase runs are deliberately excluded — counting
2154
+ * an epilogue for its whole grace wall opens fresh connections (2 runtime
2155
+ * threads each) for traffic that rides an existing one, and their frames
2156
+ * are mux-routed by run id anyway. The counts move synchronously from the
2157
+ * call that adds them (`runRawCode`/`prefixRun`/`precompile`), which keeps
2158
+ * the pool's same-tick load observation exact.
2141
2159
  */
2142
2160
  get load() {
2143
- return this.runs.size + this.precompileWaiters.size + this.controlWaiters.length;
2161
+ return this.runs.size - this.graceRuns + this.precompileWaiters.size + this.controlWaiters.length;
2162
+ }
2163
+ /**
2164
+ * Nothing is routed here at all — grace phases included — and nothing is
2165
+ * left in the socket's write buffer. The pool reaps only quiescent
2166
+ * connections, so closing one never drops a frame already written.
2167
+ */
2168
+ get quiescent() {
2169
+ return this.load === 0 && this.graceRuns === 0 && this.socket.writableLength === 0;
2144
2170
  }
2145
2171
  /**
2146
2172
  * Pending `stats()` requests, FIFO — sound because the runtime answers
@@ -2159,6 +2185,10 @@ var RuntimeIpcClient = class RuntimeIpcClient {
2159
2185
  * Session brand key for host-type descriptors written on this connection.
2160
2186
  */
2161
2187
  brandKey;
2188
+ /**
2189
+ * Set by {@link connect} — see `RuntimeIpcClientOptions.onSlotAllowance`.
2190
+ */
2191
+ onSlotAllowance;
2162
2192
  constructor(socket, brandKey) {
2163
2193
  this.socket = socket;
2164
2194
  this.brandKey = brandKey;
@@ -2207,9 +2237,10 @@ var RuntimeIpcClient = class RuntimeIpcClient {
2207
2237
  */
2208
2238
  static async connect(options) {
2209
2239
  const client = new RuntimeIpcClient(await connectSocket(options.socketPath), brandKeyForToken(options.descriptorToken));
2240
+ client.onSlotAllowance = options.onSlotAllowance;
2210
2241
  try {
2211
2242
  await client.write(encodeTsToRustFrame(TsToRustMessageTypes.Authenticate, encodeAuthenticatePayload({
2212
- protocolVersion: 2,
2243
+ protocolVersion: 1,
2213
2244
  probe: serializationProbe(),
2214
2245
  descriptorToken: options.descriptorToken
2215
2246
  })));
@@ -2523,6 +2554,7 @@ var RuntimeIpcClient = class RuntimeIpcClient {
2523
2554
  else entry.reject(failure);
2524
2555
  }
2525
2556
  this.runs.clear();
2557
+ this.graceRuns = 0;
2526
2558
  for (const waiter of this.controlWaiters.splice(0)) waiter.reject(failure);
2527
2559
  for (const [, waiter] of this.precompileWaiters) waiter.reject(failure);
2528
2560
  this.precompileWaiters.clear();
@@ -2611,6 +2643,7 @@ var RuntimeIpcClient = class RuntimeIpcClient {
2611
2643
  * @param payload
2612
2644
  */
2613
2645
  routeResult(payload) {
2646
+ this.onSlotAllowance?.(peekRunCompletionSlotAllowance(payload));
2614
2647
  const runId = peekRunCompletionRunId(payload);
2615
2648
  const entry = runId === void 0 ? void 0 : this.runs.get(runId);
2616
2649
  if (runId === void 0 || entry === void 0 || entry.epilogue !== void 0) throw new ProtocolDesyncError(`Result frame carries runId ${runId ?? "(truncated payload)"} but no run with that id is awaiting a Result on this connection — the runtime is answering a run this client does not know`);
@@ -2632,6 +2665,7 @@ var RuntimeIpcClient = class RuntimeIpcClient {
2632
2665
  settleEpilogue = resolve;
2633
2666
  });
2634
2667
  entry.epilogue = settleEpilogue;
2668
+ this.graceRuns++;
2635
2669
  const signal = entry.signal;
2636
2670
  const hardAbortSignal = entry.hardAbortSignal;
2637
2671
  const cancelGrace = (hard) => () => {
@@ -2668,6 +2702,7 @@ var RuntimeIpcClient = class RuntimeIpcClient {
2668
2702
  const entry = this.runs.get(report.runId);
2669
2703
  if (entry === void 0 || entry.epilogue === void 0) throw new ProtocolDesyncError(`RunComplete frame carries runId ${report.runId} but no run with that id is in its waitUntil grace phase on this connection`);
2670
2704
  this.runs.delete(report.runId);
2705
+ this.graceRuns--;
2671
2706
  entry.detachAbort();
2672
2707
  entry.streams?.releaseAll();
2673
2708
  entry.outStreams.failAll(/* @__PURE__ */ new Error("[@iso4/sandbox] the run completed before its body stream terminated"));
@@ -2862,6 +2897,10 @@ function connectSocket(socketPath) {
2862
2897
  });
2863
2898
  }
2864
2899
  /**
2900
+ * How often idleness is sampled — the reap granularity on top of the TTL.
2901
+ */
2902
+ const IDLE_SWEEP_MS = 5e3;
2903
+ /**
2865
2904
  * The waiter queue is at `maxQueuedRuns`: the run is shed as a failed
2866
2905
  * result with `error.code: 'ERR_QUEUE_FULL'` instead of growing an
2867
2906
  * unbounded, memory-holding queue.
@@ -2887,6 +2926,29 @@ var SlotPool = class {
2887
2926
  this.maxQueued = maxQueued;
2888
2927
  }
2889
2928
  /**
2929
+ * Runs admitted concurrently right now — `stats()` reports this as
2930
+ * `slotLimit`.
2931
+ */
2932
+ get limit() {
2933
+ return this.capacity;
2934
+ }
2935
+ /**
2936
+ * Take the runtime's current allowance. Growing admits queued callers
2937
+ * immediately; shrinking never interrupts a run — `active` walks down to
2938
+ * the new figure as runs finish (see {@link release}).
2939
+ * @param capacity the new admission number
2940
+ */
2941
+ setCapacity(capacity) {
2942
+ if (this.disposed || capacity === this.capacity || capacity < 1) return;
2943
+ this.capacity = capacity;
2944
+ while (this.active < this.capacity) {
2945
+ const next = this.waiters.shift();
2946
+ if (next === void 0) return;
2947
+ this.active++;
2948
+ next.resolve();
2949
+ }
2950
+ }
2951
+ /**
2890
2952
  * Callers currently queued for a slot — `stats()` reports this as
2891
2953
  * `queueDepth`.
2892
2954
  */
@@ -2894,7 +2956,9 @@ var SlotPool = class {
2894
2956
  return this.waiters.length;
2895
2957
  }
2896
2958
  /**
2897
- * Take a slot, or queue FIFO until one frees.
2959
+ * Take a slot, or queue FIFO until one frees. Resolves with the wait in
2960
+ * milliseconds, or `undefined` when the slot was free — the immediate
2961
+ * path never reads a clock.
2898
2962
  * @param signal
2899
2963
  * The caller's abort signal, honoured *while queued*. Per-run
2900
2964
  * `wallTimeMs` / `cpuTimeMs` cannot bound that wait: the caller is
@@ -2912,12 +2976,14 @@ var SlotPool = class {
2912
2976
  if (hardAbortSignal?.aborted) return Promise.reject(new RunAbortedError(hardAbortSignal.reason));
2913
2977
  if (this.active < this.capacity) {
2914
2978
  this.active++;
2915
- return Promise.resolve();
2979
+ return Promise.resolve(void 0);
2916
2980
  }
2917
2981
  if (this.waiters.length >= this.maxQueued) return Promise.reject(new QueueFullError(`run queue is full (${this.waiters.length} queued behind ${this.capacity} executing runs, maxQueuedRuns: ${this.maxQueued}); the sandbox is overloaded — retry later, or raise maxQueuedRuns`));
2982
+ const queuedAt = performance.now();
2918
2983
  return new Promise((resolve, reject) => {
2984
+ const admit = () => resolve(performance.now() - queuedAt);
2919
2985
  const waiter = {
2920
- resolve,
2986
+ resolve: admit,
2921
2987
  reject
2922
2988
  };
2923
2989
  if (signal === void 0 && hardAbortSignal === void 0) {
@@ -2939,7 +3005,7 @@ var SlotPool = class {
2939
3005
  };
2940
3006
  waiter.resolve = () => {
2941
3007
  settle();
2942
- resolve();
3008
+ admit();
2943
3009
  };
2944
3010
  waiter.reject = (error) => {
2945
3011
  settle();
@@ -2951,12 +3017,18 @@ var SlotPool = class {
2951
3017
  /**
2952
3018
  * Free a slot. The longest-queued caller takes it directly; only when
2953
3019
  * nobody waits does the active count drop.
3020
+ *
3021
+ * Above capacity — the allowance shrank under runs already executing —
3022
+ * the slot is never handed on: `active` has to walk down to the new
3023
+ * figure, and passing it to a waiter would hold it there forever.
2954
3024
  */
2955
3025
  release() {
2956
- const next = this.waiters.shift();
2957
- if (next !== void 0) {
2958
- next.resolve();
2959
- return;
3026
+ if (this.active <= this.capacity) {
3027
+ const next = this.waiters.shift();
3028
+ if (next !== void 0) {
3029
+ next.resolve();
3030
+ return;
3031
+ }
2960
3032
  }
2961
3033
  this.active--;
2962
3034
  }
@@ -2980,11 +3052,19 @@ var ConnectionRegistry = class {
2980
3052
  * registry's ledger, not a per-read socket probe.
2981
3053
  */
2982
3054
  connections = [];
3055
+ sweepTimer;
2983
3056
  /**
2984
3057
  * Connects in flight — counted in the ledger so a burst of opens is
2985
3058
  * visible, not a blind spot.
2986
3059
  */
2987
3060
  opening = 0;
3061
+ /**
3062
+ * Callers parked on the opens in flight, each holding a claim on a place
3063
+ * of the connection that settles first. Settled with `undefined` when that
3064
+ * open failed, which sends the caller back to {@link openOrWait}'s
3065
+ * decision.
3066
+ */
3067
+ waiters = [];
2988
3068
  connect;
2989
3069
  disposed = false;
2990
3070
  constructor(connect) {
@@ -3007,43 +3087,103 @@ var ConnectionRegistry = class {
3007
3087
  tryAcquire() {
3008
3088
  if (this.disposed) throw new Error("runtime is disposed");
3009
3089
  for (let i = 0; i < this.connections.length; i++) {
3010
- const client = this.connections[i];
3011
- if (!client.usable) {
3012
- client.dispose().catch(() => {});
3090
+ const entry = this.connections[i];
3091
+ if (!entry.client.usable) {
3092
+ entry.client.dispose().catch(() => {});
3013
3093
  this.connections.splice(i, 1);
3014
3094
  i--;
3015
3095
  continue;
3016
3096
  }
3017
- if (client.load < 4) return client;
3097
+ if (entry.client.load < 4) {
3098
+ entry.busyAt = Date.now();
3099
+ return entry.client;
3100
+ }
3101
+ }
3102
+ }
3103
+ /**
3104
+ * Close connections that have carried nothing for {@link
3105
+ * IDLE_CONNECTION_TTL_MS}, newest first (first-fit packs onto the oldest),
3106
+ * keeping one. The sweep only runs while there is a surplus to reap.
3107
+ */
3108
+ sweep() {
3109
+ const now = Date.now();
3110
+ for (let i = this.connections.length - 1; i >= 0 && this.connections.length > 1; i--) {
3111
+ const entry = this.connections[i];
3112
+ if (!entry.client.quiescent) {
3113
+ entry.busyAt = now;
3114
+ continue;
3115
+ }
3116
+ if (now - entry.busyAt < 3e4) continue;
3117
+ this.connections.splice(i, 1);
3118
+ entry.client.dispose().catch(() => {});
3018
3119
  }
3120
+ if (this.connections.length <= 1) this.stopSweep();
3121
+ }
3122
+ startSweep() {
3123
+ if (this.sweepTimer !== void 0 || this.connections.length <= 1) return;
3124
+ this.sweepTimer = setInterval(() => this.sweep(), IDLE_SWEEP_MS);
3125
+ this.sweepTimer.unref?.();
3126
+ }
3127
+ stopSweep() {
3128
+ if (this.sweepTimer === void 0) return;
3129
+ clearInterval(this.sweepTimer);
3130
+ this.sweepTimer = void 0;
3019
3131
  }
3020
3132
  /**
3021
- * Open a fresh connection and add it to the shared set. Concurrent
3022
- * callers that all found the set full each open one — a cold burst can
3023
- * briefly open more connections than the steady-state packing needs;
3024
- * they are kept and reused, so the count follows demand from then on. A
3025
- * failed connect fails this caller's run; the registry never shrinks
3026
- * silently.
3133
+ * A place on a connection for a caller {@link tryAcquire} turned away:
3134
+ * open one, or wait for an open already in flight when it still has room.
3135
+ *
3136
+ * A fresh connection seats {@link RUNS_PER_CONNECTION} runs, one of them
3137
+ * the caller that opened it, so the opens in flight promise
3138
+ * `opening * (RUNS_PER_CONNECTION - 1)` places to waiters. Deciding and
3139
+ * taking a place are synchronous with `opening++`, so callers arriving in
3140
+ * one tick see each other's claims: a burst of N opens ceil(N / cap)
3141
+ * connections rather than N. Single-flighting them onto one connection
3142
+ * instead would be wrong — it cannot seat them.
3143
+ */
3144
+ async openOrWait() {
3145
+ for (;;) {
3146
+ if (this.disposed) throw new Error("runtime is disposed");
3147
+ if (this.opening * 3 - this.waiters.length < 1) return this.open();
3148
+ const client = await new Promise((resolve) => {
3149
+ this.waiters.push(resolve);
3150
+ });
3151
+ if (client !== void 0) return client;
3152
+ }
3153
+ }
3154
+ /**
3155
+ * Open a fresh connection and add it to the shared set, seating the
3156
+ * waiters that claimed a place on it. A failed connect fails this caller's
3157
+ * run, leaves the ledger untouched and sends its waiters back to decide.
3027
3158
  */
3028
3159
  async open() {
3029
3160
  if (this.disposed) throw new Error("runtime is disposed");
3030
3161
  this.opening++;
3162
+ let opened;
3031
3163
  try {
3032
3164
  const client = await this.connect();
3033
3165
  if (this.disposed) {
3034
3166
  client.dispose().catch(() => {});
3035
3167
  throw new Error("runtime is disposed");
3036
3168
  }
3037
- this.connections.push(client);
3169
+ this.connections.push({
3170
+ client,
3171
+ busyAt: Date.now()
3172
+ });
3173
+ this.startSweep();
3174
+ opened = client;
3038
3175
  return client;
3039
3176
  } finally {
3040
3177
  this.opening--;
3178
+ for (const settle of this.waiters.splice(0, 3)) settle(opened);
3041
3179
  }
3042
3180
  }
3043
3181
  async dispose() {
3044
3182
  if (this.disposed) return;
3045
3183
  this.disposed = true;
3046
- await Promise.all(this.connections.splice(0).map((client) => client.dispose()));
3184
+ this.stopSweep();
3185
+ for (const settle of this.waiters.splice(0)) settle(void 0);
3186
+ await Promise.all(this.connections.splice(0).map(({ client }) => client.dispose()));
3047
3187
  }
3048
3188
  };
3049
3189
  /**
@@ -3060,31 +3200,43 @@ var RunPool = class {
3060
3200
  get queueDepth() {
3061
3201
  return this.slots.queueDepth;
3062
3202
  }
3203
+ get slotLimit() {
3204
+ return this.slots.limit;
3205
+ }
3063
3206
  get openConnections() {
3064
3207
  return this.connections.openConnections;
3065
3208
  }
3066
3209
  /**
3210
+ * Adopt the runtime's concurrency allowance. Ignored by `createSandbox`
3211
+ * when `maxConcurrentRuns` pinned the number.
3212
+ * @param allowance runs the runtime grants; `0` = no opinion yet
3213
+ */
3214
+ setSlotLimit(allowance) {
3215
+ if (allowance > 0) this.slots.setCapacity(allowance);
3216
+ }
3217
+ /**
3067
3218
  * Take a run slot (queueing FIFO when `maxConcurrentRuns` are executing),
3068
3219
  * pick a shared connection, run `fn`, then release the slot when `fn`
3069
3220
  * settles — which is at the run's Result. A run that ended with pending
3070
3221
  * `waitUntil` work holds no slot during its grace phase: the grace frames
3071
3222
  * ride the shared connection, routed by run id, until its RunComplete.
3072
- * @param fn ran with the shared connection
3223
+ * @param fn ran with the shared connection and how long the slot was
3224
+ * waited for — `undefined` when one was free
3073
3225
  * @param signal the caller's abort signal, honoured while queued
3074
3226
  * @param hardAbortSignal the caller's hard-abort signal — while queued it
3075
3227
  * dequeues exactly like `signal`
3076
3228
  */
3077
3229
  async withClient(fn, signal, hardAbortSignal) {
3078
- await this.slots.acquire(signal, hardAbortSignal);
3230
+ const queueWaitMs = await this.slots.acquire(signal, hardAbortSignal);
3079
3231
  let client;
3080
3232
  try {
3081
- client = this.connections.tryAcquire() ?? await this.connections.open();
3233
+ client = this.connections.tryAcquire() ?? await this.connections.openOrWait();
3082
3234
  } catch (error) {
3083
3235
  this.slots.release();
3084
3236
  throw error;
3085
3237
  }
3086
3238
  try {
3087
- return await fn(client);
3239
+ return await fn(client, queueWaitMs);
3088
3240
  } finally {
3089
3241
  this.slots.release();
3090
3242
  }
@@ -3265,14 +3417,25 @@ function extractBridgeGlobals(runGlobals, precompileGlobals) {
3265
3417
  * Spawns the Rust V8 subprocess, admits runs through a slot pool over
3266
3418
  * lazily opened UDS connections, and exposes the `Sandbox` + `Prefix` API.
3267
3419
  */
3420
+ /**
3421
+ * Default queue bound. Fixed rather than a multiple of the concurrency,
3422
+ * which now moves with the workload: a threshold that moved with it would
3423
+ * tighten exactly when load rises. Sits above the ~8 k concurrent runs one
3424
+ * host process was measured to sustain, so it bounds memory without
3425
+ * shedding work the sandbox could still have taken.
3426
+ */
3427
+ const DEFAULT_MAX_QUEUED_RUNS = 1e4;
3268
3428
  async function createSandbox(options) {
3269
3429
  if (options !== void 0 && "maxIsolates" in options) throw new TypeError("[@iso4/sandbox] maxIsolates was removed: capacity admits runs, not connections — set maxConcurrentRuns instead (same default: os.availableParallelism())");
3270
3430
  const binaryPath = resolveRuntimeBinary(options);
3271
3431
  validateMemoryMb(options?.memoryMb, "memoryMb");
3272
- const warmBudgetBytes = resolveWarmBudgetBytes(options?.memoryBudgetMb);
3273
- const maxConcurrentRuns = options?.maxConcurrentRuns ?? defaultMaxConcurrentRuns(warmBudgetBytes, options?.memoryMb);
3432
+ const hostReserveMb = resolveHostReserveMb(options?.hostReserveMb);
3433
+ const warmBudgetBytes = resolveWarmBudgetBytes(options?.memoryBudgetMb, hostReserveMb);
3434
+ const pinnedConcurrency = options?.maxConcurrentRuns;
3435
+ const maxConcurrentRuns = pinnedConcurrency ?? availableParallelism();
3274
3436
  if (!Number.isInteger(maxConcurrentRuns) || maxConcurrentRuns < 1) throw new TypeError("[@iso4/sandbox] maxConcurrentRuns must be an integer >= 1");
3275
- const maxQueuedRuns = options?.maxQueuedRuns ?? 100 * maxConcurrentRuns;
3437
+ if (pinnedConcurrency !== void 0) warnIfSlotsOutrunMemory(maxConcurrentRuns, options?.memoryMb, warmBudgetBytes, hostReserveMb);
3438
+ const maxQueuedRuns = options?.maxQueuedRuns ?? DEFAULT_MAX_QUEUED_RUNS;
3276
3439
  if (!Number.isInteger(maxQueuedRuns) || maxQueuedRuns < 0) throw new TypeError("[@iso4/sandbox] maxQueuedRuns must be an integer >= 0");
3277
3440
  const socketDir = await mkdtemp(join(tmpdir(), "iso4-v8-"));
3278
3441
  const socketPath = join(socketDir, "runtime.sock");
@@ -3282,7 +3445,9 @@ async function createSandbox(options) {
3282
3445
  "--socket",
3283
3446
  socketPath,
3284
3447
  "--warm-budget-bytes",
3285
- String(warmBudgetBytes)
3448
+ String(warmBudgetBytes),
3449
+ "--host-reserve-bytes",
3450
+ String(hostReserveMb * 1024 * 1024)
3286
3451
  ], { stdio: [
3287
3452
  "ignore",
3288
3453
  "ignore",
@@ -3293,11 +3458,15 @@ async function createSandbox(options) {
3293
3458
  });
3294
3459
  try {
3295
3460
  await waitForSocket(socketPath, proc);
3461
+ let pool;
3296
3462
  const connect = () => RuntimeIpcClient.connect({
3297
3463
  socketPath,
3298
- descriptorToken
3464
+ descriptorToken,
3465
+ onSlotAllowance: pinnedConcurrency === void 0 ? (allowance) => pool.setSlotLimit(allowance) : void 0
3299
3466
  });
3300
- return new SandboxImpl(proc, new RunPool(maxConcurrentRuns, maxQueuedRuns, connect), await connect(), socketPath, brandKey, options?.memoryMb);
3467
+ pool = new RunPool(maxConcurrentRuns, maxQueuedRuns, connect);
3468
+ const statsClient = await connect();
3469
+ return new SandboxImpl(proc, pool, statsClient, socketPath, brandKey, options?.memoryMb);
3301
3470
  } catch (error) {
3302
3471
  proc.kill();
3303
3472
  await rm(socketDir, {
@@ -3315,19 +3484,30 @@ async function createSandbox(options) {
3315
3484
  * @param memoryBudgetMb the explicit budget knob (`0` opts out of
3316
3485
  * watermarks entirely, like celld's `CELLD_MAX_RSS_MB=0`), or undefined
3317
3486
  * for the container-aware default
3487
+ * @param hostReserveMb what the default subtracts from the container limit
3318
3488
  */
3319
- function resolveWarmBudgetBytes(memoryBudgetMb) {
3489
+ function resolveWarmBudgetBytes(memoryBudgetMb, hostReserveMb) {
3320
3490
  if (memoryBudgetMb !== void 0 && !Number.isFinite(memoryBudgetMb)) throw new TypeError("[@iso4/sandbox] memoryBudgetMb must be a finite number of megabytes");
3321
- const budgetMb = memoryBudgetMb ?? defaultMemoryBudgetMb();
3491
+ const budgetMb = memoryBudgetMb ?? defaultMemoryBudgetMb(hostReserveMb);
3322
3492
  return Math.min(Math.max(0, Math.floor(budgetMb * 1024 * 1024)), Number.MAX_SAFE_INTEGER);
3323
3493
  }
3324
3494
  /**
3325
- * The Node-host reserve subtracted from the container limit before any
3495
+ * Default Node-host reserve subtracted from the container limit before any
3326
3496
  * capacity line is drawn. Mirrors the runtime's `container.rs`
3327
- * `NODE_RESERVE_BYTES` — change both together. A measured reserve replaces
3328
- * this constant later (#165).
3497
+ * `DEFAULT_HOST_RESERVE_BYTES` — change both together. Sized for a typical
3498
+ * Node host (~80 MB measured) with margin; `hostReserveMb` tunes it.
3329
3499
  */
3330
- const NODE_RESERVE_MB = 256;
3500
+ const DEFAULT_HOST_RESERVE_MB = 128;
3501
+ /**
3502
+ * The host reserve both capacity lines are drawn from: the runtime gets it
3503
+ * on the command line, the default budget below subtracts the same number.
3504
+ * @param hostReserveMb the explicit knob, or undefined for the default
3505
+ */
3506
+ function resolveHostReserveMb(hostReserveMb) {
3507
+ if (hostReserveMb === void 0) return DEFAULT_HOST_RESERVE_MB;
3508
+ if (!Number.isInteger(hostReserveMb) || hostReserveMb < 0) throw new TypeError("[@iso4/sandbox] hostReserveMb must be an integer >= 0 (megabytes; 0 = no reserve)");
3509
+ return Math.min(hostReserveMb, Math.floor(Number.MAX_SAFE_INTEGER / (1024 * 1024)));
3510
+ }
3331
3511
  /**
3332
3512
  * Default memory budget (the 80% shedding mark): 80% of what remains of the
3333
3513
  * container limit after the Node-host reserve — container/cgroup-aware via
@@ -3343,34 +3523,59 @@ const NODE_RESERVE_MB = 256;
3343
3523
  * (`memoryBudgetMb: 0` stays the only deliberate opt-out). The floor makes
3344
3524
  * such a host shed warmth aggressively instead — degraded, never
3345
3525
  * unprotected — and says so on stderr.
3526
+ * @param hostReserveMb the reserve both lines are drawn from
3346
3527
  */
3347
- function defaultMemoryBudgetMb() {
3348
- const constrained = process.constrainedMemory?.() || Number.POSITIVE_INFINITY;
3349
- const totalMb = Math.min(constrained, totalmem()) / (1024 * 1024);
3350
- const budgetMb = Math.floor((totalMb - NODE_RESERVE_MB) * .8);
3528
+ function defaultMemoryBudgetMb(hostReserveMb) {
3529
+ const totalMb = containerLimitMb();
3530
+ const budgetMb = Math.floor((totalMb - hostReserveMb) * .8);
3351
3531
  if (budgetMb < 64) {
3352
- process.stderr.write(`[@iso4/sandbox] host memory (${Math.floor(totalMb)} MB) leaves no room for a warm budget after the ${NODE_RESERVE_MB} MB host reserve — flooring the budget at 64 MB (expect aggressive eviction); set memoryBudgetMb explicitly to tune or 0 to disable\n`);
3532
+ process.stderr.write(`[@iso4/sandbox] host memory (${Math.floor(totalMb)} MB) leaves no room for a warm budget after the ${hostReserveMb} MB host reserve — flooring the budget at 64 MB (expect aggressive eviction); set memoryBudgetMb explicitly to tune or 0 to disable\n`);
3353
3533
  return 64;
3354
3534
  }
3355
3535
  return budgetMb;
3356
3536
  }
3357
3537
  /**
3358
- * Default `maxConcurrentRuns`: the core count, unless that many worst-case
3359
- * heaps could not fit inside the memory budget — then the budget bounds it
3360
- * (`min(cores, budget / ceiling)`, at least 1). The worst case is each
3361
- * isolate's terminating ceiling (`memoryMb` plus its headroom band), not the
3362
- * advertised number. With an uncapped heap (`memoryMb: 0`) or a disabled
3363
- * budget there is nothing to bound with, so the default stays the core
3364
- * count.
3365
- * @param warmBudgetBytes
3538
+ * The container limit in megabytes, as the runtime reads it.
3539
+ * `constrainedMemory()` reports 0/undefined when there is no cgroup limit —
3540
+ * except on cgroup v1, where "unlimited" is a sentinel near 2^63 (seen on
3541
+ * GitHub Actions runners). Take the smaller of it and the host total instead
3542
+ * of trusting either alone: a real container limit is below the host total,
3543
+ * and the sentinel is above it.
3544
+ */
3545
+ function containerLimitMb() {
3546
+ const constrained = process.constrainedMemory?.() || Number.POSITIVE_INFINITY;
3547
+ return Math.min(constrained, totalmem()) / (1024 * 1024);
3548
+ }
3549
+ /**
3550
+ * The memory one run may reach, in megabytes — what capacity planning has to
3551
+ * reserve for a slot. The worst case is a prefix instance's TERMINATING line,
3552
+ * band included; a one-off's is the bare cap. An unset `memoryMb` reaches the
3553
+ * child as 128 (the runtime's `ipc.rs` `DEFAULT_MEMORY_MB`). `0` = uncapped,
3554
+ * which has no arithmetic.
3366
3555
  * @param memoryMb
3367
3556
  */
3368
- function defaultMaxConcurrentRuns(warmBudgetBytes, memoryMb) {
3369
- const cores = availableParallelism();
3370
- const capMb = hardCeilingMb(memoryMb) ?? 128 + heapBandMb(128);
3371
- if (capMb <= 0 || warmBudgetBytes <= 0) return cores;
3372
- const fitting = Math.floor(warmBudgetBytes / (capMb * 1024 * 1024));
3373
- return Math.max(1, Math.min(cores, fitting));
3557
+ function runCeilingMb(memoryMb) {
3558
+ return hardCeilingMb(memoryMb) ?? 128 + heapBandMb(128);
3559
+ }
3560
+ /**
3561
+ * Explicit knobs that promise more concurrent heap than this container can
3562
+ * hold (#144). Warns, never throws: the ceiling is a worst case, and a
3563
+ * workload whose runs stay well under it may never feel this.
3564
+ * @param maxConcurrentRuns the explicit slot count
3565
+ * @param memoryMb
3566
+ * @param warmBudgetBytes
3567
+ * @param hostReserveMb
3568
+ */
3569
+ function warnIfSlotsOutrunMemory(maxConcurrentRuns, memoryMb, warmBudgetBytes, hostReserveMb) {
3570
+ const ceilingMb = runCeilingMb(memoryMb);
3571
+ const budgetMb = Math.floor(warmBudgetBytes / (1024 * 1024));
3572
+ if (ceilingMb <= 0 || budgetMb <= 0) return;
3573
+ const wantMb = maxConcurrentRuns * ceilingMb;
3574
+ if (wantMb <= budgetMb) return;
3575
+ const lineMb = Math.floor((containerLimitMb() - hostReserveMb) * .9);
3576
+ let consequence = `over the ${budgetMb} MB memory budget — warm instances are evicted to hold the mark; lower maxConcurrentRuns or memoryMb, or raise memoryBudgetMb`;
3577
+ if (wantMb > lineMb) consequence = `over the runtime's ${lineMb} MB admission line — runs that need a new isolate fail with ERR_CAPACITY_MEMORY; lower maxConcurrentRuns or memoryMb`;
3578
+ process.stderr.write(`[@iso4/sandbox] maxConcurrentRuns ${maxConcurrentRuns} × a ${ceilingMb} MB heap ceiling = ${wantMb} MB, ${consequence}\n`);
3374
3579
  }
3375
3580
  async function waitForSocket(socketPath, proc, timeoutMs = 5e3) {
3376
3581
  const deadline = Date.now() + timeoutMs;
@@ -3495,7 +3700,7 @@ function heapCapsForWire(value) {
3495
3700
  /**
3496
3701
  * The failed result for a run shed at the host-side queue bound
3497
3702
  * (`maxQueuedRuns`). Nothing reached the runtime, so telemetry is genuinely
3498
- * zero. Distinct from `ERR_CAPACITY` (the runtime's memory admission):
3703
+ * zero. Distinct from `ERR_CAPACITY_MEMORY` (the runtime's memory admission):
3499
3704
  * this wall is queue depth, that one is memory.
3500
3705
  * @param error the pool's refusal, carrying the bound in its message
3501
3706
  */
@@ -3516,6 +3721,16 @@ function queueFullResult(error) {
3516
3721
  bridgeCalls: []
3517
3722
  };
3518
3723
  }
3724
+ /**
3725
+ * Stamp what the run waited for its slot onto its result. Absent when it
3726
+ * never queued; an aborted run reports no time of its own either.
3727
+ * @param result the run's outcome
3728
+ * @param queueWaitMs the wait the pool measured
3729
+ */
3730
+ function withQueueWait(result, queueWaitMs) {
3731
+ if (queueWaitMs !== void 0 && result.status !== "aborted") result.queueWaitMs = queueWaitMs;
3732
+ return result;
3733
+ }
3519
3734
  function desyncResult(error) {
3520
3735
  return {
3521
3736
  status: "failed",
@@ -3619,7 +3834,7 @@ var SandboxImpl = class {
3619
3834
  argsBlob: await serializeHostValue(options.call.args ?? [], this.brandKey, streams)
3620
3835
  };
3621
3836
  try {
3622
- return await this.pool.withClient(async (client) => {
3837
+ return await this.pool.withClient(async (client, queueWaitMs) => {
3623
3838
  const raw = await client.runRawCode(options.code, {
3624
3839
  filename: options.filename,
3625
3840
  limits: {
@@ -3641,7 +3856,7 @@ var SandboxImpl = class {
3641
3856
  if (options.signal?.aborted) return abortedResult(options.signal.reason, decoded);
3642
3857
  if (options.hardAbortSignal?.aborted) return abortedResult(options.hardAbortSignal.reason, decoded);
3643
3858
  }
3644
- return decoded;
3859
+ return withQueueWait(decoded, queueWaitMs);
3645
3860
  }, options.signal, options.hardAbortSignal);
3646
3861
  } catch (error) {
3647
3862
  streams.releaseAll();
@@ -3659,6 +3874,7 @@ var SandboxImpl = class {
3659
3874
  const raw = await this.statsClient.stats();
3660
3875
  return {
3661
3876
  activeRuns: raw.oneoffRunning + raw.warmRuns,
3877
+ slotLimit: this.pool.slotLimit,
3662
3878
  queueDepth: this.pool.queueDepth,
3663
3879
  openConnections: this.pool.openConnections,
3664
3880
  warmInstances: raw.warmBusy + raw.warmIdle,
@@ -3888,7 +4104,7 @@ var PrefixImpl = class {
3888
4104
  }
3889
4105
  const streams = payload.streams ?? new StreamSourceRegistry();
3890
4106
  try {
3891
- return await this.pool.withClient(async (client) => {
4107
+ return await this.pool.withClient(async (client, queueWaitMs) => {
3892
4108
  const raw = await client.prefixRun({
3893
4109
  prefixId: this.id,
3894
4110
  code: payload.code,
@@ -3912,7 +4128,7 @@ var PrefixImpl = class {
3912
4128
  if (options.signal?.aborted) return abortedResult(options.signal.reason, decoded);
3913
4129
  if (options.hardAbortSignal?.aborted) return abortedResult(options.hardAbortSignal.reason, decoded);
3914
4130
  }
3915
- return decoded;
4131
+ return withQueueWait(decoded, queueWaitMs);
3916
4132
  }, options.signal, options.hardAbortSignal);
3917
4133
  } catch (error) {
3918
4134
  streams.releaseAll();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@iso4/sandbox",
3
- "version": "0.5.2",
3
+ "version": "0.6.0",
4
4
  "type": "module",
5
5
  "description": "Fast, sandboxed V8 isolate runtime for agent-generated JavaScript. Two-process architecture for crash isolation.",
6
6
  "keywords": [
@@ -49,10 +49,10 @@
49
49
  "vitest": "^4.1.5"
50
50
  },
51
51
  "optionalDependencies": {
52
- "@iso4/v8-darwin-arm64": "^0.5.2",
53
- "@iso4/v8-darwin-x64": "^0.5.2",
54
- "@iso4/v8-linux-arm64-gnu": "^0.5.2",
55
- "@iso4/v8-linux-x64-gnu": "^0.5.2"
52
+ "@iso4/v8-darwin-arm64": "^0.6.0",
53
+ "@iso4/v8-darwin-x64": "^0.6.0",
54
+ "@iso4/v8-linux-arm64-gnu": "^0.6.0",
55
+ "@iso4/v8-linux-x64-gnu": "^0.6.0"
56
56
  },
57
57
  "engines": {
58
58
  "node": ">=24.0.0"