eutaxy 0.15.1 → 0.16.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 (34) hide show
  1. package/README.md +6 -6
  2. package/dist/aws.d.mts +2 -2
  3. package/dist/aws.d.mts.map +1 -1
  4. package/dist/aws.mjs +53 -79
  5. package/dist/aws.mjs.map +1 -1
  6. package/dist/bin.mjs +1 -1
  7. package/dist/{cli-DT4lxaPK.mjs → cli-DbLlYHTY.mjs} +180 -162
  8. package/dist/cli-DbLlYHTY.mjs.map +1 -0
  9. package/dist/cli.mjs +1 -1
  10. package/dist/cloudflare.d.mts +7 -7
  11. package/dist/cloudflare.d.mts.map +1 -1
  12. package/dist/cloudflare.mjs +2 -2
  13. package/dist/delivery-invariants-90c5xBcd.mjs +44 -0
  14. package/dist/delivery-invariants-90c5xBcd.mjs.map +1 -0
  15. package/dist/{delivery-invariants-DzMy3iPs.d.mts → delivery-invariants-B8ZZnCZg.d.mts} +2 -2
  16. package/dist/{delivery-invariants-DzMy3iPs.d.mts.map → delivery-invariants-B8ZZnCZg.d.mts.map} +1 -1
  17. package/dist/{explore-B52m-wmk.d.mts → explore-DlwIUowm.d.mts} +2 -2
  18. package/dist/{explore-B52m-wmk.d.mts.map → explore-DlwIUowm.d.mts.map} +1 -1
  19. package/dist/index.d.mts +2 -2
  20. package/dist/index.mjs +2 -2
  21. package/dist/{platform-Ba1Kvdza.d.mts → platform-DPJTjpSr.d.mts} +56 -4
  22. package/dist/{platform-Ba1Kvdza.d.mts.map → platform-DPJTjpSr.d.mts.map} +1 -1
  23. package/dist/{src-CPuihHZh.mjs → src-CmHdPsZy.mjs} +1089 -159
  24. package/dist/src-CmHdPsZy.mjs.map +1 -0
  25. package/dist/{src-wa0JZa-T.mjs → src-Dz9Wn2vL.mjs} +2 -2
  26. package/dist/{src-wa0JZa-T.mjs.map → src-Dz9Wn2vL.mjs.map} +1 -1
  27. package/dist/{workerd-DvhVDnQW.mjs → workerd-D9cUGjYv.mjs} +561 -480
  28. package/dist/workerd-D9cUGjYv.mjs.map +1 -0
  29. package/package.json +1 -1
  30. package/dist/cli-DT4lxaPK.mjs.map +0 -1
  31. package/dist/delivery-invariants-Dr658H1W.mjs +0 -67
  32. package/dist/delivery-invariants-Dr658H1W.mjs.map +0 -1
  33. package/dist/src-CPuihHZh.mjs.map +0 -1
  34. package/dist/workerd-DvhVDnQW.mjs.map +0 -1
@@ -29,6 +29,39 @@ function canonicalJson(value) {
29
29
  default: throw new TypeError(`not JSON data: ${typeof value}`);
30
30
  }
31
31
  }
32
+ // packages/core/src/delivery.ts
33
+ /** The invocation one attempt of an event runs as: `<event>#<attempt>`, so a schedule's faults stay keyed when other events are removed. */
34
+ function invocationOf(event) {
35
+ return `${event.id}#${event.attempt}`;
36
+ }
37
+ /**
38
+ * The pending event to deliver next, as the engine and the raw sides pick
39
+ * it: the earliest by `at` (an event without one is due now), and the first
40
+ * queued among equals. The index into `pending`. Pure.
41
+ */
42
+ function earliestEvent(pending) {
43
+ let best = 0;
44
+ for (let i = 1; i < pending.length; i++) if ((pending[i]?.at ?? 0) < (pending[best]?.at ?? 0)) best = i;
45
+ return best;
46
+ }
47
+ /**
48
+ * The next attempt of an event that was not handled (a message not
49
+ * acknowledged or deleted, a request its caller resends, an alarm that
50
+ * failed), or null when it is dropped (dead-lettered, given up on). It is
51
+ * delivered again while both the platform's own limit on redeliveries
52
+ * (Queues' `max_retries`, the caller's `retries`, SQS's `maxReceiveCount`
53
+ * less the first delivery, an alarm's six retries) and the scenario's
54
+ * `maxRedeliveries` leave room; the redeliveries so far are `attempt - 1`.
55
+ * Pure.
56
+ */
57
+ function redelivery(event, limit, bounds) {
58
+ const redeliveries = event.attempt - 1;
59
+ if (redeliveries >= limit || redeliveries >= bounds.maxRedeliveries) return null;
60
+ return {
61
+ ...event,
62
+ attempt: event.attempt + 1
63
+ };
64
+ }
32
65
  // packages/core/src/selectors.ts
33
66
  /** Picking effect records out of the log, and reading paths out of their payloads. */
34
67
  const partsOf = (path) => path === "" ? [] : path.split(".");
@@ -359,14 +392,18 @@ function snapshotSeq(log, target) {
359
392
  const last = findSnapshot(log, target);
360
393
  return last === void 0 ? [] : [last.seq];
361
394
  }
362
- function checkEveryRow(log, inv) {
363
- const rows = queryRows(log, inv.query);
364
- if (rows === void 0) return {
365
- invariant: inv.name,
366
- message: `no snapshot of ${inv.query.target} was recorded`,
395
+ /** The violation a state invariant reports when the target it reads was never snapshotted. */
396
+ function noSnapshot(invariant, target) {
397
+ return {
398
+ invariant,
399
+ message: `no snapshot of ${target} was recorded`,
367
400
  keys: [],
368
401
  evidence: []
369
402
  };
403
+ }
404
+ function checkEveryRow(log, inv) {
405
+ const rows = queryRows(log, inv.query);
406
+ if (rows === void 0) return noSnapshot(inv.name, inv.query.target);
370
407
  const failing = rows.filter((r) => !inv.holds.every((c) => rowMatches(r, c)));
371
408
  if (failing.length === 0) return null;
372
409
  const keys = failing.map((r) => canonicalJson(r));
@@ -380,12 +417,7 @@ function checkEveryRow(log, inv) {
380
417
  }
381
418
  function checkUnique(log, inv) {
382
419
  const rows = queryRows(log, inv.query);
383
- if (rows === void 0) return {
384
- invariant: inv.name,
385
- message: `no snapshot of ${inv.query.target} was recorded`,
386
- keys: [],
387
- evidence: []
388
- };
420
+ if (rows === void 0) return noSnapshot(inv.name, inv.query.target);
389
421
  const counts = /* @__PURE__ */ new Map();
390
422
  for (const r of rows) {
391
423
  const v = getPath(r, inv.path);
@@ -405,42 +437,32 @@ function checkUnique(log, inv) {
405
437
  }
406
438
  function checkImplies(log, inv) {
407
439
  const rows = queryRows(log, inv.state);
408
- if (rows === void 0) return {
409
- invariant: inv.name,
410
- message: `no snapshot of ${inv.state.target} was recorded`,
411
- keys: [],
412
- evidence: []
413
- };
440
+ if (rows === void 0) return noSnapshot(inv.name, inv.state.target);
414
441
  const present = /* @__PURE__ */ new Set();
415
442
  for (const r of rows) {
416
443
  const v = r[inv.column];
417
444
  if (v !== void 0) present.add(canonicalJson(v));
418
445
  }
419
- const missing = [];
446
+ const missing = /* @__PURE__ */ new Set();
420
447
  const evidence = [];
421
448
  for (const e of selectEffects(log, inv.when)) {
422
449
  const k = keyOf(e, inv.key);
423
450
  if (k === void 0 || present.has(k)) continue;
424
- if (!missing.includes(k)) missing.push(k);
451
+ missing.add(k);
425
452
  evidence.push(e.seq);
426
453
  }
427
- if (missing.length === 0) return null;
454
+ if (missing.size === 0) return null;
428
455
  return {
429
456
  invariant: inv.name,
430
- message: `${inv.when.target} ${inv.when.op ?? "*"} happened for key(s) ${missing.join(", ")} but ${inv.state.table}.${inv.column} in ${inv.state.target} has no such row`,
431
- keys: missing,
457
+ message: `${inv.when.target} ${inv.when.op ?? "*"} happened for key(s) ${[...missing].join(", ")} but ${inv.state.table}.${inv.column} in ${inv.state.target} has no such row`,
458
+ keys: [...missing],
432
459
  evidence
433
460
  };
434
461
  }
435
462
  function checkReferences(log, inv) {
436
463
  const rows = queryRows(log, inv.query);
437
464
  const targets = queryRows(log, inv.in);
438
- for (const [q, r] of [[inv.query, rows], [inv.in, targets]]) if (r === void 0) return {
439
- invariant: inv.name,
440
- message: `no snapshot of ${q.target} was recorded`,
441
- keys: [],
442
- evidence: []
443
- };
465
+ for (const [q, r] of [[inv.query, rows], [inv.in, targets]]) if (r === void 0) return noSnapshot(inv.name, q.target);
444
466
  const pointedAt = /* @__PURE__ */ new Set();
445
467
  for (const t of targets ?? []) {
446
468
  const v = t[inv.column];
@@ -554,8 +576,8 @@ function validateScenario(spec) {
554
576
  const errors = [];
555
577
  if (spec.version !== 1) errors.push(`version must be 1, got ${String(spec.version)}`);
556
578
  if (!spec.name.trim()) errors.push("name must not be empty");
579
+ else if (!/^[a-z0-9][a-z0-9-]*$/.test(spec.name)) errors.push(`name must be lowercase letters, digits and dashes: ${JSON.stringify(spec.name)}`);
557
580
  if (spec.platform !== void 0 && !spec.platform) errors.push("platform must not be empty when given");
558
- if (!/^[a-z0-9][a-z0-9-]*$/.test(spec.name)) errors.push(`name must be lowercase letters, digits and dashes: ${JSON.stringify(spec.name)}`);
559
581
  if (!spec.worker.entry) errors.push("worker.entry must not be empty");
560
582
  if (!spec.worker.config) errors.push("worker.config must not be empty");
561
583
  if (!spec.drive.kind) errors.push("drive.kind must not be empty");
@@ -578,7 +600,7 @@ function validateScenario(spec) {
578
600
  const ext = /* @__PURE__ */ new Set();
579
601
  for (const e of spec.externals) {
580
602
  if (!e.name) errors.push("every external needs a name");
581
- if (ext.has(e.name)) errors.push(`duplicate external ${JSON.stringify(e.name)}`);
603
+ else if (ext.has(e.name)) errors.push(`duplicate external ${JSON.stringify(e.name)}`);
582
604
  ext.add(e.name);
583
605
  if (!e.host) errors.push(`external ${JSON.stringify(e.name)} needs a host`);
584
606
  (e.responses ?? []).forEach((r, i) => {
@@ -817,12 +839,14 @@ function patchProperty(target, key, patch) {
817
839
  * functions are replaced by deterministic versions driven by the run's seed
818
840
  * and by a clock that starts at a fixed epoch and advances only when the
819
841
  * engine says so: one millisecond per effect, and to each timer's due time
820
- * when the timer fires. Timers fire only while the invocation is idle (no
821
- * effect in flight), in due order, so they never race real I/O.
842
+ * when the timer fires. Timers fire in due order and never race real I/O:
843
+ * in a sequential run only while the invocation is idle (no effect in
844
+ * flight); in a concurrent run one already due is a turn like a parked
845
+ * effect, and one not yet due fires only when nothing else can move.
822
846
  */
823
847
  /** 2026-01-01T00:00:00.000Z. Every run starts here. */
824
848
  const virtualEpoch = Date.UTC(2026, 0, 1);
825
- const realSetTimeout = globalThis.setTimeout.bind(globalThis);
849
+ const realSetTimeout$1 = globalThis.setTimeout.bind(globalThis);
826
850
  const realSetInterval = globalThis.setInterval.bind(globalThis);
827
851
  const realClearTimeout = globalThis.clearTimeout.bind(globalThis);
828
852
  const realClearInterval = globalThis.clearInterval.bind(globalThis);
@@ -838,11 +862,19 @@ const libraryScope = asyncScope();
838
862
  var VirtualClock = class {
839
863
  time = virtualEpoch;
840
864
  timers = [];
865
+ /** Deferred timers fired and not yet run by their pollers: work on its way, inside a host. */
866
+ unrun = /* @__PURE__ */ new Set();
867
+ /** Set by `stop`: the run is over, so no timer is pending and every deferred poller ends. */
868
+ stopped = false;
841
869
  nextId = 1;
842
870
  /** The invocation whose code is running; timers scheduled now belong to it. */
843
871
  owner = null;
844
872
  /** Set by a concurrent run: who is running, asked when a timer is scheduled (overrides `owner`). */
845
873
  ownerNow = null;
874
+ /** Set by the run: the effect being performed by the code scheduling a timer, kept on the timer. */
875
+ scopeNow = null;
876
+ /** Set by the run: told whose timer fired (or was marked fired), whichever path fired it. */
877
+ afterFire = null;
846
878
  /** Set by a concurrent run: binds a callback to the async context it was scheduled in. */
847
879
  bind = null;
848
880
  now() {
@@ -851,7 +883,7 @@ var VirtualClock = class {
851
883
  advance(ms) {
852
884
  if (ms > 0) this.time += ms;
853
885
  }
854
- schedule(callback, delay, args, interval) {
886
+ schedule(callback, delay, args, interval, owner) {
855
887
  const ms = Number.isFinite(delay) && delay > 0 ? Math.floor(delay) : 0;
856
888
  const timer = {
857
889
  id: this.nextId++,
@@ -859,14 +891,50 @@ var VirtualClock = class {
859
891
  callback: this.bind ? this.bind(callback) : callback,
860
892
  args,
861
893
  interval,
862
- owner: this.ownerNow ? this.ownerNow() : this.owner
894
+ owner: owner ?? (this.ownerNow ? this.ownerNow() : this.owner),
895
+ scope: owner === void 0 ? this.scopeNow?.() : void 0,
896
+ deferred: false,
897
+ deadline: owner !== void 0,
898
+ fired: 0
863
899
  };
900
+ if (this.stopped) return timer.id;
901
+ if (timer.scope !== void 0 && inWorkerd) {
902
+ timer.deferred = true;
903
+ this.pollDeferred(timer);
904
+ }
864
905
  this.timers.push(timer);
865
906
  return timer.id;
866
907
  }
908
+ /**
909
+ * Run a deferred timer's callback from where it was scheduled: a real zero
910
+ * timer made here, inside the host's code, polls until `fireNext` has
911
+ * fired it (as often as it fired, for an interval) or it was cleared.
912
+ */
913
+ pollDeferred(timer) {
914
+ const tick = () => {
915
+ while (timer.fired > 0) {
916
+ timer.fired--;
917
+ if (timer.fired === 0) this.unrun.delete(timer);
918
+ try {
919
+ timer.callback(...timer.args);
920
+ } catch {}
921
+ }
922
+ if (timer.fired > 0 || this.timers.includes(timer)) realSetTimeout$1(tick, 0);
923
+ };
924
+ realSetTimeout$1(tick, 0);
925
+ }
867
926
  setTimeout(callback, delay = 0, ...args) {
868
927
  return this.schedule(callback, delay, args, null);
869
928
  }
929
+ /**
930
+ * A timer of `owner`'s set by the run itself, whoever is running (an
931
+ * attempt's deadline): cancelled with the owner's others, and fired
932
+ * whenever time reaches it, whoever's timers may fire then (an object
933
+ * napping inside the attempt's call does not hold the engine's clock).
934
+ */
935
+ setTimeoutAs(owner, callback, delay) {
936
+ return this.schedule(callback, delay, [], null, owner);
937
+ }
870
938
  setInterval(callback, delay = 0, ...args) {
871
939
  const every = Number.isFinite(delay) && delay >= 1 ? Math.floor(delay) : 1;
872
940
  return this.schedule(callback, delay, args, every);
@@ -881,9 +949,32 @@ var VirtualClock = class {
881
949
  pendingTimers() {
882
950
  return this.timers.length;
883
951
  }
952
+ /**
953
+ * The run is over: drop every timer, fired or not, so the pollers armed
954
+ * inside hosts' code end (one left polling would keep an object referenced
955
+ * past the run) and nothing of the run's fires later.
956
+ */
957
+ stop() {
958
+ this.stopped = true;
959
+ for (const t of this.unrun) t.fired = 0;
960
+ this.unrun.clear();
961
+ this.timers = [];
962
+ }
963
+ /** Deferred timers fired and not yet run: what waits on nothing visible is still about to move. */
964
+ firedPending() {
965
+ return this.unrun.size;
966
+ }
967
+ /** Whether a timer scheduled inside the effect `scope` is still pending. */
968
+ hasTimerIn(scope) {
969
+ return scope !== void 0 && this.timers.some((t) => t.scope === scope);
970
+ }
884
971
  /** Drop every timer an invocation scheduled: a crashed invocation's code must never run again. */
885
972
  cancelOwner(owner) {
886
973
  this.timers = this.timers.filter((t) => t.owner !== owner);
974
+ for (const t of this.unrun) if (t.owner === owner) {
975
+ t.fired = 0;
976
+ this.unrun.delete(t);
977
+ }
887
978
  }
888
979
  earliest() {
889
980
  let earliest = this.timers[0];
@@ -894,20 +985,47 @@ var VirtualClock = class {
894
985
  nextDue() {
895
986
  return this.earliest()?.due;
896
987
  }
897
- /** Who set the timer `fireNext` would run: an invocation, null for none, undefined when no timer is pending. */
898
- nextOwner() {
899
- return this.earliest()?.owner;
988
+ /** Advance to the earliest due timer whose owner `owned` accepts and run it. False when none is pending. */
989
+ fireNextOwned(owned) {
990
+ const earliest = this.earliestOwned(owned);
991
+ if (!earliest) return false;
992
+ return this.fire(earliest);
993
+ }
994
+ /**
995
+ * When the earliest timer whose owner `owned` accepts is due, or undefined
996
+ * when none is pending; a deadline (`setTimeoutAs`) counts, as it fires,
997
+ * unless `deadlines` is false: whether an owner has a timer of its own to
998
+ * advance to (an object sleeping before it answers) is asked without them.
999
+ */
1000
+ nextDueOwned(owned, deadlines = true) {
1001
+ return this.earliestOwned(owned, deadlines)?.due;
1002
+ }
1003
+ earliestOwned(owned, deadlines = true) {
1004
+ let earliest;
1005
+ for (const t of this.timers) if ((deadlines && t.deadline || owned(t.owner)) && (!earliest || t.due < earliest.due || t.due === earliest.due && t.id < earliest.id)) earliest = t;
1006
+ return earliest;
1007
+ }
1008
+ /** Who set the timer `fireNextOwned` would run for `owned`; undefined when none is pending. */
1009
+ nextOwnerOwned(owned) {
1010
+ return this.earliestOwned(owned)?.owner;
900
1011
  }
901
1012
  /** Advance to the earliest due timer and run it. False when none is pending. */
902
1013
  fireNext() {
903
1014
  const earliest = this.earliest();
904
1015
  if (!earliest) return false;
1016
+ return this.fire(earliest);
1017
+ }
1018
+ fire(earliest) {
905
1019
  if (earliest.due > this.time) this.time = earliest.due;
906
1020
  if (earliest.interval === null) this.timers = this.timers.filter((t) => t !== earliest);
907
1021
  else earliest.due = this.time + earliest.interval;
908
- try {
1022
+ if (earliest.deferred) {
1023
+ earliest.fired++;
1024
+ this.unrun.add(earliest);
1025
+ } else try {
909
1026
  earliest.callback(...earliest.args);
910
1027
  } catch {}
1028
+ this.afterFire?.(earliest.owner);
911
1029
  return true;
912
1030
  }
913
1031
  };
@@ -1000,7 +1118,7 @@ function patchGlobals(seed, options = {}) {
1000
1118
  return random.float();
1001
1119
  });
1002
1120
  define(g, "setTimeout", (cb, ms, ...args) => {
1003
- if (inLibrary()) return realSetTimeout(cb, ms, ...args);
1121
+ if (inLibrary()) return realSetTimeout$1(cb, ms, ...args);
1004
1122
  read();
1005
1123
  return clock.setTimeout(cb, ms, ...args);
1006
1124
  });
@@ -1056,6 +1174,7 @@ function patchGlobals(seed, options = {}) {
1056
1174
  restore() {
1057
1175
  if (restored) return;
1058
1176
  restored = true;
1177
+ clock.stop();
1059
1178
  for (const u of undo.reverse()) u();
1060
1179
  }
1061
1180
  };
@@ -1067,14 +1186,14 @@ function realDeadline(ms) {
1067
1186
  let handle;
1068
1187
  return {
1069
1188
  expired: new Promise((resolve) => {
1070
- handle = realSetTimeout(() => resolve("expired"), Math.min(ms, maxTimeoutMs));
1189
+ handle = realSetTimeout$1(() => resolve("expired"), Math.min(ms, maxTimeoutMs));
1071
1190
  }),
1072
1191
  cancel: () => realClearTimeout(handle)
1073
1192
  };
1074
1193
  }
1075
1194
  /** Yield to the real event loop so microtasks and pending I/O can make progress. */
1076
1195
  function realTick() {
1077
- return new Promise((resolve) => realSetTimeout(() => resolve(), 0));
1196
+ return new Promise((resolve) => realSetTimeout$1(() => resolve(), 0));
1078
1197
  }
1079
1198
  const hostSetImmediate = globalThis.setImmediate;
1080
1199
  const inWorkerd = globalThis.navigator?.userAgent === "Cloudflare-Workers" || typeof globalThis.WebSocketPair === "function";
@@ -1113,6 +1232,7 @@ async function settleOn(promise, ctx) {
1113
1232
  error = e;
1114
1233
  });
1115
1234
  let afterTimer = false;
1235
+ let idleBefore = false;
1116
1236
  for (;;) {
1117
1237
  await Promise.race([tracked, afterTimer ? eventLoopTurn() : realTick()]);
1118
1238
  const cheap = afterTimer;
@@ -1121,8 +1241,19 @@ async function settleOn(promise, ctx) {
1121
1241
  if (failed) throw error;
1122
1242
  return value;
1123
1243
  }
1124
- if (ctx.crashed()) return new Promise(() => {});
1125
- if (ctx.inFlight() > 0) continue;
1244
+ if (ctx.crashed()) {
1245
+ if (ctx.crashError) throw ctx.crashError();
1246
+ return new Promise(() => {});
1247
+ }
1248
+ if (ctx.inFlight() > 0) {
1249
+ const owned = ctx.idle?.() ?? null;
1250
+ if (owned && idleBefore && ctx.clock.fireNextOwned(owned)) {
1251
+ idleBefore = false;
1252
+ afterTimer = true;
1253
+ } else idleBefore = owned !== null;
1254
+ continue;
1255
+ }
1256
+ idleBefore = false;
1126
1257
  if (ctx.clock.fireNext()) {
1127
1258
  afterTimer = true;
1128
1259
  continue;
@@ -1193,11 +1324,32 @@ function replyOf(r) {
1193
1324
  body
1194
1325
  };
1195
1326
  }
1327
+ /**
1328
+ * The scripted reply as a `Response`. Its body is known, so `text()` and
1329
+ * `json()` answer from it within a microtask: the model assumes body reads
1330
+ * settle within one turn of the event loop, and a stream read inside a
1331
+ * Durable Object can take a turn or more, during which the object's code
1332
+ * looks idle to the run.
1333
+ */
1196
1334
  function toResponse(reply) {
1197
- return new Response(reply.body === "" ? null : reply.body, {
1335
+ const response = new Response(reply.body === "" ? null : reply.body, {
1198
1336
  status: reply.status,
1199
1337
  headers: reply.headers
1200
1338
  });
1339
+ const text = reply.body;
1340
+ Object.defineProperties(response, {
1341
+ text: {
1342
+ value: () => Promise.resolve(text),
1343
+ configurable: true,
1344
+ writable: true
1345
+ },
1346
+ json: {
1347
+ value: () => Promise.resolve().then(() => JSON.parse(text)),
1348
+ configurable: true,
1349
+ writable: true
1350
+ }
1351
+ });
1352
+ return response;
1201
1353
  }
1202
1354
  /** A request or reply body as effect-log data: JSON when it parses, the text otherwise, null when empty. */
1203
1355
  function parseBody(text) {
@@ -1230,7 +1382,8 @@ function createScriptedFetch(externals, hooks, unsupported, afterRequest = () =>
1230
1382
  });
1231
1383
  const dedupeHeader = external.guarantees.dedupeBy?.toLowerCase();
1232
1384
  const dedupeKey = dedupeHeader ? headers[dedupeHeader] ?? null : null;
1233
- const body = parseBody(await request.text());
1385
+ const given = init?.body;
1386
+ const body = parseBody(typeof given === "string" ? given : given === null || given === void 0 && !(input instanceof Request) ? "" : await request.text());
1234
1387
  const args = {
1235
1388
  url: request.url,
1236
1389
  method,
@@ -1322,18 +1475,37 @@ async function withoutNetwork(work) {
1322
1475
  var Frame = class {
1323
1476
  /** The invocation whose effect this is. */
1324
1477
  invocation;
1478
+ target;
1479
+ op;
1325
1480
  /** Whether the effect hosts user code that makes effects of its own (`hostsEffects`). */
1326
1481
  hosts;
1482
+ /** Whose code the effect hosts, when it stays alive after the effect (`EffectOptions.host`). */
1483
+ host;
1327
1484
  /** False once the effect's perform has ended. */
1328
1485
  active = true;
1329
1486
  /** The effect's `onAbandon`, called where the crash happens (inside the hosted code's context). */
1330
1487
  onAbandon;
1488
+ /** Set by the run: told, after `onAbandon` reset the host, which host it was. */
1489
+ onHostAbandoned;
1331
1490
  /** The effect's `mayPark`: whether an effect its hosted code makes may wait for a turn now. */
1332
1491
  mayPark;
1333
1492
  /** The hosting effect this one was made inside of and waited for a turn under, if any. */
1334
1493
  parent;
1335
1494
  /** Effects the hosted code made that are parked or running now. */
1336
1495
  children = 0;
1496
+ /** Effects nested in this one (made inside its perform, not as turns) being performed now. */
1497
+ performing = 0;
1498
+ /** A host's effect whose call the host's code has started (`Frames.claimHost`). */
1499
+ claimed = false;
1500
+ /** The host's code this effect is the call of has started running (`Run.hostedCode`); until then the call is in transit. */
1501
+ entered = false;
1502
+ /** The host's code this effect is the call of has returned (`Frames.answered`): its answer is in transit. */
1503
+ answered = false;
1504
+ /**
1505
+ * The attempt (`RunHooks.attempt`) whose code made this effect, if any: what
1506
+ * the effect hosts is that attempt's code too, late once the attempt is.
1507
+ */
1508
+ attempt;
1337
1509
  /** Of those, the ones parked, or running but only waiting on parked effects of their own. */
1338
1510
  waitingChildren = 0;
1339
1511
  abandoned = false;
@@ -1341,9 +1513,12 @@ var Frame = class {
1341
1513
  crashed = new Promise((resolve) => {
1342
1514
  this.wake = () => resolve("nested_crash");
1343
1515
  });
1344
- constructor(invocation, hosts, options) {
1345
- this.invocation = invocation;
1346
- this.hosts = hosts;
1516
+ constructor(point, options) {
1517
+ this.invocation = point.invocation;
1518
+ this.target = point.target;
1519
+ this.op = point.op;
1520
+ this.hosts = point.hostsEffects === true;
1521
+ this.host = options.host;
1347
1522
  this.onAbandon = options.onAbandon;
1348
1523
  this.mayPark = options.mayPark ?? (() => true);
1349
1524
  }
@@ -1351,13 +1526,32 @@ var Frame = class {
1351
1526
  isWaiting() {
1352
1527
  return this.children > 0 && this.waitingChildren === this.children;
1353
1528
  }
1529
+ /**
1530
+ * Whether it counts as real I/O pending: unless its hosted code is only
1531
+ * waiting on parked effects of its own; once that code has answered, the
1532
+ * answer is on its way whatever it left parked, so the effect counts again
1533
+ * until it ends.
1534
+ */
1535
+ inFlight() {
1536
+ return this.answered || !this.isWaiting();
1537
+ }
1354
1538
  crash() {
1355
- this.abandon();
1356
1539
  this.wake();
1540
+ this.abandon();
1357
1541
  }
1542
+ /** Whether the effect was abandoned: a crash in its hosted code, or its I/O past the budget; the host was reset. */
1543
+ get isAbandoned() {
1544
+ return this.abandoned;
1545
+ }
1546
+ /**
1547
+ * The run's bookkeeping first, the platform's reset last: a Durable
1548
+ * Object's `abort()` tears down the task it is called in, so nothing after
1549
+ * it may be counted on to run.
1550
+ */
1358
1551
  abandon() {
1359
1552
  if (this.abandoned) return;
1360
1553
  this.abandoned = true;
1554
+ if (this.host !== void 0) this.onHostAbandoned?.(this.host);
1361
1555
  this.onAbandon?.();
1362
1556
  }
1363
1557
  };
@@ -1373,23 +1567,75 @@ var Frames = class {
1373
1567
  hosting = /* @__PURE__ */ new Map();
1374
1568
  /** Effects with `hostsEffects` being performed now, across invocations. */
1375
1569
  hostingCount = 0;
1570
+ /** Per host (`EffectOptions.host`), its effects being performed, innermost last. */
1571
+ byHost = /* @__PURE__ */ new Map();
1376
1572
  /** How many effects with `hostsEffects` are being performed now: above 0, hosted code may be running. */
1377
1573
  get hostingNow() {
1378
1574
  return this.hostingCount;
1379
1575
  }
1576
+ /** The innermost effect of `host`'s being performed now, if any: code of the host's runs inside it. */
1577
+ liveHost(host) {
1578
+ return this.byHost.get(host)?.at(-1);
1579
+ }
1580
+ /** The effects of `invocation`'s being performed now that host an object's code (`EffectOptions.host`). */
1581
+ hostingOf(invocation) {
1582
+ return this.stack.filter((f) => f.invocation === invocation && f.host !== void 0);
1583
+ }
1584
+ /**
1585
+ * The oldest effect of `host`'s being performed, with `op` when given, whose
1586
+ * call the host's code has not started yet, now claimed: an object's input
1587
+ * gate delivers calls in the order they arrived, which is the order their
1588
+ * effects entered. Without one of that op, the oldest unclaimed of any.
1589
+ */
1590
+ claimHost(host, op) {
1591
+ const live = this.byHost.get(host) ?? [];
1592
+ const frame = (op === void 0 ? void 0 : live.find((f) => !f.claimed && f.op === op)) ?? live.find((f) => !f.claimed);
1593
+ if (frame) frame.claimed = true;
1594
+ return frame;
1595
+ }
1596
+ /**
1597
+ * The hosts of the effects in flight, when every one of them is a hosting
1598
+ * effect whose hosted code is idle: running (entered, its answer not yet
1599
+ * on its way), with no effect of it performing or waiting for a turn,
1600
+ * nothing hosted inside it and no real work tracked. Such code can only
1601
+ * be awaiting a timer of its own (an object sleeping before it answers),
1602
+ * which the run may fire for it. Null while anything else is in flight,
1603
+ * or nothing is: a call still crossing into its object is on its way, and
1604
+ * waiting for it keeps the order in which calls enter the object the
1605
+ * schedule's, not real time's (two timers due together fire by the order
1606
+ * they were set).
1607
+ */
1608
+ idleHosts() {
1609
+ let counted = 0;
1610
+ const hosts = /* @__PURE__ */ new Set();
1611
+ for (const frame of this.stack) {
1612
+ if (frame.isWaiting()) continue;
1613
+ counted++;
1614
+ if (frame.host === void 0 || !frame.entered || frame.answered || frame.performing > 0 || frame.children > 0) return null;
1615
+ hosts.add(frame.host);
1616
+ }
1617
+ return counted > 0 && counted === this.inFlight ? hosts : null;
1618
+ }
1380
1619
  /**
1381
1620
  * The effect an invocation's new effect is made inside of, if any. Async
1382
1621
  * context tells exactly which code is inside; an invocation merely woken
1383
1622
  * meanwhile is not. A hosting effect's own effects are attributed to its
1384
1623
  * invocation: only those count as nested. Async context can be stale (code
1385
1624
  * resumed in the context of an effect that has ended, as an object's code
1386
- * may run in the context it was built in): trust only a live frame of the
1387
- * same invocation (the innermost), else the invocation's own hosting effect.
1625
+ * may run in the context it was built in) or absent (workerd carries none
1626
+ * into an object's code): trust only a live frame of the same invocation
1627
+ * (the innermost); else, for code in a stale context or hosted code
1628
+ * (`hosted`: an object's, entered by the platform), the invocation's own
1629
+ * hosting effect. Code in no context at all that is not hosted is
1630
+ * outside every effect: a second strand of the invocation (a step
1631
+ * attempt the engine gave up on, see `Run.attempt`) running while a call
1632
+ * of the first strand is in flight.
1388
1633
  */
1389
- enclosing(invocation) {
1390
- const store = effectScope?.getStore();
1391
- const live = store?.active && store.invocation === invocation ? store : void 0;
1392
- return effectScope ? live ?? this.hosting.get(invocation)?.at(-1) : this.stack.at(-1);
1634
+ enclosing(invocation, hosted = true) {
1635
+ if (!effectScope) return this.stack.at(-1);
1636
+ const store = effectScope.getStore();
1637
+ if (store?.active && store.invocation === invocation) return store;
1638
+ return hosted || store !== void 0 ? this.hosting.get(invocation)?.at(-1) : void 0;
1393
1639
  }
1394
1640
  /**
1395
1641
  * The effect whose perform the current code runs inside, whatever
@@ -1409,6 +1655,23 @@ var Frames = class {
1409
1655
  this.hostingFrames(frame.invocation).push(frame);
1410
1656
  this.hostingCount++;
1411
1657
  }
1658
+ if (frame.host !== void 0) {
1659
+ const frames = this.byHost.get(frame.host) ?? [];
1660
+ frames.push(frame);
1661
+ this.byHost.set(frame.host, frames);
1662
+ }
1663
+ }
1664
+ /**
1665
+ * The host's code `frame` is the call of has returned: its answer is in
1666
+ * transit, so the effect is in flight until it ends, whatever that code
1667
+ * left parked (the run waits for the answer before its next turn, so what
1668
+ * the code left outstanding is handed over before anything else moves).
1669
+ */
1670
+ answered(frame) {
1671
+ if (frame.answered) return;
1672
+ const before = frame.inFlight();
1673
+ frame.answered = true;
1674
+ if (frame.active && !before) this.inFlight++;
1412
1675
  }
1413
1676
  /** An effect's perform has ended. */
1414
1677
  leave(frame) {
@@ -1418,8 +1681,12 @@ var Frames = class {
1418
1681
  this.hostingCount--;
1419
1682
  }
1420
1683
  this.stack.splice(this.stack.lastIndexOf(frame), 1);
1421
- if (!frame.isWaiting()) this.inFlight--;
1422
- else if (frame.parent) {
1684
+ if (frame.host !== void 0) {
1685
+ const frames = this.byHost.get(frame.host);
1686
+ frames?.splice(frames.lastIndexOf(frame), 1);
1687
+ }
1688
+ if (frame.inFlight()) this.inFlight--;
1689
+ if (frame.isWaiting() && frame.parent) {
1423
1690
  const parent = frame.parent;
1424
1691
  this.adjust(parent, () => parent.waitingChildren--);
1425
1692
  }
@@ -1432,13 +1699,14 @@ var Frames = class {
1432
1699
  * and a frame that starts or stops waiting does so for its parent too.
1433
1700
  */
1434
1701
  adjust(frame, change) {
1435
- const before = frame.isWaiting();
1702
+ const waitingBefore = frame.isWaiting();
1703
+ const inFlightBefore = frame.inFlight();
1436
1704
  change();
1437
- const after = frame.isWaiting();
1438
- if (before === after) return;
1439
- if (frame.active) this.inFlight += after ? -1 : 1;
1705
+ const waiting = frame.isWaiting();
1706
+ if (frame.active && inFlightBefore !== frame.inFlight()) this.inFlight += waiting ? -1 : 1;
1707
+ if (waitingBefore === waiting) return;
1440
1708
  const parent = frame.parent;
1441
- if (frame.active && parent) this.adjust(parent, () => parent.waitingChildren += after ? 1 : -1);
1709
+ if (frame.active && parent) this.adjust(parent, () => parent.waitingChildren += waiting ? 1 : -1);
1442
1710
  }
1443
1711
  hostingFrames(invocation) {
1444
1712
  let frames = this.hosting.get(invocation);
@@ -1449,7 +1717,6 @@ var Frames = class {
1449
1717
  return frames;
1450
1718
  }
1451
1719
  };
1452
- // packages/engine/src/turns.ts
1453
1720
  var Turns = class {
1454
1721
  chooser;
1455
1722
  frames;
@@ -1457,6 +1724,12 @@ var Turns = class {
1457
1724
  runAs;
1458
1725
  /** The virtual globals' read counter, when they are installed. */
1459
1726
  reads;
1727
+ /** Work on its way that no frame counts: a host's timer fired and not yet run by its poller. */
1728
+ pending;
1729
+ /** Whether an object's work after an answer may be running: a wake could then come from inside it. */
1730
+ inObjects;
1731
+ /** Whether everything in flight is a hosting effect whose code is idle (see `Frames.idleHosts`). */
1732
+ idleHosted;
1460
1733
  /** Invocations waiting at an effect for their turn. */
1461
1734
  parked = [];
1462
1735
  parkSeq = 0;
@@ -1464,6 +1737,8 @@ var Turns = class {
1464
1737
  picked = [];
1465
1738
  /** Events started so far, to name the next start the same in every run. */
1466
1739
  starts = 0;
1740
+ /** Times the run let time pass over late turns (see `takeTurn`). */
1741
+ waits = 0;
1467
1742
  /** The target of the turn running since the last decision; null for an event's start or none. */
1468
1743
  turnTarget = null;
1469
1744
  commuteNot = false;
@@ -1477,11 +1752,14 @@ var Turns = class {
1477
1752
  restsAtStep = 0;
1478
1753
  /** The order invocations started in, which orders the parked ones. */
1479
1754
  startOrder = /* @__PURE__ */ new Map();
1480
- constructor(chooser, frames, runAs, reads) {
1755
+ constructor(chooser, frames, runAs, reads, pending = () => 0, inObjects = () => false, idleHosted = () => false) {
1481
1756
  this.chooser = chooser;
1482
1757
  this.frames = frames;
1483
1758
  this.runAs = runAs;
1484
1759
  this.reads = reads;
1760
+ this.pending = pending;
1761
+ this.inObjects = inObjects;
1762
+ this.idleHosted = idleHosted;
1485
1763
  }
1486
1764
  /** The turns picked so far, as a copy. */
1487
1765
  get picks() {
@@ -1492,7 +1770,7 @@ var Turns = class {
1492
1770
  this.startOrder.set(id, this.startOrder.size);
1493
1771
  }
1494
1772
  /** Park an invocation at an effect until `takeTurn` releases it with `go`. */
1495
- park(inv, target, go, host) {
1773
+ park(inv, target, go, host, attempt) {
1496
1774
  const option = {
1497
1775
  label: `${inv.id}@${inv.parks++}`,
1498
1776
  invocation: inv.id,
@@ -1503,10 +1781,26 @@ var Turns = class {
1503
1781
  seq: this.parkSeq++,
1504
1782
  go,
1505
1783
  option,
1784
+ attempt,
1506
1785
  ...host ? { host } : {}
1507
1786
  });
1508
1787
  this.rested();
1509
1788
  }
1789
+ /**
1790
+ * The hosting effect `host` ended with effects of its hosted code parked:
1791
+ * they are `owner`'s turns now (the host's work after its answer), so the
1792
+ * caller's crash does not drop them and a fault in them is the owner's.
1793
+ */
1794
+ adopt(host, owner) {
1795
+ this.parked = this.parked.map((p) => p.host === host ? {
1796
+ ...p,
1797
+ inv: owner,
1798
+ option: {
1799
+ ...p.option,
1800
+ invocation: owner.id
1801
+ }
1802
+ } : p);
1803
+ }
1510
1804
  /** See `Run.rested`. */
1511
1805
  rested() {
1512
1806
  this.rests++;
@@ -1544,7 +1838,7 @@ var Turns = class {
1544
1838
  /** See `Run.progressed`. */
1545
1839
  progressed() {
1546
1840
  this.moves++;
1547
- if (this.frames.hostingNow > 0) return;
1841
+ if (this.frames.hostingNow > 0 || this.inObjects()) return;
1548
1842
  const waiters = this.progressWaiters;
1549
1843
  this.progressWaiters = [];
1550
1844
  for (const wake of waiters) wake();
@@ -1553,7 +1847,11 @@ var Turns = class {
1553
1847
  async quiesce() {
1554
1848
  for (;;) {
1555
1849
  const moved = await this.wait();
1556
- if (this.frames.inFlight > 0) continue;
1850
+ if (this.pending() > 0) continue;
1851
+ if (this.frames.inFlight > 0) {
1852
+ if (!moved && this.idleHosted()) return;
1853
+ continue;
1854
+ }
1557
1855
  if (this.rests !== this.restsAtStep) return;
1558
1856
  if (!moved) return;
1559
1857
  }
@@ -1587,20 +1885,37 @@ var Turns = class {
1587
1885
  this.seenMoves = this.moves;
1588
1886
  return this.moves !== before;
1589
1887
  }
1590
- /** See `Run.takeTurn`. */
1591
- takeTurn(canStart) {
1888
+ /**
1889
+ * See `Run.takeTurn`. `canWait`: whether, with nothing else to do, the run
1890
+ * could let time pass (a timer is pending or a delayed event is due later).
1891
+ * While every parked turn is late (`RunHooks.attempt`) and nothing else is
1892
+ * on offer, waiting is an option too, so the late code's next move lands
1893
+ * before or after what the time brings; "none" then means the run should
1894
+ * let time pass as when nothing is parked.
1895
+ */
1896
+ takeTurn(canStart, timer, canWait = false) {
1592
1897
  const order = (inv) => this.startOrder.get(inv.id) ?? 0;
1593
1898
  this.parked = this.parked.filter((p) => !p.inv.isCrashed()).sort((a, b) => order(a.inv) - order(b.inv) || a.seq - b.seq);
1594
- const options = this.parked.length + (canStart ? 1 : 0);
1899
+ const waiting = canWait && !canStart && !timer && this.waits < 100 && this.parked.length > 0 && this.parked.every((p) => p.attempt?.late === true);
1900
+ const offered = this.turnOptions(canStart, timer, waiting);
1901
+ const options = offered.length;
1595
1902
  this.endSegment();
1596
1903
  this.turnTarget = null;
1597
1904
  this.step();
1598
1905
  if (options === 0) return "none";
1599
- const answer = this.chooser.choose("turn", this.turnOptions(canStart));
1906
+ const answer = this.chooser.choose("turn", offered);
1600
1907
  const pick = answer < options ? answer : 0;
1601
1908
  if (options > 1) this.picked.push(pick);
1602
1909
  const [chosen] = pick < this.parked.length ? this.parked.splice(pick, 1) : [];
1603
1910
  if (!chosen) {
1911
+ if (waiting) {
1912
+ this.waits++;
1913
+ return "none";
1914
+ }
1915
+ if (timer && pick === options - 1) {
1916
+ timer.fire();
1917
+ return "timer";
1918
+ }
1604
1919
  this.starts++;
1605
1920
  return "start";
1606
1921
  }
@@ -1611,9 +1926,26 @@ var Turns = class {
1611
1926
  chosen.go();
1612
1927
  return "turn";
1613
1928
  }
1614
- /** The turns on offer, as choices: the parked invocations in order, then starting the next event. */
1615
- turnOptions(canStart) {
1616
- return [...this.parked.map((p) => p.option), ...canStart ? [{ label: `start:${this.starts}` }] : []];
1929
+ /**
1930
+ * The turns on offer, as choices: the parked invocations in order, then
1931
+ * starting the next event, then the due timer (last, so a recorded pick
1932
+ * of the others means the same with or without it), or, when every parked
1933
+ * turn is late and nothing else is offered, letting time pass. A timer's
1934
+ * option names its owner and how many of that owner's timers have fired,
1935
+ * and has no target: the callback may do anything, and firing it reads
1936
+ * virtual time, so it commutes with nothing; so does waiting, which fires
1937
+ * the next timer.
1938
+ */
1939
+ turnOptions(canStart, timer, waiting = false) {
1940
+ return [
1941
+ ...this.parked.map((p) => p.option),
1942
+ ...canStart ? [{ label: `start:${this.starts}` }] : [],
1943
+ ...timer ? [{
1944
+ label: `timer:${timer.owner ?? ""}@${timer.fired}`,
1945
+ ...timer.owner !== null ? { invocation: timer.owner } : {}
1946
+ }] : [],
1947
+ ...waiting ? [{ label: `wait:${this.waits}` }] : []
1948
+ ];
1617
1949
  }
1618
1950
  };
1619
1951
  // packages/engine/src/run.ts
@@ -1630,6 +1962,8 @@ var Turns = class {
1630
1962
  * attributed to the invocation whose code made it even when a promise shared
1631
1963
  * between invocations resumes one during another's turn.
1632
1964
  */
1965
+ /** The host's own timer, captured before any patching: a host poller's ticks are real. */
1966
+ const realSetTimeout = globalThis.setTimeout.bind(globalThis);
1633
1967
  /** Thrown into user code by a synchronous effect that crashes the invocation. */
1634
1968
  var CrashSignal = class extends Error {
1635
1969
  name = "CrashSignal";
@@ -1670,14 +2004,17 @@ var InvocationState = class {
1670
2004
  isCrashed() {
1671
2005
  return this.crashedFlag;
1672
2006
  }
1673
- crash() {
2007
+ /** `inside`: the effect the crash happened inside of, when one did (a nested effect's fault). */
2008
+ crash(inside) {
1674
2009
  if (this.crashedFlag) return;
1675
2010
  this.crashedFlag = true;
1676
- this.onCrash();
2011
+ this.onCrash(inside);
1677
2012
  this.resolveCrashed();
1678
2013
  }
1679
2014
  };
1680
2015
  const deliveryScope = asyncScope();
2016
+ const hostScope = asyncScope();
2017
+ const attemptScope = asyncScope();
1681
2018
  /** The run whose globals are installed, if any: where code observed from outside records into. */
1682
2019
  let installed = null;
1683
2020
  function installedRun() {
@@ -1695,6 +2032,9 @@ function waitingUnseen(invocation) {
1695
2032
  }
1696
2033
  /** Delivered invocations are `<event>#<attempt>`, so this id is never one of theirs. */
1697
2034
  const bookkeepingId = "platform";
2035
+ function isThenable(value) {
2036
+ return value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
2037
+ }
1698
2038
  var Run = class {
1699
2039
  /** The records, appended in place. */
1700
2040
  entries = [];
@@ -1716,6 +2056,30 @@ var Run = class {
1716
2056
  * `hosted`.
1717
2057
  */
1718
2058
  hosts = /* @__PURE__ */ new Map();
2059
+ /** Per host (`EffectOptions.host`), the invocation its work after an answer runs as; see `continuationOf`. */
2060
+ continuations = /* @__PURE__ */ new Map();
2061
+ /** Per host, how many such invocations it has had: one more after each reset of the object. */
2062
+ continuationCounts = /* @__PURE__ */ new Map();
2063
+ /** Per host, the last of its effects performed: its `onAbandon` resets the object when its later work crashes. */
2064
+ hostFrames = /* @__PURE__ */ new Map();
2065
+ /** Continuations with work that may still move: the run does not end while one is alive. */
2066
+ afterWork = /* @__PURE__ */ new Set();
2067
+ /** Per continuation, timers of its fired since its work last settled (see `afterWorkTimerLimit`). */
2068
+ afterWorkTimers = /* @__PURE__ */ new Map();
2069
+ /** Per owner, timers fired so far (any path): names a timer turn (see `dueTimer`). */
2070
+ timersFired = /* @__PURE__ */ new Map();
2071
+ /** Per host, real work its code started and the run tracks (Web Crypto) still running; see `leftHost`. */
2072
+ hostIo = /* @__PURE__ */ new Map();
2073
+ /**
2074
+ * Hosting effects that ended with effects of their hosted code outstanding
2075
+ * (parked or performing), and the host's work after its answer, which owns
2076
+ * those effects from then on; see `ownerOf`.
2077
+ */
2078
+ adopted = /* @__PURE__ */ new WeakMap();
2079
+ /** Per host, its poller (concurrent runs; see `pollHost`). */
2080
+ hostPollers = /* @__PURE__ */ new Map();
2081
+ /** Concurrent runs: settles waiting on invocations, released with a `CrashSignal` once theirs crashed; see `settle`. */
2082
+ crashWatch = [];
1719
2083
  patched = null;
1720
2084
  restoreFetch = null;
1721
2085
  /** The invocation whose code is running (one at a time); outbound fetches are attributed to it. */
@@ -1729,7 +2093,7 @@ var Run = class {
1729
2093
  options;
1730
2094
  constructor(options) {
1731
2095
  this.options = options;
1732
- this.turns = new Turns(options.chooser, this.frames, (id) => this.runAs(id), () => this.patched?.reads);
2096
+ this.turns = new Turns(options.chooser, this.frames, (id) => this.runAs(id), () => this.patched?.reads, () => this.firedPending(), () => this.hasAfterWork(), () => this.timersAllowed() !== null);
1733
2097
  this.concurrent = options.bounds.maxConcurrentInvocations > 1;
1734
2098
  }
1735
2099
  get log() {
@@ -1779,18 +2143,40 @@ var Run = class {
1779
2143
  if (!this.patched) {
1780
2144
  this.patched = patchGlobals(this.options.chooser.seed, { trackIo: (work) => {
1781
2145
  this.frames.inFlight++;
2146
+ const host = hostScope?.getStore()?.host;
2147
+ if (host !== void 0) this.hostIo.set(host, (this.hostIo.get(host) ?? 0) + 1);
1782
2148
  return work.finally(() => {
1783
2149
  this.frames.inFlight--;
2150
+ if (host !== void 0) {
2151
+ const left = (this.hostIo.get(host) ?? 1) - 1;
2152
+ if (left > 0) this.hostIo.set(host, left);
2153
+ else this.hostIo.delete(host);
2154
+ }
1784
2155
  if (this.concurrent) this.progressed();
1785
2156
  });
1786
2157
  } });
1787
2158
  const clock = this.patched.clock;
1788
- clock.ownerNow = () => this.running();
2159
+ clock.ownerNow = () => this.timerOwner();
2160
+ clock.scopeNow = () => hostScope?.getStore()?.host;
2161
+ clock.afterFire = (owner) => {
2162
+ this.timersFired.set(owner, (this.timersFired.get(owner) ?? 0) + 1);
2163
+ if (owner !== null) this.timerFired(owner);
2164
+ };
1789
2165
  clock.bind = (callback) => {
1790
2166
  if (!deliveryScope) return callback;
1791
2167
  const scope = deliveryScope;
1792
2168
  const cell = scope.getStore() ?? { id: this.running() };
1793
- return (...args) => scope.run(cell, () => callback(...args));
2169
+ const inHostCtx = hostScope?.getStore();
2170
+ const inHost = (fn) => {
2171
+ if (hostScope && inHostCtx !== void 0) hostScope.run(inHostCtx, fn);
2172
+ else fn();
2173
+ };
2174
+ const inAttemptCell = attemptScope?.getStore();
2175
+ const inAttempt = (fn) => {
2176
+ if (attemptScope && inAttemptCell !== void 0) attemptScope.run(inAttemptCell, fn);
2177
+ else fn();
2178
+ };
2179
+ return (...args) => scope.run(cell, () => inHost(() => inAttempt(() => callback(...args))));
1794
2180
  };
1795
2181
  }
1796
2182
  if (!this.restoreFetch) this.restoreFetch = installScriptedFetch(externals, {
@@ -1835,8 +2221,282 @@ var Run = class {
1835
2221
  return queued;
1836
2222
  }
1837
2223
  running() {
2224
+ const host = this.afterWorkHost();
2225
+ if (host !== void 0) return this.continuationOf(host).id;
1838
2226
  return deliveryScope?.getStore()?.id ?? this.current;
1839
2227
  }
2228
+ hostedCode(host, code, op) {
2229
+ if (hostScope?.getStore()?.host === host) return code();
2230
+ if (this.concurrent) this.pollHost(host);
2231
+ const current = this.frames.current();
2232
+ const frame = current?.host === host && current.active ? current : this.frames.claimHost(host, op);
2233
+ if (frame) frame.entered = true;
2234
+ const run = () => this.patched ? this.patched.handlerCode(code) : code();
2235
+ const result = hostScope ? hostScope.run({
2236
+ host,
2237
+ frame
2238
+ }, run) : run();
2239
+ if (frame) {
2240
+ const answered = () => this.frames.answered(frame);
2241
+ if (isThenable(result)) Promise.resolve(result).then(answered, answered);
2242
+ else answered();
2243
+ }
2244
+ return result;
2245
+ }
2246
+ /**
2247
+ * Concurrent runs: the host's poller, a real zero timer armed here, inside
2248
+ * the host's code during its request, and re-armed from its own ticks while
2249
+ * the host may still move (an effect of its being performed, work of its
2250
+ * own alive, a wait pending). Each tick wakes the host's waits (`hostTick`):
2251
+ * the host's work after an answer waits for its turns on them, since a
2252
+ * timer that work armed itself, after its request completed, would keep the
2253
+ * object referenced in workerd.
2254
+ */
2255
+ pollHost(host) {
2256
+ if (this.hostPollers.has(host)) return;
2257
+ const poller = { waiters: [] };
2258
+ this.hostPollers.set(host, poller);
2259
+ const tick = () => {
2260
+ const waiters = poller.waiters;
2261
+ poller.waiters = [];
2262
+ for (const wake of waiters) wake();
2263
+ if (poller.waiters.length > 0 || this.hostMayMove(host)) realSetTimeout(tick, 0);
2264
+ else this.hostPollers.delete(host);
2265
+ };
2266
+ realSetTimeout(tick, 0);
2267
+ }
2268
+ hostMayMove(host) {
2269
+ const cont = this.continuations.get(host);
2270
+ return cont !== void 0 && !cont.isCrashed() && this.afterWork.has(cont) || this.frames.liveHost(host) !== void 0;
2271
+ }
2272
+ /** One tick of the host's poller, from inside the host's code; a real tick where no poller is armed. */
2273
+ hostTick(host) {
2274
+ const poller = this.hostPollers.get(host);
2275
+ if (!poller) return realTick();
2276
+ return new Promise((resolve) => poller.waiters.push(resolve));
2277
+ }
2278
+ /**
2279
+ * The invocation a timer set now belongs to: a host's timers are the
2280
+ * host's, its continuation's, inside a call or after it, so the caller's
2281
+ * crash does not cancel them and a crash of the host's work does.
2282
+ */
2283
+ timerOwner() {
2284
+ const ctx = hostScope?.getStore();
2285
+ if (ctx !== void 0) return this.continuationOf(ctx.host).id;
2286
+ return this.running();
2287
+ }
2288
+ /**
2289
+ * The host whose code is running after the effect it was entered by has
2290
+ * ended (or, where that effect is not known, while none of its effects is
2291
+ * being performed), if any: work after an answer.
2292
+ */
2293
+ afterWorkHost() {
2294
+ const ctx = hostScope?.getStore();
2295
+ if (ctx === void 0) return void 0;
2296
+ return (ctx.frame ? ctx.frame.active : this.frames.liveHost(ctx.host) !== void 0) ? void 0 : ctx.host;
2297
+ }
2298
+ /**
2299
+ * The invocation a host's work after an answer runs as, `<host>/after`
2300
+ * (`#<n>` once the object was reset: a new instance's work is a new
2301
+ * invocation's), started on first use and alive until `settleAfterWork`;
2302
+ * work woken later revives it.
2303
+ */
2304
+ continuationOf(host) {
2305
+ let cont = this.continuations.get(host);
2306
+ if (!cont) {
2307
+ const n = (this.continuationCounts.get(host) ?? 0) + 1;
2308
+ this.continuationCounts.set(host, n);
2309
+ cont = this.track(`${host}/after${n > 1 ? `#${n}` : ""}`);
2310
+ this.continuations.set(host, cont);
2311
+ if (this.concurrent) this.turns.started(cont.id);
2312
+ }
2313
+ if (!cont.isCrashed()) this.afterWork.add(cont);
2314
+ return cont;
2315
+ }
2316
+ hostReset(host) {
2317
+ this.hostAbandoned(host);
2318
+ }
2319
+ /**
2320
+ * The host was reset (`onAbandon` ran: a crash inside its code, an effect
2321
+ * of its that hung; or the platform dropped the instance, `hostReset`): its
2322
+ * work after an answer is gone with the instance, timers included, and its
2323
+ * poller with it.
2324
+ */
2325
+ hostAbandoned(host) {
2326
+ this.hostPollers.delete(host);
2327
+ const cont = this.continuations.get(host);
2328
+ if (!cont) return;
2329
+ this.continuations.delete(host);
2330
+ this.afterWork.delete(cont);
2331
+ cont.crash();
2332
+ }
2333
+ /**
2334
+ * A host's effect ended: work its code left outstanding (effects parked or
2335
+ * performing, timers pending, real work tracked) is the host's own now,
2336
+ * its continuation's, which owns the outstanding effects from here on
2337
+ * (see `ownerOf`): the caller's crash does not end them, and a fault in
2338
+ * them is the object's.
2339
+ */
2340
+ leftHost(frame) {
2341
+ if (frame.host === void 0 || frame.isAbandoned) return;
2342
+ this.hostFrames.set(frame.host, frame);
2343
+ const effects = frame.children > 0 || frame.performing > 0;
2344
+ if (!effects && !this.patched?.clock.hasTimerIn(frame.host) && (this.hostIo.get(frame.host) ?? 0) === 0) {
2345
+ const cont = this.continuations.get(frame.host);
2346
+ if (cont) this.afterWorkTimers.delete(cont.id);
2347
+ return;
2348
+ }
2349
+ const cont = this.continuationOf(frame.host);
2350
+ if (!effects) return;
2351
+ this.adopted.set(frame, cont);
2352
+ if (this.concurrent) this.turns.adopt(frame, cont);
2353
+ }
2354
+ /**
2355
+ * Who owns an effect of `inv`'s made inside `enclosing`: `inv`, unless the
2356
+ * enclosing effect was a host's, ended while this one was outstanding and
2357
+ * handed it to the host's work after its answer (`leftHost`). The call's
2358
+ * invocation may be long finished or crashed then; the object goes on.
2359
+ */
2360
+ ownerOf(inv, enclosing) {
2361
+ const adopted = enclosing && this.adopted.get(enclosing);
2362
+ return adopted && enclosing.invocation === inv.id ? adopted : inv;
2363
+ }
2364
+ /**
2365
+ * A timer of a continuation's fired, by whichever path: its count against
2366
+ * `afterWorkTimerLimit` since its work last settled; past it the object's
2367
+ * work does not settle, so the run is UNSUPPORTED and the work ends (its
2368
+ * timers with it).
2369
+ */
2370
+ timerFired(owner) {
2371
+ let cont;
2372
+ for (const c of this.continuations.values()) if (c.id === owner) cont = c;
2373
+ if (!cont || cont.isCrashed()) return;
2374
+ const n = (this.afterWorkTimers.get(owner) ?? 0) + 1;
2375
+ this.afterWorkTimers.set(owner, n);
2376
+ if (n <= 100) return;
2377
+ this.unsupported(`${owner}: the object's work after its answer fired its timers ${n} times and does not settle (an interval or a timer that re-arms itself); the model waits for such work only up to 100 firings without it settling`);
2378
+ this.afterWork.delete(cont);
2379
+ cont.crash();
2380
+ }
2381
+ /** A host's timers fired and not yet run by their pollers inside it: work on its way. */
2382
+ firedPending() {
2383
+ return this.patched?.clock.firedPending() ?? 0;
2384
+ }
2385
+ /** Whether an object's work after an answer may still move; the run does not end while it may. */
2386
+ hasAfterWork() {
2387
+ for (const cont of this.afterWork) if (!cont.isCrashed()) return true;
2388
+ return false;
2389
+ }
2390
+ /**
2391
+ * Nothing can move (no effect in flight, no turn to take, no timer due):
2392
+ * every continuation alive has settled, as an object with nothing pending
2393
+ * goes idle. How many did; work of theirs woken later revives them.
2394
+ */
2395
+ settleAfterWork() {
2396
+ const n = this.afterWork.size;
2397
+ for (const cont of this.afterWork) this.afterWorkTimers.delete(cont.id);
2398
+ this.afterWork.clear();
2399
+ return n;
2400
+ }
2401
+ /**
2402
+ * Sequential runs: between deliveries, let objects' work after their
2403
+ * answers run to rest, as it does in the runtime while nothing else comes
2404
+ * in: real I/O completes, timers fire in due order, and once nothing of it
2405
+ * can move it has settled.
2406
+ */
2407
+ async driveAfterWork() {
2408
+ let idleBefore = false;
2409
+ while (this.hasAfterWork()) {
2410
+ if (this.firedPending() > 0) {
2411
+ idleBefore = false;
2412
+ await realTick();
2413
+ continue;
2414
+ }
2415
+ if (this.frames.inFlight > 0) {
2416
+ const allowed = this.timersAllowed();
2417
+ if (allowed && idleBefore && this.fireOwned(allowed) !== void 0) {
2418
+ idleBefore = false;
2419
+ await eventLoopTurn();
2420
+ } else {
2421
+ idleBefore = allowed !== null;
2422
+ await realTick();
2423
+ }
2424
+ continue;
2425
+ }
2426
+ idleBefore = false;
2427
+ if (this.fireAfterWorkTimer()) {
2428
+ await eventLoopTurn();
2429
+ continue;
2430
+ }
2431
+ await realTick();
2432
+ if (this.frames.inFlight > 0 || this.firedPending() > 0 || this.fireAfterWorkTimer()) continue;
2433
+ this.settleAfterWork();
2434
+ }
2435
+ }
2436
+ /** Fire the next due timer of an object's work after an answer, as that work. False when none is pending. */
2437
+ fireAfterWorkTimer() {
2438
+ const alive = this.aliveAfterWork();
2439
+ if (alive.size === 0) return false;
2440
+ return this.fireOwned((owner) => owner !== null && alive.has(owner)) !== void 0;
2441
+ }
2442
+ /**
2443
+ * Whose timers may fire now: anyone's while nothing is in flight; while
2444
+ * only hosting effects whose hosted code is idle are, and one of those
2445
+ * hosts has a timer pending (an object awaiting a timer of its own before
2446
+ * it answers, see `Frames.idleHosts`), the timers of those hosts' work;
2447
+ * nobody's otherwise: a fired timer not yet run, or idle hosted code with
2448
+ * no timer, is work on its way that the run cannot see yet (a call
2449
+ * crossing into the object, storage I/O).
2450
+ */
2451
+ timersAllowed() {
2452
+ const clock = this.patched?.clock;
2453
+ if (!clock || this.firedPending() > 0) return null;
2454
+ if (this.frames.inFlight === 0) return () => true;
2455
+ const hosts = this.frames.idleHosts();
2456
+ if (!hosts) return null;
2457
+ const owners = /* @__PURE__ */ new Set();
2458
+ for (const host of hosts) {
2459
+ const cont = this.continuations.get(host);
2460
+ if (cont) owners.add(cont.id);
2461
+ }
2462
+ const allowed = (owner) => owner !== null && owners.has(owner);
2463
+ return clock.nextDueOwned(allowed, false) === void 0 ? null : allowed;
2464
+ }
2465
+ /**
2466
+ * Fire the earliest due timer whose owner `allowed` accepts, as that owner
2467
+ * (a step of a concurrent run). The owner it fired as (null for none);
2468
+ * undefined when no such timer is pending.
2469
+ */
2470
+ fireOwned(allowed) {
2471
+ const clock = this.patched?.clock;
2472
+ if (!clock) return void 0;
2473
+ const owner = clock.nextOwnerOwned(allowed);
2474
+ if (owner === void 0) return void 0;
2475
+ this.runAs(owner);
2476
+ if (this.concurrent) this.turns.step();
2477
+ clock.fireNextOwned(allowed);
2478
+ return owner;
2479
+ }
2480
+ /**
2481
+ * Wait until what is running has come to rest: fired timers run and real
2482
+ * I/O done; or, two turns of the event loop running, only hosting effects
2483
+ * whose code is idle in flight (an object awaiting a timer of its own
2484
+ * before it answers), which the next timer to fire is for.
2485
+ */
2486
+ async rest() {
2487
+ let idleBefore = false;
2488
+ for (;;) {
2489
+ await eventLoopTurn();
2490
+ if (this.firedPending() > 0) {
2491
+ idleBefore = false;
2492
+ continue;
2493
+ }
2494
+ if (this.frames.inFlight === 0) return;
2495
+ const idle = this.timersAllowed() !== null;
2496
+ if (idle && idleBefore) return;
2497
+ idleBefore = idle;
2498
+ }
2499
+ }
1840
2500
  runAs(id) {
1841
2501
  if (this.patched) this.patched.clock.owner = id;
1842
2502
  if (id !== null) this.current = id;
@@ -1847,10 +2507,30 @@ var Run = class {
1847
2507
  }
1848
2508
  track(id) {
1849
2509
  if (this.invocations.has(id)) throw new Error(`invocation ${id} already started`);
1850
- const inv = new InvocationState(id, () => this.patched?.clock.cancelOwner(id));
2510
+ const inv = new InvocationState(id, (inside) => {
2511
+ this.patched?.clock.cancelOwner(id);
2512
+ this.adoptInFlight(id, inside);
2513
+ });
1851
2514
  this.invocations.set(id, inv);
1852
2515
  return inv;
1853
2516
  }
2517
+ /**
2518
+ * The invocation crashed with calls into objects still in flight (a late
2519
+ * attempt's call while the retry's effect took the fault): the objects go
2520
+ * on, as the runtime's do, so what their code still does is their own work
2521
+ * (`ownerOf`), an answer to a caller that is gone. The call the crash
2522
+ * happened inside (`inside`) is abandoned by the crash instead and resets
2523
+ * its object.
2524
+ */
2525
+ adoptInFlight(id, inside) {
2526
+ for (const frame of this.frames.hostingOf(id)) {
2527
+ if (frame === inside || frame.isAbandoned || frame.host === void 0) continue;
2528
+ if (this.adopted.has(frame)) continue;
2529
+ const cont = this.continuationOf(frame.host);
2530
+ this.adopted.set(frame, cont);
2531
+ if (this.concurrent) this.turns.adopt(frame, cont);
2532
+ }
2533
+ }
1854
2534
  invocation(id) {
1855
2535
  const inv = this.invocations.get(id);
1856
2536
  if (!inv) throw new Error(`effect from unknown invocation ${id}`);
@@ -1911,19 +2591,48 @@ var Run = class {
1911
2591
  return fault;
1912
2592
  }
1913
2593
  async effect(point, perform, summarize, options = {}) {
2594
+ const ctx = hostScope?.getStore();
2595
+ if (ctx !== void 0) {
2596
+ const { host } = ctx;
2597
+ const live = ctx.frame ? ctx.frame.active ? ctx.frame : void 0 : this.frames.liveHost(host);
2598
+ if (live) {
2599
+ if (live.invocation !== point.invocation) return this.effect({
2600
+ ...point,
2601
+ invocation: live.invocation
2602
+ }, perform, summarize, options);
2603
+ } else {
2604
+ const cont = this.continuationOf(host);
2605
+ const own = {
2606
+ ...point,
2607
+ invocation: cont.id
2608
+ };
2609
+ if (cont.isCrashed()) return hang();
2610
+ const ended = ctx.frame ?? this.hostFrames.get(host);
2611
+ if (this.concurrent && (ended?.mayPark() ?? true)) {
2612
+ let released = false;
2613
+ this.turns.park(cont, own.target, () => {
2614
+ released = true;
2615
+ });
2616
+ while (!released && !cont.isCrashed()) await this.hostTick(host);
2617
+ if (!released) return hang();
2618
+ }
2619
+ return this.performEffect(own, perform, summarize, options, cont, ended);
2620
+ }
2621
+ }
1914
2622
  const inv = this.invocation(point.invocation);
1915
- if (inv.isCrashed()) return hang();
1916
- const enclosing = this.frames.enclosing(point.invocation);
2623
+ const enclosing = this.frames.enclosing(point.invocation, hostScope?.getStore() !== void 0);
2624
+ if (this.ownerOf(inv, enclosing).isCrashed()) return hang();
1917
2625
  const nested = enclosing !== void 0;
1918
2626
  if (this.concurrent && !nested) {
1919
2627
  const host = this.hosts.get(point.invocation);
1920
2628
  if (host?.active) return this.hostedTurn(point, perform, summarize, options, inv, void 0, host, (park) => new Promise((go) => park(() => go(true))));
1921
- await new Promise((go) => this.turns.park(inv, point.target, go));
2629
+ await new Promise((go) => this.turns.park(inv, point.target, go, void 0, this.attemptNow()));
1922
2630
  if (inv.isCrashed()) return hang();
1923
- } else if (this.concurrent && enclosing?.hosts && enclosing.mayPark()) return this.hostedTurn(point, perform, summarize, options, inv, enclosing, enclosing, async (park) => {
2631
+ } else if (this.concurrent && enclosing?.hosts && enclosing.mayPark()) return this.hostedTurn(point, perform, summarize, options, inv, enclosing, enclosing, async (park, crashed) => {
1924
2632
  let released = false;
1925
2633
  park(() => released = true);
1926
- while (!released && !inv.isCrashed()) await realTick();
2634
+ const host = enclosing.host;
2635
+ while (!released && !crashed()) await (host === void 0 ? realTick() : this.hostTick(host));
1927
2636
  return released;
1928
2637
  });
1929
2638
  return this.performEffect(point, perform, summarize, options, inv, enclosing);
@@ -1936,7 +2645,10 @@ var Run = class {
1936
2645
  */
1937
2646
  async hostedTurn(point, perform, summarize, options, inv, enclosing, host, wait) {
1938
2647
  this.childWaits(host);
1939
- if (!await wait((go) => this.turns.park(inv, point.target, go, host))) {
2648
+ const owner = this.ownerOf(inv, enclosing);
2649
+ const crashed = () => this.ownerOf(inv, enclosing).isCrashed();
2650
+ const attempt = this.attemptNow(enclosing, host);
2651
+ if (!await wait((go) => this.turns.park(owner, point.target, go, host, attempt), crashed)) {
1940
2652
  this.childLeaves(host, true);
1941
2653
  return hang();
1942
2654
  }
@@ -1961,20 +2673,29 @@ var Run = class {
1961
2673
  });
1962
2674
  }
1963
2675
  /** The effect once it has its turn: the fault, the perform under its deadline, the record. */
1964
- async performEffect(point, perform, summarize, options, inv, enclosing, host) {
2676
+ async performEffect(made, perform, summarize, options, inv, enclosing, host) {
1965
2677
  const dead = () => {
1966
2678
  enclosing?.crash();
1967
2679
  return hang();
1968
2680
  };
1969
- const fault = this.open(point, inv);
1970
- const before = this.faultBefore(point, inv, fault);
2681
+ const owner = () => this.ownerOf(inv, enclosing);
2682
+ const opener = owner();
2683
+ const point = opener === inv ? made : {
2684
+ ...made,
2685
+ invocation: opener.id
2686
+ };
2687
+ const fault = this.open(point, opener);
2688
+ const before = this.faultBefore(point, opener, fault, enclosing);
1971
2689
  if (before === "crashed") return dead();
1972
2690
  if (before) throw before;
1973
2691
  let settled;
1974
2692
  const deadline = realDeadline(this.options.bounds.budgetMs);
1975
- const frame = new Frame(point.invocation, point.hostsEffects === true, options);
2693
+ const frame = new Frame(point, options);
2694
+ frame.onHostAbandoned = (h) => this.hostAbandoned(h);
1976
2695
  frame.parent = host;
2696
+ frame.attempt = this.attemptNow(enclosing, host);
1977
2697
  this.frames.enter(frame);
2698
+ if (enclosing) enclosing.performing++;
1978
2699
  try {
1979
2700
  const inside = () => effectScope ? effectScope.run(frame, perform) : perform();
1980
2701
  const io = this.patched ? this.patched.libraryIo(inside) : inside();
@@ -1996,13 +2717,15 @@ var Run = class {
1996
2717
  };
1997
2718
  } finally {
1998
2719
  deadline.cancel();
2720
+ if (enclosing) enclosing.performing--;
1999
2721
  this.frames.leave(frame);
2722
+ this.leftHost(frame);
2000
2723
  this.patched?.clock.advance(1);
2001
2724
  if (this.concurrent) this.progressed();
2002
2725
  }
2003
2726
  if (settled === "expired") {
2004
2727
  this.unsupported(`${point.target} ${point.op} did not complete within ${this.options.bounds.budgetMs} ms of real time`);
2005
- inv.crash();
2728
+ owner().crash();
2006
2729
  frame.abandon();
2007
2730
  return hang();
2008
2731
  }
@@ -2020,17 +2743,23 @@ var Run = class {
2020
2743
  args: point.args,
2021
2744
  result: summarize(value)
2022
2745
  });
2023
- if (inv.isCrashed()) return hang();
2024
- const after = this.faultAfter(point, inv, fault);
2746
+ if (owner().isCrashed()) return hang();
2747
+ const after = this.faultAfter(point, owner(), fault, enclosing);
2025
2748
  if (after === "crashed") return dead();
2026
2749
  if (after) throw after;
2027
2750
  return value;
2028
2751
  }
2029
2752
  /** A fault decided before the effect performs: the crash it is, the error to throw, or nothing. */
2030
- faultBefore(point, inv, fault) {
2753
+ /**
2754
+ * A fault decided before the effect performs: the crash it is, the error to
2755
+ * throw, or nothing. The crash names the effect the point is nested in
2756
+ * (an object's call the crash happened inside, which `dead` then abandons,
2757
+ * resetting the object), so it is not handed to the object (`adoptInFlight`).
2758
+ */
2759
+ faultBefore(point, inv, fault, enclosing) {
2031
2760
  if (fault === "crash_before" || fault === "cut_off") {
2032
2761
  this.recordFault(point, fault);
2033
- inv.crash();
2762
+ inv.crash(enclosing);
2034
2763
  return "crashed";
2035
2764
  }
2036
2765
  if (fault === "error") {
@@ -2040,10 +2769,10 @@ var Run = class {
2040
2769
  return null;
2041
2770
  }
2042
2771
  /** A fault decided after the effect committed: the crash it is, the error to throw, or nothing. */
2043
- faultAfter(point, inv, fault) {
2772
+ faultAfter(point, inv, fault, enclosing) {
2044
2773
  if (fault === "crash_after") {
2045
2774
  this.recordFault(point, fault);
2046
- inv.crash();
2775
+ inv.crash(enclosing);
2047
2776
  return "crashed";
2048
2777
  }
2049
2778
  if (fault === "ambiguous") {
@@ -2088,16 +2817,56 @@ var Run = class {
2088
2817
  unsupported(reason) {
2089
2818
  this.reasons.push(reason);
2090
2819
  }
2820
+ attempt(invocation, code, deadlineMs) {
2821
+ const cell = { late: deadlineMs <= 0 };
2822
+ let giveUp = () => {};
2823
+ const late = new Promise((resolve) => {
2824
+ giveUp = () => {
2825
+ cell.late = true;
2826
+ resolve();
2827
+ };
2828
+ });
2829
+ if (cell.late) giveUp();
2830
+ const value = attemptScope ? attemptScope.run(cell, code) : code();
2831
+ const clock = this.patched?.clock;
2832
+ if (!cell.late && clock) {
2833
+ const timer = clock.setTimeoutAs(invocation, giveUp, deadlineMs);
2834
+ const clear = () => clock.clear(timer);
2835
+ if (isThenable(value)) Promise.resolve(value).then(clear, clear);
2836
+ else clear();
2837
+ }
2838
+ return {
2839
+ value,
2840
+ late
2841
+ };
2842
+ }
2843
+ /**
2844
+ * The attempt whose code is running now, by its async context or, where the
2845
+ * runtime carries none (an object's code), by the effect it runs inside of.
2846
+ * Read live where it is kept: an attempt may become late after its effect
2847
+ * parked or entered an object.
2848
+ */
2849
+ attemptNow(...frames) {
2850
+ return attemptScope?.getStore() ?? frames.find((f) => f?.attempt)?.attempt;
2851
+ }
2091
2852
  settle(promise, invocation) {
2092
2853
  const inv = this.invocation(invocation);
2093
- if (this.concurrent) return Promise.race([promise, inv.crashed.then(() => hang())]);
2854
+ if (this.concurrent) return Promise.race([promise, new Promise((_, reject) => {
2855
+ if (inv.isCrashed()) reject(new CrashSignal(inv.id));
2856
+ else this.crashWatch.push({
2857
+ inv,
2858
+ reject
2859
+ });
2860
+ })]);
2094
2861
  const patched = this.patched;
2095
2862
  if (!this.hosts.has(invocation)) this.runAs(invocation);
2096
2863
  if (!patched) return Promise.race([promise, inv.crashed.then(() => hang())]);
2097
2864
  return settleOn(promise, {
2098
2865
  clock: patched.clock,
2099
- inFlight: () => this.frames.inFlight + this.hostedBy(invocation),
2866
+ inFlight: () => this.frames.inFlight + this.hostedBy(invocation) + this.firedPending(),
2867
+ idle: () => this.hostedBy(invocation) > 0 ? null : this.timersAllowed(),
2100
2868
  crashed: () => inv.isCrashed(),
2869
+ crashError: () => new CrashSignal(invocation),
2101
2870
  stuck: () => {
2102
2871
  this.unsupported(waitingUnseen(invocation));
2103
2872
  inv.crash();
@@ -2131,7 +2900,8 @@ var Run = class {
2131
2900
  }
2132
2901
  };
2133
2902
  const asHandler = () => this.patched ? this.patched.handlerCode(run) : run();
2134
- return deliveryScope.run({ id }, asHandler);
2903
+ const unhosted = () => hostScope ? hostScope.run(void 0, asHandler) : asHandler();
2904
+ return deliveryScope.run({ id }, unhosted);
2135
2905
  }
2136
2906
  /** How many invocations are hosted inside effects of `invocation` now. */
2137
2907
  hostedBy(invocation) {
@@ -2169,16 +2939,57 @@ var Run = class {
2169
2939
  * path gives, before it counts as idle.
2170
2940
  */
2171
2941
  quiesce() {
2942
+ this.releaseCrashed();
2172
2943
  return this.turns.quiesce();
2173
2944
  }
2174
2945
  /**
2175
- * Concurrent runs: pick the next turn among the parked invocations and,
2176
- * when `canStart`, starting the next event. Parked invocations are ordered
2177
- * by start, then by when they parked, so the pick does not depend on
2178
- * real-time arrival. Returns what was picked; "turn" has already released it.
2946
+ * Concurrent runs: settles waiting on invocations that have crashed since
2947
+ * are released, on the run's own step. Returns the invocations released.
2948
+ */
2949
+ releaseCrashed() {
2950
+ const released = /* @__PURE__ */ new Set();
2951
+ if (this.crashWatch.length === 0) return released;
2952
+ const waiting = this.crashWatch;
2953
+ this.crashWatch = [];
2954
+ for (const w of waiting) if (w.inv.isCrashed()) {
2955
+ w.reject(new CrashSignal(w.inv.id));
2956
+ released.add(w.inv.id);
2957
+ } else this.crashWatch.push(w);
2958
+ return released;
2959
+ }
2960
+ /**
2961
+ * Concurrent runs: pick the next turn among the parked invocations, when
2962
+ * `canStart` starting the next event, and the earliest virtual timer
2963
+ * already due that may fire now (`timersAllowed`; with `afterWorkOnly`,
2964
+ * only an object's work after its answer's, as `fireAfterWorkTimer`).
2965
+ * Parked invocations are ordered by start, then by when they parked, so
2966
+ * the pick does not depend on real-time arrival; timers keep their due
2967
+ * order among themselves. `canWait`: whether the loop could let time pass
2968
+ * if nothing were parked; while only late turns are, it is an option
2969
+ * (`Turns.takeTurn`). Returns what was picked; "turn" has already
2970
+ * released it, "timer" fired it, and "none" leaves the loop to let time
2971
+ * pass or give up.
2179
2972
  */
2180
- takeTurn(canStart) {
2181
- return this.turns.takeTurn(canStart);
2973
+ takeTurn(canStart, afterWorkOnly = false, canWait = false) {
2974
+ return this.turns.takeTurn(canStart, this.dueTimer(afterWorkOnly), canWait);
2975
+ }
2976
+ /** The earliest timer already due (at or before the virtual now) that may fire now, as a turn. */
2977
+ dueTimer(afterWorkOnly) {
2978
+ const clock = this.patched?.clock;
2979
+ const allowed = this.timersAllowed();
2980
+ if (!clock || !allowed) return void 0;
2981
+ const alive = afterWorkOnly ? this.aliveAfterWork() : null;
2982
+ const owned = alive ? (owner) => owner !== null && alive.has(owner) && allowed(owner) : allowed;
2983
+ const due = clock.nextDueOwned(owned);
2984
+ if (due === void 0 || due > clock.now()) return void 0;
2985
+ const owner = clock.nextOwnerOwned(owned) ?? null;
2986
+ return {
2987
+ owner,
2988
+ fired: this.timersFired.get(owner) ?? 0,
2989
+ fire: () => {
2990
+ this.fireOwned(owned);
2991
+ }
2992
+ };
2182
2993
  }
2183
2994
  /**
2184
2995
  * Let virtual time pass until `at`: timers due by then fire first, in due
@@ -2189,41 +3000,63 @@ var Run = class {
2189
3000
  const clock = this.patched?.clock;
2190
3001
  if (!clock) return false;
2191
3002
  let fired = false;
2192
- for (let due = clock.nextDue(); due !== void 0 && due <= at; due = clock.nextDue()) {
2193
- this.fireNextTimer(clock);
3003
+ for (;;) {
3004
+ const allowed = this.timersAllowed();
3005
+ const due = allowed ? clock.nextDueOwned(allowed) : void 0;
3006
+ if (!allowed || due === void 0 || due > at) break;
3007
+ this.fireOwned(allowed);
2194
3008
  fired = true;
2195
- do
2196
- await eventLoopTurn();
2197
- while (this.frames.inFlight > 0);
3009
+ await this.rest();
2198
3010
  }
2199
3011
  clock.advance(at - clock.now());
2200
3012
  return fired;
2201
3013
  }
2202
- /** When the next virtual timer is due, or undefined when none is pending. */
2203
- nextTimerDue() {
2204
- return this.patched?.clock.nextDue();
2205
- }
2206
- /** Concurrent runs: fire the next due timer as the invocation that set it. False when none is pending. */
2207
- fireTimer() {
3014
+ /**
3015
+ * When the next virtual timer is due, or undefined when none is pending;
3016
+ * `afterWorkOnly` counts the timers of objects' work after answers alone,
3017
+ * the ones that fire while only such work is alive.
3018
+ */
3019
+ nextTimerDue(afterWorkOnly = false) {
2208
3020
  const clock = this.patched?.clock;
2209
- if (!clock || clock.nextOwner() === void 0) return false;
2210
- return this.fireNextTimer(clock);
3021
+ if (!clock) return void 0;
3022
+ if (!afterWorkOnly) {
3023
+ const allowed = this.timersAllowed();
3024
+ return allowed ? clock.nextDueOwned(allowed) : void 0;
3025
+ }
3026
+ const alive = this.aliveAfterWork();
3027
+ return clock.nextDueOwned((owner) => owner !== null && alive.has(owner));
2211
3028
  }
2212
- /** Fire the next due timer as the invocation that set it (a step of a concurrent run). */
2213
- fireNextTimer(clock) {
2214
- this.runAs(clock.nextOwner() ?? null);
2215
- if (this.concurrent) this.turns.step();
2216
- return clock.fireNext();
3029
+ /** The ids of continuations alive now. */
3030
+ aliveAfterWork() {
3031
+ const alive = /* @__PURE__ */ new Set();
3032
+ for (const cont of this.afterWork) if (!cont.isCrashed()) alive.add(cont.id);
3033
+ return alive;
3034
+ }
3035
+ /**
3036
+ * Concurrent runs: fire the next due timer that may fire now
3037
+ * (`timersAllowed`) as the invocation that set it. False when none is.
3038
+ */
3039
+ fireTimer() {
3040
+ const allowed = this.timersAllowed();
3041
+ return allowed !== null && this.fireOwned(allowed) !== void 0;
2217
3042
  }
2218
3043
  /**
2219
3044
  * Concurrent runs: nothing can make progress; abandon these invocations so
2220
- * the run can end. Returns how many were still alive.
3045
+ * the run can end. Returns how many were still alive, or whose delivery
3046
+ * ends now: one that crashed inside an object (the object's reset tears
3047
+ * down the task the crash settled its promise in, so the delivery never
3048
+ * saw it) has its settle released here, on the run's own step.
2221
3049
  */
2222
3050
  abandon(ids) {
2223
3051
  let abandoned = 0;
3052
+ const released = this.releaseCrashed();
2224
3053
  for (const id of ids) {
2225
3054
  const inv = this.invocations.get(id);
2226
- if (!inv || inv.isCrashed()) continue;
3055
+ if (!inv) continue;
3056
+ if (inv.isCrashed()) {
3057
+ if (released.has(id)) abandoned++;
3058
+ continue;
3059
+ }
2227
3060
  this.unsupported(waitingUnseen(id));
2228
3061
  inv.crash();
2229
3062
  abandoned++;
@@ -2255,18 +3088,22 @@ var Run = class {
2255
3088
  * Run user code as an invocation: under `RunHooks.settle` (real I/O
2256
3089
  * completes, timers fire while it is idle) and ended as "crashed" when an
2257
3090
  * injected fault crashes the invocation, whether the code saw the crash as
2258
- * a `CrashSignal` or an effect of its hung, as "errored" when it threw
2259
- * anything else.
3091
+ * a `CrashSignal`, an effect of its hung (the settle then rejects with the
3092
+ * signal, on the run's own tick), the invocation's `crashed` settled, or
3093
+ * the code returned or threw anything else after the crash (an object's
3094
+ * reset rejecting the call into it with an error of the runtime's); as
3095
+ * "errored" when it threw anything else.
2260
3096
  */
2261
3097
  async function runInvocation(hooks, inv, work) {
2262
- const outcome = Promise.resolve().then(work).then((value) => ({
3098
+ const crashed = { status: "crashed" };
3099
+ const outcome = Promise.resolve().then(work).then((value) => inv.isCrashed() ? crashed : {
2263
3100
  status: "completed",
2264
3101
  value
2265
- }), (error) => error instanceof CrashSignal ? { status: "crashed" } : {
3102
+ }, (error) => error instanceof CrashSignal || inv.isCrashed() ? crashed : {
2266
3103
  status: "errored",
2267
3104
  error
2268
3105
  });
2269
- return Promise.race([hooks.settle(outcome, inv.id), inv.crashed.then(() => ({ status: "crashed" }))]);
3106
+ return Promise.race([hooks.settle(outcome, inv.id).catch((error) => error instanceof CrashSignal ? crashed : Promise.reject(error)), inv.crashed.then(() => crashed)]);
2270
3107
  }
2271
3108
  /**
2272
3109
  * Run user code as an invocation of its own inside the effect being performed
@@ -2283,6 +3120,28 @@ function hostInvocation(hooks, id, work) {
2283
3120
  if (!(hooks instanceof Run)) throw new Error("hostInvocation needs the engine's run");
2284
3121
  return hooks.hosted(id, work);
2285
3122
  }
3123
+ /**
3124
+ * Record a platform action that performs nothing: a marker in the log (a
3125
+ * message dead-lettered, a caller that gave up, a Workflow step's result).
3126
+ * Under faults it can crash the invocation like any effect; most admit none.
3127
+ */
3128
+ function note(hooks, point) {
3129
+ hooks.effectSync(point, () => null, () => null);
3130
+ }
3131
+ /**
3132
+ * Perform a decision of the platform's own (an implicit ack, a delete)
3133
+ * under the faults around a decision: it stands, or an injected crash
3134
+ * ended the invocation at that point.
3135
+ */
3136
+ function decide(hooks, point, perform, summarize) {
3137
+ try {
3138
+ hooks.effectSync(point, perform, summarize);
3139
+ return "decided";
3140
+ } catch (err) {
3141
+ if (err instanceof CrashSignal) return "crashed";
3142
+ throw err;
3143
+ }
3144
+ }
2286
3145
  // packages/engine/src/exhaustive.ts
2287
3146
  /**
2288
3147
  * Exhaustive exploration: every schedule within the bounds, each once. A
@@ -2296,8 +3155,9 @@ function hostInvocation(hooks, id, work) {
2296
3155
  * Reduction, when on, uses sleep sets (Godefroid, Partial-Order Methods for
2297
3156
  * the Verification of Concurrent Systems, 1996): two turns of different
2298
3157
  * invocations whose effects have different targets commute, so after one
2299
- * order of them has been explored the other is not. Starting an event is
2300
- * dependent on everything. A run whose every option is asleep repeats an
3158
+ * order of them has been explored the other is not. Starting an event and
3159
+ * firing a timer already due are dependent on everything (their options
3160
+ * have no target), so what they run is never reordered. A run whose every option is asleep repeats an
2301
3161
  * explored order; it still runs (the choices are forced up to it) but is not
2302
3162
  * counted as a schedule and nothing below it is explored.
2303
3163
  */
@@ -2518,7 +3378,7 @@ const engineAssumptions = [
2518
3378
  "schedule points are effect boundaries: proxied bindings, patched timers and fetch; other awaits run in program order",
2519
3379
  "faults: crash_before, crash_after, ambiguous, error at any effect point; redelivery per the platform's queue model",
2520
3380
  "Date, Math.random, crypto.randomUUID, crypto.getRandomValues, performance.now and timers are virtualised per run from the seed; time starts at 2026-01-01T00:00:00Z and advances 1 ms per effect and to each timer's due time",
2521
- "timers fire only while the invocation is idle (no effect in flight), in due order; an invocation waiting on something outside Eutaxy makes the run UNSUPPORTED",
3381
+ "timers fire in due order; one at a time, only while the invocation is idle (no effect in flight); with several in flight, as the concurrency assumption says; an invocation waiting on something outside Eutaxy makes the run UNSUPPORTED",
2522
3382
  "an effect whose real I/O takes longer than the time budget (the scenario's budgetMs, or the budgetMs option replacing it) is treated as hung: the run is UNSUPPORTED and names the effect",
2523
3383
  "while an effect performs real I/O, timers the library schedules inside that I/O are real (backoff, timeouts) and timers the handler schedules meanwhile stay virtual, told apart by async context; without async context support every timer stays virtual",
2524
3384
  "module-level state cannot be reset between runs; before BOUNDED the first runs are replayed in reverse order and any difference makes the run UNSUPPORTED (module_state_leak)",
@@ -2527,13 +3387,7 @@ const engineAssumptions = [
2527
3387
  /** What a verdict rests on about concurrency, for these bounds. */
2528
3388
  function concurrencyAssumption(bounds) {
2529
3389
  if (bounds.maxConcurrentInvocations === 1) return "one invocation at a time (maxConcurrentInvocations = 1)";
2530
- return `up to ${bounds.maxConcurrentInvocations} invocations in flight, interleaved only at asynchronous effects (proxied bindings, fetch): code between two such effects runs without interruption (except continuations of a promise it settles for another invocation, which run then and are still attributed to their own invocation), Web Crypto calls are waited for like I/O, other non-effect awaits (body reads included) settle within one turn of the event loop, synchronous effects are not interleaving points, an effect made by code another effect hosts (an object calling out during a call) is a turn of its own unless that code cannot be interrupted (an object inside blockConcurrencyWhile), when it runs within the hosting effect's turn, the next turn is a seeded pick among parked invocations, whether a new event starts while a slot is free is a seeded pick too, and timers fire only when no invocation can take a turn`;
2531
- }
2532
- /** The pending event to deliver next: the earliest by `at`, then the first queued. */
2533
- function nextEvent(pending) {
2534
- let best = 0;
2535
- for (let i = 1; i < pending.length; i++) if ((pending[i]?.at ?? 0) < (pending[best]?.at ?? 0)) best = i;
2536
- return best;
3390
+ return `up to ${bounds.maxConcurrentInvocations} invocations in flight, interleaved only at asynchronous effects (proxied bindings, fetch): code between two such effects runs without interruption (except continuations of a promise it settles for another invocation, which run then and are still attributed to their own invocation), Web Crypto calls are waited for like I/O, other non-effect awaits (body reads included) settle within one turn of the event loop, synchronous effects are not interleaving points, an effect made by code another effect hosts (an object calling out during a call) is a turn of its own unless that code cannot be interrupted (an object inside blockConcurrencyWhile), when it runs within the hosting effect's turn, the next turn is a seeded pick among parked invocations, starting a new event while a slot is free, and firing the earliest timer already due (at or before the virtual now, which effects advance), timers firing in due order among themselves, and a timer not yet due fires (virtual time passing to it) only when nothing else can move`;
2537
3391
  }
2538
3392
  /** The first record a replay recorded differently from the run, or how their lengths differ; null when the logs match. */
2539
3393
  function whatDiffered(run, replay) {
@@ -2562,17 +3416,19 @@ function explorationAssumption(options) {
2562
3416
  async function deliverInOrder(spec, platform, run) {
2563
3417
  const pending = [...platform.initialEvents(spec)];
2564
3418
  while (pending.length > 0) {
2565
- const [event] = pending.splice(nextEvent(pending), 1);
3419
+ const [event] = pending.splice(earliestEvent(pending), 1);
2566
3420
  if (event.at !== void 0) await run.advanceTo(event.at);
2567
3421
  const result = await platform.deliver(event, run, spec);
3422
+ await run.driveAfterWork();
2568
3423
  pending.push(...run.takeQueued(), ...result.followUps);
2569
3424
  }
2570
3425
  }
2571
3426
  /**
2572
3427
  * Deliver events with up to `maxConcurrentInvocations` in flight. Each turn
2573
3428
  * is a seeded pick: one parked invocation performs its effect and runs to
2574
- * its next one, or, while a slot is free, the next event starts. When
2575
- * nothing is parked and no event can start a timer fires, and when nothing
3429
+ * its next one, while a slot is free the next event starts, or a timer
3430
+ * already due fires. When nothing is parked, no event can start and no
3431
+ * timer is due, the next timer fires (time passes to it), and when nothing
2576
3432
  * can move the remaining invocations are abandoned.
2577
3433
  */
2578
3434
  async function deliverConcurrently(spec, platform, run) {
@@ -2588,11 +3444,15 @@ async function deliverConcurrently(spec, platform, run) {
2588
3444
  active = active.filter((d) => !d.outcome);
2589
3445
  pending.push(...run.takeQueued());
2590
3446
  if (pending.length > queuedBefore) run.queuedEvents();
2591
- if (active.length === 0 && pending.length === 0) return;
2592
- const next = pending.length > 0 ? nextEvent(pending) : -1;
2593
- const due = next >= 0 && (pending[next]?.at ?? 0) <= run.now();
3447
+ if (active.length === 0 && pending.length === 0 && !run.hasAfterWork()) return;
3448
+ const next = pending.length > 0 ? earliestEvent(pending) : -1;
3449
+ const eventAt = pending[next]?.at ?? 0;
3450
+ const due = next >= 0 && eventAt <= run.now();
2594
3451
  const canStart = active.length < spec.bounds.maxConcurrentInvocations && due;
2595
- const turn = run.takeTurn(canStart);
3452
+ const afterWorkOnly = active.length === 0 && run.hasAfterWork();
3453
+ const timerDue = run.nextTimerDue(afterWorkOnly);
3454
+ const untilEvent = next >= 0 && !due && active.length < spec.bounds.maxConcurrentInvocations && (timerDue ?? Number.POSITIVE_INFINITY) > eventAt;
3455
+ const turn = run.takeTurn(canStart, afterWorkOnly, untilEvent || timerDue !== void 0);
2596
3456
  if (turn === "start") {
2597
3457
  const [event] = pending.splice(next, 1);
2598
3458
  const d = {
@@ -2607,9 +3467,9 @@ async function deliverConcurrently(spec, platform, run) {
2607
3467
  run.rested();
2608
3468
  });
2609
3469
  active.push(d);
2610
- } else if (turn === "none" && next >= 0 && !due && active.length < spec.bounds.maxConcurrentInvocations && (run.nextTimerDue() ?? Number.POSITIVE_INFINITY) > (pending[next]?.at ?? 0)) {
2611
- if (!await run.advanceTo(pending[next]?.at ?? 0)) continue;
2612
- } else if (turn === "none" && !run.fireTimer()) {
3470
+ } else if (turn === "none" && untilEvent) {
3471
+ if (!await run.advanceTo(eventAt)) continue;
3472
+ } else if (turn === "none" && !(active.length > 0 || !run.hasAfterWork() ? run.fireTimer() : run.fireAfterWorkTimer()) && run.settleAfterWork() === 0) {
2613
3473
  const stuck = active.flatMap((d) => d.started.invocation() ?? []);
2614
3474
  if (run.abandon(stuck) === 0) throw new Error(`the ${platform.name} platform's delivery made no progress and cannot be abandoned`);
2615
3475
  }
@@ -2783,11 +3643,14 @@ async function explore(scenario, platform, options) {
2783
3643
  }
2784
3644
  // packages/engine/src/differential.ts
2785
3645
  /**
2786
- * The platform-neutral half of a differential check: the same fault-free
2787
- * scenario once through Eutaxy (this module) and once against the raw
2788
- * bindings (each platform's own, sharing no proxy code), then a comparison
2789
- * of what each attempt decided and of the final state. Any difference is a
2790
- * bug in the proxies or the platform model, not in the handler.
3646
+ * The platform-neutral part of a differential check: the same fault-free
3647
+ * scenario once through Eutaxy and once against the raw bindings, then a
3648
+ * comparison of what each attempt decided and of the final state. Any
3649
+ * difference is a bug in the proxies or the platform model, not in the
3650
+ * handler. The raw side's loop is here too (the same virtual globals and
3651
+ * scripted externals as the proxied side, the same pick of the next event
3652
+ * and the same redelivery rule); a platform writes only how one raw attempt
3653
+ * calls its handler, sharing no proxy code.
2791
3654
  */
2792
3655
  /** The raw side cannot abandon an invocation the way the engine does; a stuck handler ends the comparison. */
2793
3656
  var DifferentialStuck = class extends Error {
@@ -2835,6 +3698,73 @@ async function proxiedSide(spec, platform, attempt) {
2835
3698
  unsupported: run.unsupportedReasons
2836
3699
  };
2837
3700
  }
3701
+ /**
3702
+ * The raw side: every event delivered as the engine would deliver it with
3703
+ * no faults and one invocation at a time (the earliest due first, time
3704
+ * moved to a delayed one, an unhandled one delivered again under core's
3705
+ * redelivery rule), each attempt performed by the platform. The attempts'
3706
+ * records, in order.
3707
+ */
3708
+ async function rawRun(spec, side) {
3709
+ const patched = patchGlobals(0);
3710
+ const reasons = [];
3711
+ const unsupported = (reason) => {
3712
+ reasons.push(reason);
3713
+ };
3714
+ const restoreFetch = installScriptedFetch(spec.externals, null, unsupported, () => patched.clock.advance(1));
3715
+ const io = { n: 0 };
3716
+ const settle = (promise) => settleOn(promise, {
3717
+ clock: patched.clock,
3718
+ inFlight: () => io.n,
3719
+ crashed: () => false,
3720
+ stuck: () => {
3721
+ throw new DifferentialStuck();
3722
+ }
3723
+ });
3724
+ const call = async (code) => {
3725
+ try {
3726
+ return {
3727
+ status: "completed",
3728
+ value: await settle(Promise.resolve().then(code))
3729
+ };
3730
+ } catch (error) {
3731
+ if (error instanceof DifferentialStuck) throw error;
3732
+ return {
3733
+ status: "errored",
3734
+ error
3735
+ };
3736
+ }
3737
+ };
3738
+ const attempts = [];
3739
+ const pending = [...side.events];
3740
+ let restore;
3741
+ try {
3742
+ const installed = side.install({
3743
+ clock: patched.clock,
3744
+ io,
3745
+ libraryIo: (perform) => patched.libraryIo(perform),
3746
+ unsupported,
3747
+ settle,
3748
+ call
3749
+ });
3750
+ restore = installed.restore;
3751
+ const { attempt } = installed;
3752
+ while (pending.length > 0) {
3753
+ const [event] = pending.splice(earliestEvent(pending), 1);
3754
+ if (event.at !== void 0 && event.at > patched.clock.now()) patched.clock.advance(event.at - patched.clock.now());
3755
+ const { record, handled } = await attempt(event);
3756
+ attempts.push(record);
3757
+ const next = handled ? null : redelivery(event, side.limit, spec.bounds);
3758
+ if (next) pending.push(next);
3759
+ }
3760
+ } finally {
3761
+ restore?.();
3762
+ restoreFetch();
3763
+ patched.restore();
3764
+ }
3765
+ if (reasons.length > 0) throw new DifferentialStuck(`raw side: ${reasons.join("; ")}`);
3766
+ return attempts;
3767
+ }
2838
3768
  /** Every difference between the two sides, one readable entry each; none means they agree. */
2839
3769
  function compareSides(eutaxy, raw, unsupported) {
2840
3770
  const differences = [];
@@ -2929,6 +3859,6 @@ function observeCore(namespace, functions) {
2929
3859
  }
2930
3860
  };
2931
3861
  }
2932
- export { readFaults as A, patchProperty as C, checkInvariant as D, validateScenario as E, seedPrng as F, getPath as I, canonicalJson as L, nextFloat as M, nextInt as N, checkInvariants as O, nextU32 as P, virtualEpoch as S, defaultBounds as T, toResponse as _, explore as a, realTick as b, hostInvocation as c, InjectedEffectError as d, findResponse as f, replyOf as g, parseBody as h, proxiedSide as i, writeFaults as j, decisionFaults as k, runInvocation as l, isRedirect as m, DifferentialStuck as n, replay as o, installScriptedFetch as p, compareSides as r, restrictSpec as s, observeCore as t, CrashSignal as u, withoutNetwork as v, toJson as w, settleOn as x, patchGlobals as y };
3862
+ export { writeFaults as A, toJson as C, checkInvariants as D, checkInvariant as E, getPath as F, invocationOf as I, redelivery as L, nextInt as M, nextU32 as N, decisionFaults as O, seedPrng as P, canonicalJson as R, patchProperty as S, validateScenario as T, replyOf as _, explore as a, realTick as b, decide as c, runInvocation as d, CrashSignal as f, parseBody as g, isRedirect as h, rawRun as i, nextFloat as j, readFaults as k, hostInvocation as l, findResponse as m, compareSides as n, replay as o, InjectedEffectError as p, proxiedSide as r, restrictSpec as s, observeCore as t, note as u, toResponse as v, defaultBounds as w, virtualEpoch as x, withoutNetwork as y };
2933
3863
 
2934
- //# sourceMappingURL=src-CPuihHZh.mjs.map
3864
+ //# sourceMappingURL=src-CmHdPsZy.mjs.map