eutaxy 0.18.0 → 0.19.1

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 (75) hide show
  1. package/README.md +15 -12
  2. package/dist/aws.d.mts +3 -3
  3. package/dist/aws.d.mts.map +1 -1
  4. package/dist/aws.mjs +13 -4
  5. package/dist/aws.mjs.map +1 -1
  6. package/dist/bin.mjs +1 -1
  7. package/dist/check-zkHLdWyf.mjs +1281 -0
  8. package/dist/check-zkHLdWyf.mjs.map +1 -0
  9. package/dist/cli-Bxjvq4p9.mjs +297 -0
  10. package/dist/cli-Bxjvq4p9.mjs.map +1 -0
  11. package/dist/cli.d.mts.map +1 -1
  12. package/dist/cli.mjs +1 -1
  13. package/dist/cloudflare.d.mts +38 -6
  14. package/dist/cloudflare.d.mts.map +1 -1
  15. package/dist/cloudflare.mjs +6466 -3
  16. package/dist/cloudflare.mjs.map +1 -0
  17. package/dist/{delivery-invariants-D-_GPOqE.d.mts → delivery-invariants-C3GXJIbg.d.mts} +2 -2
  18. package/dist/{delivery-invariants-D-_GPOqE.d.mts.map → delivery-invariants-C3GXJIbg.d.mts.map} +1 -1
  19. package/dist/{delivery-invariants-BRwfZJrs.mjs → delivery-invariants-DsBHpT1n.mjs} +2 -2
  20. package/dist/{delivery-invariants-BRwfZJrs.mjs.map → delivery-invariants-DsBHpT1n.mjs.map} +1 -1
  21. package/dist/draft-DEUDffHa.mjs +467 -0
  22. package/dist/draft-DEUDffHa.mjs.map +1 -0
  23. package/dist/{src-H1Q8ytEx.mjs → generate-TBJM3-2P.mjs} +3 -618
  24. package/dist/generate-TBJM3-2P.mjs.map +1 -0
  25. package/dist/index.d.mts +36 -36
  26. package/dist/index.d.mts.map +1 -1
  27. package/dist/index.mjs +6 -3
  28. package/dist/index.mjs.map +1 -1
  29. package/dist/install-DkzpGA5D.mjs +611 -0
  30. package/dist/install-DkzpGA5D.mjs.map +1 -0
  31. package/dist/{explore-D33RP9hF.d.mts → ir-KpC2epGn.d.mts} +70 -70
  32. package/dist/ir-KpC2epGn.d.mts.map +1 -0
  33. package/dist/keys-xtanNmuR.mjs +111 -0
  34. package/dist/keys-xtanNmuR.mjs.map +1 -0
  35. package/dist/mcp-DEn3HnLz.mjs +539 -0
  36. package/dist/mcp-DEn3HnLz.mjs.map +1 -0
  37. package/dist/{platform-CawKCUru.d.mts → platform-Cs9V9t2k.d.mts} +25 -11
  38. package/dist/platform-Cs9V9t2k.d.mts.map +1 -0
  39. package/dist/pool-CXN4CwGY.mjs +61 -0
  40. package/dist/pool-CXN4CwGY.mjs.map +1 -0
  41. package/dist/{provers-DS44OeEm.mjs → provers-D8VaY_OM.mjs} +18 -2
  42. package/dist/provers-D8VaY_OM.mjs.map +1 -0
  43. package/dist/reader-B9FSoEYW.mjs +1 -0
  44. package/dist/reader-Cz6_bLf6.mjs +3774 -0
  45. package/dist/reader-Cz6_bLf6.mjs.map +1 -0
  46. package/dist/report-_Vzavqg0.mjs +310 -0
  47. package/dist/report-_Vzavqg0.mjs.map +1 -0
  48. package/dist/src-B2DpVbMN.mjs +2 -0
  49. package/dist/src-BFGTvuA_.mjs +1235 -0
  50. package/dist/src-BFGTvuA_.mjs.map +1 -0
  51. package/dist/src-BtLZPRyG.mjs +120 -0
  52. package/dist/src-BtLZPRyG.mjs.map +1 -0
  53. package/dist/src-CB8DcvsK.mjs +1 -0
  54. package/dist/src-COuquJvI.mjs +269 -0
  55. package/dist/src-COuquJvI.mjs.map +1 -0
  56. package/dist/src-Chn-m_r1.mjs +1082 -0
  57. package/dist/src-Chn-m_r1.mjs.map +1 -0
  58. package/dist/{src-Whn0RMSh.mjs → src-D-MeEFn3.mjs} +589 -517
  59. package/dist/src-D-MeEFn3.mjs.map +1 -0
  60. package/dist/src-DwYD3QQJ.mjs +346 -0
  61. package/dist/src-DwYD3QQJ.mjs.map +1 -0
  62. package/dist/toolchain-DWfymxAJ.mjs +80 -0
  63. package/dist/toolchain-DWfymxAJ.mjs.map +1 -0
  64. package/dist/verdict-evEM5Gxx.mjs +12 -0
  65. package/dist/verdict-evEM5Gxx.mjs.map +1 -0
  66. package/package.json +4 -1
  67. package/dist/cli-DyA7uTBg.mjs +0 -9447
  68. package/dist/cli-DyA7uTBg.mjs.map +0 -1
  69. package/dist/explore-D33RP9hF.d.mts.map +0 -1
  70. package/dist/platform-CawKCUru.d.mts.map +0 -1
  71. package/dist/provers-DS44OeEm.mjs.map +0 -1
  72. package/dist/src-H1Q8ytEx.mjs.map +0 -1
  73. package/dist/src-Whn0RMSh.mjs.map +0 -1
  74. package/dist/workerd-tI8INa6v.mjs +0 -6334
  75. package/dist/workerd-tI8INa6v.mjs.map +0 -1
@@ -1,35 +1,28 @@
1
- // packages/core/src/canonical-json.ts
2
- function canonicalJson(value) {
3
- if (value === null) return "null";
4
- switch (typeof value) {
5
- case "boolean": return value ? "true" : "false";
6
- case "number":
7
- if (!Number.isFinite(value)) throw new TypeError(`non-finite number: ${value}`);
8
- return Object.is(value, -0) ? "0" : JSON.stringify(value);
9
- case "string": return JSON.stringify(value);
10
- case "object": {
11
- if (Array.isArray(value)) {
12
- const items = [];
13
- for (let i = 0; i < value.length; i++) {
14
- const v = value[i];
15
- if (v === void 0) throw new TypeError(`hole or undefined at index ${i}`);
16
- items.push(canonicalJson(v));
17
- }
18
- return `[${items.join(",")}]`;
19
- }
20
- const keys = Object.keys(value).sort();
21
- const parts = [];
22
- for (const k of keys) {
23
- const v = value[k];
24
- if (v === void 0) throw new TypeError(`undefined at key ${JSON.stringify(k)}`);
25
- parts.push(`${JSON.stringify(k)}:${canonicalJson(v)}`);
26
- }
27
- return `{${parts.join(",")}}`;
28
- }
29
- default: throw new TypeError(`not JSON data: ${typeof value}`);
30
- }
1
+ import { a as serializeLog, i as seedPrng, n as nextInt, o as canonicalJson, r as nextU32, t as nextFloat } from "./src-BtLZPRyG.mjs";
2
+ // packages/core/src/delivery-model.ts
3
+ /**
4
+ * The model of delivery that Eutaxy proves: how often an event is
5
+ * delivered under the redelivery rule every platform shares. An attempt
6
+ * that was not handled is delivered again while the platform's own limit
7
+ * on redeliveries and the scenario's bound both leave room. Written in the
8
+ * subset the Lean engine translates, so what is proved is this code. The
9
+ * rule, `redelivers`, is also the code that runs: `redelivery` in
10
+ * delivery.ts decides by it. The count, `deliveries`, models the loops
11
+ * that deliver, which are the platforms' own code; delivery.test.ts
12
+ * holds a loop over `redelivery` to it on every case up to a bound. The
13
+ * helpers below state the claims.
14
+ */
15
+ /** Whether an attempt that was not handled is delivered again: not once the redeliveries so far, `attempt - 1`, have reached either limit. */
16
+ function redelivers(attempt, limit, maxRedeliveries) {
17
+ return !(attempt - 1 >= limit || attempt - 1 >= maxRedeliveries);
31
18
  }
32
19
  // packages/core/src/delivery.ts
20
+ /**
21
+ * The delivery conventions every platform shares, and the differential
22
+ * runner's raw sides with them: how an attempt names its invocation, which
23
+ * pending event is delivered next, and the redelivery rule, which applies
24
+ * the same reading of a platform's limit without any of its proxy code.
25
+ */
33
26
  /** The invocation one attempt of an event runs as: `<event>#<attempt>`, so a schedule's faults stay keyed when other events are removed. */
34
27
  function invocationOf(event) {
35
28
  return `${event.id}#${event.attempt}`;
@@ -49,19 +42,26 @@ function earliestEvent(pending) {
49
42
  * acknowledged or deleted, a request its caller resends, an alarm that
50
43
  * failed), or null when it is dropped (dead-lettered, given up on). It is
51
44
  * delivered again while both the platform's own limit on redeliveries
52
- * (Queues' `max_retries`, the caller's `retries`, SQS's `maxReceiveCount`
45
+ * (Queues' `max_retries`, a drive's `retries`, SQS's `maxReceiveCount`
53
46
  * 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.
47
+ * `maxRedeliveries` leave room, which `redelivers` decides: the rule of the
48
+ * delivery model, whose claims are proved (delivery-model.props.ts) for
49
+ * limits that are whole and not negative. Any other limit throws here, so
50
+ * none is ever delivered by, however the scenario was built. Pure.
56
51
  */
57
52
  function redelivery(event, limit, bounds) {
58
- const redeliveries = event.attempt - 1;
59
- if (redeliveries >= limit || redeliveries >= bounds.maxRedeliveries) return null;
53
+ whole("the platform's limit on redeliveries", limit);
54
+ whole("bounds.maxRedeliveries", bounds.maxRedeliveries);
55
+ if (!redelivers(event.attempt, limit, bounds.maxRedeliveries)) return null;
60
56
  return {
61
57
  ...event,
62
58
  attempt: event.attempt + 1
63
59
  };
64
60
  }
61
+ /** Throws unless the limit is one the delivery model's claims cover. */
62
+ function whole(name, limit) {
63
+ if (!(Number.isInteger(limit) && limit >= 0)) throw new Error(`${name} must be a non-negative integer, got ${limit}`);
64
+ }
65
65
  // packages/core/src/selectors.ts
66
66
  /** Picking effect records out of the log, and reading paths out of their payloads. */
67
67
  const partsOf = (path) => path === "" ? [] : path.split(".");
@@ -117,18 +117,6 @@ function keyOf(record, path) {
117
117
  const v = getPath(record.payload, path);
118
118
  return v === void 0 ? void 0 : canonicalJson(v);
119
119
  }
120
- Object.freeze({ entries: Object.freeze([]) });
121
- /** One canonical JSON object per line, in sequence order. */
122
- function serializeLog(log) {
123
- return log.entries.map((e) => canonicalJson({
124
- seq: e.seq,
125
- kind: e.kind,
126
- invocation: e.invocation,
127
- target: e.target,
128
- op: e.op,
129
- payload: e.payload
130
- })).join("\n");
131
- }
132
120
  // packages/core/src/fault-sites.ts
133
121
  /**
134
122
  * Fault sites: where a scenario's bounds let faults go. A run spends its
@@ -203,80 +191,6 @@ function describeFaultSites(sites) {
203
191
  };
204
192
  return `faults only where the scenario's bounds say: ${sites.map(one).join("; ")}`;
205
193
  }
206
- // packages/core/src/prng.ts
207
- function rotl(x, k) {
208
- return (x << k | x >>> 32 - k) >>> 0;
209
- }
210
- /** splitmix32: expands a 32-bit seed into well-mixed words for seeding. */
211
- function splitmix32(seed) {
212
- let a = seed >>> 0;
213
- return () => {
214
- a = a + 2654435769 >>> 0;
215
- let t = a;
216
- t = Math.imul(t ^ t >>> 16, 569420461);
217
- t = Math.imul(t ^ t >>> 15, 1935289751);
218
- return (t ^ t >>> 15) >>> 0;
219
- };
220
- }
221
- /** FNV-1a over UTF-16 code units, so string seeds are stable across runtimes. */
222
- function hashString(s) {
223
- let h = 2166136261;
224
- for (let i = 0; i < s.length; i++) {
225
- h ^= s.charCodeAt(i);
226
- h = Math.imul(h, 16777619);
227
- }
228
- return h >>> 0;
229
- }
230
- /** Derive an initial state from a number (taken modulo 2^32) or a string. */
231
- function seedPrng(seed) {
232
- const next = splitmix32(typeof seed === "string" ? hashString(seed) : seed >>> 0);
233
- const s = [
234
- next(),
235
- next(),
236
- next(),
237
- next()
238
- ];
239
- if (s[0] === 0 && s[1] === 0 && s[2] === 0 && s[3] === 0) s[0] = 1;
240
- return s;
241
- }
242
- /** Next 32-bit unsigned integer and the state that follows it. */
243
- function nextU32(state) {
244
- const [s0, s1, s2, s3] = state;
245
- const result = Math.imul(rotl(Math.imul(s1, 5) >>> 0, 7), 9) >>> 0;
246
- const t = s1 << 9 >>> 0;
247
- let n2 = (s2 ^ s0) >>> 0;
248
- let n3 = (s3 ^ s1) >>> 0;
249
- const n1 = (s1 ^ n2) >>> 0;
250
- const n0 = (s0 ^ n3) >>> 0;
251
- n2 = (n2 ^ t) >>> 0;
252
- n3 = rotl(n3, 11);
253
- return [result, [
254
- n0,
255
- n1,
256
- n2,
257
- n3
258
- ]];
259
- }
260
- /** Next float in [0, 1) with 24 bits of precision. */
261
- function nextFloat(state) {
262
- const [u, next] = nextU32(state);
263
- return [(u >>> 8) * 2 ** -24, next];
264
- }
265
- /**
266
- * Next integer in [0, bound). Uses rejection sampling, so every value is
267
- * equally likely; a bound of 1 always yields 0 without consuming state.
268
- */
269
- function nextInt(state, bound) {
270
- if (!Number.isInteger(bound) || bound < 1 || bound > 4294967296) throw new RangeError(`nextInt bound must be an integer in [1, 2^32], got ${bound}`);
271
- if (bound === 1) return [0, state];
272
- const limit = 4294967296 - 4294967296 % bound;
273
- let s = state;
274
- for (;;) {
275
- const [u, next] = nextU32(s);
276
- s = next;
277
- if (u < limit) return [u % bound, s];
278
- }
279
- }
280
194
  // packages/core/src/faults.ts
281
195
  /**
282
196
  * The fault model and the schedule. A schedule is the complete, replayable
@@ -580,10 +494,6 @@ function recomputePerMessageExpected(invariants, bodies) {
580
494
  };
581
495
  });
582
496
  }
583
- /** True when two violations are of the same invariant for the same keys, whatever the traces. */
584
- function sameViolation(a, b) {
585
- return a.invariant === b.invariant && a.keys.length === b.keys.length && a.keys.every((k, i) => k === b.keys[i]);
586
- }
587
497
  /** Check one invariant against a run's effect log; null when it holds. */
588
498
  function checkInvariant(log, inv) {
589
499
  switch (inv.kind) {
@@ -670,6 +580,7 @@ function validatePinnedSchedules(pinned) {
670
580
  for (const s of p.seeds) if (!(Number.isInteger(s) && s >= 0 && s <= 4294967295)) errors.push(`${label}.seeds: ${String(s)} is not a run seed (an integer, 0 to 2^32 - 1)`);
671
581
  }
672
582
  for (const t of p.turns ?? []) if (!(Number.isInteger(t) && t >= 0)) errors.push(`${label}.turns: ${String(t)} is not a turn (an index from 0)`);
583
+ if (p.effectsAsTurns !== void 0 && p.effectsAsTurns !== true) errors.push(`${label}.effectsAsTurns is true or left out, got ${String(p.effectsAsTurns)}`);
673
584
  });
674
585
  return errors;
675
586
  }
@@ -822,6 +733,11 @@ function walk(value, extra, depth, seen) {
822
733
  seen.delete(object);
823
734
  }
824
735
  }
736
+ // packages/core/src/violation.ts
737
+ /** True when two violations are of the same invariant for the same keys, whatever the traces. */
738
+ function sameViolation(a, b) {
739
+ return a.invariant === b.invariant && a.keys.length === b.keys.length && a.keys.every((k, i) => k === b.keys[i]);
740
+ }
825
741
  // packages/engine/src/chooser.ts
826
742
  /**
827
743
  * How a run chooses. A run's nondeterminism is a sequence of decisions: a
@@ -1676,6 +1592,10 @@ var Frame = class {
1676
1592
  mayPark;
1677
1593
  /** The hosting effect this one was made inside of and waited for a turn under, if any. */
1678
1594
  parent;
1595
+ /** The effect whose perform this one was made inside of, if any (`Frames.enclosing`), set by the run. */
1596
+ inside;
1597
+ /** Whether the effect waited for a turn before being performed, set by the run: the order of such effects is the chooser's. */
1598
+ tookTurn = false;
1679
1599
  /** Effects the hosted code made as turns, parked or running now, and invocations hosted inside it. */
1680
1600
  children = 0;
1681
1601
  /** Of those, the ones given their turn that have not started performing yet: on their way. */
@@ -1898,6 +1818,16 @@ var Frames = class {
1898
1818
  return hosted || store !== void 0 ? this.hosting.get(invocation)?.at(-1) : void 0;
1899
1819
  }
1900
1820
  /**
1821
+ * An effect of `invocation`'s being performed now, without having waited
1822
+ * for a turn, that was made where a new one is being made: inside
1823
+ * `enclosing` (or outside every effect), by the same attempt's code. Two
1824
+ * such are two chains of the invocation's effects in flight at once (a
1825
+ * handler awaiting two calls together), whose order is real time's.
1826
+ */
1827
+ beside(invocation, enclosing, attempt) {
1828
+ return this.stack.find((f) => !f.tookTurn && f.invocation === invocation && f.inside === enclosing && f.attempt === attempt);
1829
+ }
1830
+ /**
1901
1831
  * The effect whose perform the current code runs inside, whatever
1902
1832
  * invocation it belongs to: the live frame of the async context, else the
1903
1833
  * innermost being performed. Where another invocation's code is hosted.
@@ -2380,8 +2310,14 @@ var Run = class {
2380
2310
  queued = [];
2381
2311
  /** Concurrent runs only: the scheduler of turns. */
2382
2312
  turns;
2383
- /** Whether several invocations may be in flight (`maxConcurrentInvocations` above 1). */
2313
+ /**
2314
+ * Whether asynchronous effects are turns: several invocations may be in
2315
+ * flight (`maxConcurrentInvocations` above 1), or the run was asked to
2316
+ * make them turns with one at a time (`RunOptions.turns`).
2317
+ */
2384
2318
  concurrent;
2319
+ /** See `parallelCalls`. */
2320
+ parallel;
2385
2321
  options;
2386
2322
  /** The kinds a point may take under the bounds' fault sites (all it allows, without sites). */
2387
2323
  sited;
@@ -2389,7 +2325,7 @@ var Run = class {
2389
2325
  this.options = options;
2390
2326
  this.sited = compileFaultSites(options.bounds.faultsAt);
2391
2327
  this.turns = new Turns(options.chooser, this.frames, (id) => this.runAs(id), () => this.patched?.reads, () => this.firedPending() + this.releasedUnseen(), () => this.hasAfterWork(), () => this.timersAllowed() !== null || this.idleBehindParked());
2392
- this.concurrent = options.bounds.maxConcurrentInvocations > 1;
2328
+ this.concurrent = options.bounds.maxConcurrentInvocations > 1 || options.turns === true;
2393
2329
  }
2394
2330
  get log() {
2395
2331
  this.logView ??= { entries: [...this.entries] };
@@ -2401,7 +2337,8 @@ var Run = class {
2401
2337
  return {
2402
2338
  seed,
2403
2339
  faults: [...this.faults],
2404
- ...recordsTurns ? { turns: [...this.turns.picks] } : {}
2340
+ ...recordsTurns ? { turns: [...this.turns.picks] } : {},
2341
+ ...this.options.turns === true ? { effectsAsTurns: true } : {}
2405
2342
  };
2406
2343
  }
2407
2344
  /**
@@ -2437,7 +2374,8 @@ var Run = class {
2437
2374
  };
2438
2375
  }),
2439
2376
  seeds: [schedule.seed],
2440
- ...schedule.turns === void 0 ? {} : { turns: schedule.turns }
2377
+ ...schedule.turns === void 0 ? {} : { turns: schedule.turns },
2378
+ ...schedule.effectsAsTurns === true ? { effectsAsTurns: true } : {}
2441
2379
  };
2442
2380
  }
2443
2381
  get effectPoints() {
@@ -2468,6 +2406,22 @@ var Run = class {
2468
2406
  get unsupportedReasons() {
2469
2407
  return this.reasons;
2470
2408
  }
2409
+ /**
2410
+ * The first time an invocation made an effect, without a turn, while
2411
+ * another of its effects made in the same place, also without a turn, was
2412
+ * still being performed (a handler awaiting two calls together), or the
2413
+ * first such pair turns would order when there is one; undefined when
2414
+ * none did. Which of two such calls lands first is real
2415
+ * time's to say, so the run is one of several the same schedule allows.
2416
+ * In a run whose effects are not turns, `explore` and the replays run the
2417
+ * scenario again with every effect a turn (`RunOptions.turns`) where that
2418
+ * would order them and the platform can. A host without async context
2419
+ * cannot tell two such calls from one made inside the other, and reports
2420
+ * none.
2421
+ */
2422
+ get parallelCalls() {
2423
+ return this.parallel;
2424
+ }
2471
2425
  /** Replace the nondeterministic globals and `fetch` for this run. Call `uninstall` in a finally. */
2472
2426
  install(externals = []) {
2473
2427
  installed = this;
@@ -3084,7 +3038,8 @@ var Run = class {
3084
3038
  };
3085
3039
  if (cont.isCrashed()) return hang();
3086
3040
  const ended = ctx.frame ?? this.hostFrames.get(host);
3087
- if (this.concurrent && (ended?.mayPark() ?? true)) {
3041
+ const parks = this.concurrent && (ended?.mayPark() ?? true);
3042
+ if (parks) {
3088
3043
  let released = false;
3089
3044
  this.turns.park(cont, own.target, () => {
3090
3045
  released = true;
@@ -3093,7 +3048,7 @@ var Run = class {
3093
3048
  while (!released && !cont.isCrashed()) await this.hostTick(host);
3094
3049
  if (!released) return hang();
3095
3050
  }
3096
- return this.performEffect(own, perform, summarize, options, cont, ended);
3051
+ return this.performEffect(own, perform, summarize, options, cont, ended, void 0, parks);
3097
3052
  }
3098
3053
  }
3099
3054
  const inv = this.invocation(point.invocation);
@@ -3127,7 +3082,8 @@ var Run = class {
3127
3082
  while (!released && !crashed()) await (host === void 0 ? realTick() : this.hostTick(host));
3128
3083
  return released;
3129
3084
  });
3130
- return this.performEffect(point, perform, summarize, options, inv, enclosing);
3085
+ const tookTurn = this.concurrent && !nested;
3086
+ return this.performEffect(point, perform, summarize, options, inv, enclosing, void 0, tookTurn);
3131
3087
  }
3132
3088
  /**
3133
3089
  * An effect that is a turn under `host` (the effect hosting the invocation, or the hosted code's
@@ -3156,7 +3112,7 @@ var Run = class {
3156
3112
  return hang();
3157
3113
  }
3158
3114
  try {
3159
- return await this.performEffect(point, perform, summarize, options, inv, enclosing, host);
3115
+ return await this.performEffect(point, perform, summarize, options, inv, enclosing, host, true);
3160
3116
  } finally {
3161
3117
  this.childEnds(host);
3162
3118
  }
@@ -3170,7 +3126,7 @@ var Run = class {
3170
3126
  this.frames.adjust(host, () => host.children--);
3171
3127
  }
3172
3128
  /** The effect once it has its turn: the fault, the perform under its deadline, the record. */
3173
- async performEffect(made, perform, summarize, options, inv, enclosing, host) {
3129
+ async performEffect(made, perform, summarize, options, inv, enclosing, host, tookTurn = false) {
3174
3130
  const dead = () => {
3175
3131
  enclosing?.crash();
3176
3132
  return hang();
@@ -3191,7 +3147,19 @@ var Run = class {
3191
3147
  frame.onHostAbandoned = (h) => this.hostAbandoned(h);
3192
3148
  frame.parent = host;
3193
3149
  frame.attempt = this.attemptNow(enclosing, host);
3150
+ frame.inside = enclosing;
3194
3151
  frame.issuer = (hostScope?.getStore() ?? this.hostedWithin.get(made.invocation))?.host;
3152
+ frame.tookTurn = tookTurn;
3153
+ if (!tookTurn) {
3154
+ const turnsWouldOrder = !this.concurrent && (enclosing === void 0 || enclosing.hosts && enclosing.mayPark());
3155
+ if (this.parallel === void 0 || turnsWouldOrder && !this.parallel.turnsWouldOrder) {
3156
+ const beside = this.frames.beside(point.invocation, enclosing, frame.attempt);
3157
+ if (beside) this.parallel = {
3158
+ calls: `${point.invocation} made ${point.target} ${point.op} while its ${beside.target} ${beside.op} was in flight`,
3159
+ turnsWouldOrder
3160
+ };
3161
+ }
3162
+ }
3195
3163
  this.frames.enter(frame);
3196
3164
  if (enclosing) this.frames.adjust(enclosing, () => enclosing.performing++);
3197
3165
  let ended = false;
@@ -3693,142 +3661,420 @@ function decide(hooks, point, perform, summarize) {
3693
3661
  throw err;
3694
3662
  }
3695
3663
  }
3696
- // packages/engine/src/exhaustive.ts
3664
+ // packages/engine/src/once.ts
3697
3665
  /**
3698
- * Exhaustive exploration: every schedule within the bounds, each once. A
3699
- * schedule is the sequence of choices a run makes: a fault or none at each
3700
- * effect point that may still take one, and the next turn at each decision
3701
- * of a concurrent run. Runs are deterministic, so forcing a prefix of
3702
- * choices reproduces the run up to there; the enumerator walks the tree of
3703
- * choice sequences depth first, one run per leaf, without saving state
3704
- * (each run starts from the scenario's reset).
3705
- *
3706
- * Reduction, when on, uses sleep sets (Godefroid, Partial-Order Methods for
3707
- * the Verification of Concurrent Systems, 1996): two turns of different
3708
- * invocations whose effects have different targets commute, so after one
3709
- * order of them has been explored the other is not. Starting an event and
3710
- * firing a timer already due are dependent on everything (their options
3711
- * have no target), so what they run is never reordered. A run whose every option is asleep repeats an
3712
- * explored order; it still runs (the choices are forced up to it) but is not
3713
- * counted as a schedule and nothing below it is explored.
3666
+ * One run of a scenario from reset to its log: the events delivered one at
3667
+ * a time, or with several invocations in flight and each turn the run's
3668
+ * pick (`runOnce`), and a recorded schedule run again exactly
3669
+ * (`replayRun`). Exploring and shrinking both stand on these.
3714
3670
  */
3715
- /** Whether two turns commute: different invocations, effects on different targets. */
3716
- function independent(a, b) {
3717
- return a.invocation !== void 0 && b.invocation !== void 0 && a.invocation !== b.invocation && a.target !== void 0 && b.target !== void 0 && a.target !== b.target;
3718
- }
3719
- const asleep = /* @__PURE__ */ new Map();
3720
- var Enumerator = class {
3721
- stack = [];
3722
- depth = 0;
3723
- /** The depth of the first node in the run just made whose every option was asleep, or null. */
3724
- blockedAt = null;
3725
- mismatchReason = null;
3726
- reduction;
3727
- constructor(options) {
3728
- this.reduction = options.reduction;
3729
- }
3730
- /** Whether the run just made repeats an explored order (every option at some point was asleep). */
3731
- get blocked() {
3732
- return this.blockedAt !== null;
3733
- }
3734
- /** Set when a run made different choices than the same prefix did before: not deterministic. */
3735
- get mismatch() {
3736
- return this.mismatchReason;
3737
- }
3738
- /**
3739
- * The chooser for the next run: the explored prefix, then the first option
3740
- * not asleep. Enumerated runs pick their choices and share one seed for
3741
- * the virtual globals; their turns are recorded, since they do not follow it.
3742
- */
3743
- next() {
3744
- this.depth = 0;
3745
- this.blockedAt = null;
3746
- return {
3747
- seed: 0,
3748
- recordsTurns: true,
3749
- choose: (kind, options) => this.choose(kind, options)
3750
- };
3671
+ /** Deliver events one at a time, each to completion; time passes until a delayed one is due. */
3672
+ async function deliverInOrder(spec, platform, run) {
3673
+ const pending = [...platform.initialEvents(spec)];
3674
+ for (;;) {
3675
+ if (pending.length === 0) pending.push(...platform.closingEvents?.(spec) ?? []);
3676
+ if (pending.length === 0) return;
3677
+ const [event] = pending.splice(earliestEvent(pending), 1);
3678
+ if (event.at !== void 0) await run.advanceTo(event.at);
3679
+ const result = await platform.deliver(event, run, spec);
3680
+ await run.driveAfterWork();
3681
+ pending.push(...run.takeQueued(), ...result.followUps);
3751
3682
  }
3752
- choose(kind, options) {
3753
- const i = this.depth++;
3754
- const known = this.stack[i];
3755
- if (known) {
3756
- if (!(known.kind === kind && known.options.length === options.length && known.options.every((o, j) => o.label === options[j]?.label)) && this.mismatchReason === null) this.mismatchReason = `choice ${i} differed between runs with the same earlier choices (${known.options.map((o) => o.label).join(", ")} then ${options.map((o) => o.label).join(", ")})`;
3757
- return known.picked < options.length ? known.picked : 0;
3683
+ }
3684
+ /**
3685
+ * Deliver events with up to `maxConcurrentInvocations` in flight. Each turn
3686
+ * is a seeded pick: one parked invocation performs its effect and runs to
3687
+ * its next one, while a slot is free the next event starts, or a timer
3688
+ * already due fires. When nothing is parked, no event can start and no
3689
+ * timer is due, the next timer fires (time passes to it), and when nothing
3690
+ * can move the remaining invocations are abandoned.
3691
+ */
3692
+ async function deliverConcurrently(spec, platform, run) {
3693
+ const pending = [...platform.initialEvents(spec)];
3694
+ let active = [];
3695
+ for (;;) {
3696
+ const queuedBefore = pending.length;
3697
+ for (const d of active) {
3698
+ if (!d.outcome) continue;
3699
+ if ("error" in d.outcome) throw d.outcome.error;
3700
+ pending.push(...d.outcome.result.followUps);
3758
3701
  }
3759
- if (this.blockedAt !== null) return 0;
3760
- const sleep = this.sleepAt(i);
3761
- let picked = kind === "turn" ? options.findIndex((o) => !sleep.has(o.label)) : 0;
3762
- if (picked < 0) {
3763
- this.blockedAt = i;
3764
- picked = 0;
3702
+ active = active.filter((d) => !d.outcome);
3703
+ pending.push(...run.takeQueued());
3704
+ if (pending.length > queuedBefore) run.queuedEvents();
3705
+ if (active.length === 0 && pending.length === 0 && !run.hasAfterWork()) {
3706
+ pending.push(...platform.closingEvents?.(spec) ?? []);
3707
+ if (pending.length === 0) return;
3708
+ run.queuedEvents();
3765
3709
  }
3766
- this.stack.push({
3767
- kind,
3768
- options,
3769
- picked,
3770
- done: [],
3771
- sleep
3772
- });
3773
- return picked;
3774
- }
3775
- /** The sleep set of a new node at depth i, from its parent's. */
3776
- sleepAt(i) {
3777
- const parent = this.stack[i - 1];
3778
- if (!this.reduction || !parent) return asleep;
3779
- if (parent.kind === "fault") return parent.sleep;
3780
- const taken = parent.options[parent.picked];
3781
- if (!taken) return asleep;
3782
- const sleep = /* @__PURE__ */ new Map();
3783
- const candidates = [...parent.sleep.values(), ...parent.done.map((j) => parent.options[j])];
3784
- for (const c of candidates) if (c && independent(c, taken)) sleep.set(c.label, c);
3785
- return sleep;
3786
- }
3787
- /** Move to the next schedule after a run. False once every schedule has been explored. */
3788
- advance() {
3789
- this.stack.length = Math.min(this.stack.length, this.depth, (this.blockedAt ?? Infinity) + 1);
3790
- while (this.stack.length > 0) {
3791
- const node = this.stack[this.stack.length - 1];
3792
- if (!node.done.includes(node.picked)) node.done.push(node.picked);
3793
- const next = node.options.findIndex((o, j) => !node.done.includes(j) && (node.kind === "fault" || !node.sleep.has(o.label)));
3794
- if (next >= 0) {
3795
- node.picked = next;
3796
- return true;
3710
+ const next = pending.length > 0 ? earliestEvent(pending) : -1;
3711
+ const eventAt = pending[next]?.at ?? 0;
3712
+ const due = next >= 0 && eventAt <= run.now();
3713
+ const resting = spec.bounds.maxConcurrentInvocations === 1 && run.hasAfterWork();
3714
+ const canStart = active.length < spec.bounds.maxConcurrentInvocations && due && !resting;
3715
+ const afterWorkOnly = active.length === 0 && run.hasAfterWork();
3716
+ const timerDue = run.nextTimerDue(afterWorkOnly);
3717
+ const untilEvent = next >= 0 && !due && active.length < spec.bounds.maxConcurrentInvocations && (timerDue ?? Number.POSITIVE_INFINITY) > eventAt;
3718
+ const turn = run.takeTurn(canStart, afterWorkOnly, untilEvent || timerDue !== void 0);
3719
+ if (turn === "start") {
3720
+ const [event] = pending.splice(next, 1);
3721
+ const d = {
3722
+ started: run.startDelivery(() => platform.deliver(event, run, spec)),
3723
+ outcome: null
3724
+ };
3725
+ d.started.promise.then((result) => {
3726
+ d.outcome = { result };
3727
+ run.rested();
3728
+ }, (error) => {
3729
+ d.outcome = { error };
3730
+ run.rested();
3731
+ });
3732
+ active.push(d);
3733
+ } else if (turn === "none" && untilEvent) {
3734
+ if (!await run.advanceTo(eventAt)) continue;
3735
+ } else if (turn === "none" && !(active.length > 0 || !run.hasAfterWork() ? run.fireTimer() : run.fireAfterWorkTimer()) && run.settleAfterWork() === 0) {
3736
+ const stuck = active.flatMap((d) => d.started.invocation() ?? []);
3737
+ if (run.abandon(stuck) === 0) {
3738
+ const ending = active.filter((d) => run.hasCrashed(d.started.invocation()));
3739
+ if (!await run.ended(ending.map((d) => d.started.promise))) throw new Error(`the ${platform.name} platform's delivery made no progress and cannot be abandoned`);
3797
3740
  }
3798
- this.stack.pop();
3799
3741
  }
3800
- return false;
3742
+ await run.quiesce();
3801
3743
  }
3802
- };
3744
+ }
3745
+ /** Run the scenario once under the given run's fault decisions and return its log. */
3746
+ async function runOnce(spec, platform, run) {
3747
+ await platform.reset(spec);
3748
+ run.install(spec.externals);
3749
+ try {
3750
+ try {
3751
+ if (!run.concurrent) await deliverInOrder(spec, platform, run);
3752
+ else if (platform.concurrent) await deliverConcurrently(spec, platform, run);
3753
+ else throw new Error(`the ${platform.name} platform delivers one event at a time`);
3754
+ } finally {
3755
+ run.uninstall();
3756
+ }
3757
+ await platform.finish?.(spec, run);
3758
+ } finally {
3759
+ await platform.cleanup?.(spec);
3760
+ }
3761
+ return run.log;
3762
+ }
3803
3763
  /**
3804
- * The exhaustive half of `explore`: the chooser for each run, what a run
3805
- * counts for, and starting the enumeration again with the reduction off
3806
- * once a run shows its turns may not commute.
3764
+ * Whether a run on this platform can make every effect a turn: the host
3765
+ * carries async context and the platform delivers with several invocations
3766
+ * in flight. One invocation at a time needs the same once its calls run in
3767
+ * parallel (`Run.parallelCalls`).
3807
3768
  */
3808
- var ExhaustiveDriver = class {
3809
- reduction;
3810
- enumerator;
3811
- maxFaultsPerRun;
3812
- schedules = 0;
3813
- more = true;
3814
- restart = false;
3815
- constructor(reduction, maxFaultsPerRun) {
3816
- this.reduction = reduction;
3817
- this.maxFaultsPerRun = maxFaultsPerRun;
3818
- this.enumerator = new Enumerator({ reduction });
3819
- }
3820
- /** Whether schedules are left to run. */
3821
- get hasMore() {
3822
- return this.more;
3823
- }
3824
- /** See `Enumerator.mismatch`. */
3825
- get mismatch() {
3826
- return this.enumerator.mismatch;
3827
- }
3828
- /** The chooser for the next run, under the run's fault bound. */
3829
- next() {
3830
- return limitFaults(this.enumerator.next(), this.maxFaultsPerRun);
3831
- }
3769
+ function takesTurns(platform) {
3770
+ return concurrencySupported && platform.concurrent === true;
3771
+ }
3772
+ /** Refuse a schedule recorded with every effect a turn on a platform or a host that cannot run it so. */
3773
+ function mustTakeTurns(platform, what) {
3774
+ if (takesTurns(platform)) return;
3775
+ throw new Error(`${what} was recorded with every effect a turn (effectsAsTurns), which ${cannotTakeTurns(platform)}`);
3776
+ }
3777
+ /** Why effects cannot be turns here, for a reason; call only where `takesTurns` is false. */
3778
+ function cannotTakeTurns(platform) {
3779
+ return concurrencySupported ? `the ${platform.name} platform cannot do: it delivers one event at a time` : "needs AsyncLocalStorage (Node, or workerd with nodejs_compat or nodejs_als)";
3780
+ }
3781
+ /**
3782
+ * Re-run a recorded schedule exactly and return the whole run (log and
3783
+ * support status): with every effect a turn where the schedule says its run
3784
+ * had them so (`Schedule.effectsAsTurns`). A schedule that does not say so,
3785
+ * replayed in a run that shows an invocation's calls in parallel, is run
3786
+ * again that way where the platform can: `explore` would have recorded it so.
3787
+ */
3788
+ async function replayRun(spec, platform, schedule) {
3789
+ const turns = schedule.effectsAsTurns === true;
3790
+ if (turns) mustTakeTurns(platform, "the schedule");
3791
+ const run = new Run({
3792
+ bounds: spec.bounds,
3793
+ chooser: replayChooser(schedule),
3794
+ turns
3795
+ });
3796
+ await runOnce(spec, platform, run);
3797
+ if (!turns && run.parallelCalls?.turnsWouldOrder === true && takesTurns(platform)) return replayRun(spec, platform, {
3798
+ ...schedule,
3799
+ effectsAsTurns: true
3800
+ });
3801
+ return run;
3802
+ }
3803
+ // packages/engine/src/differential.ts
3804
+ /**
3805
+ * The platform-neutral part of a differential check: the same fault-free
3806
+ * scenario once through Eutaxy and once against the raw bindings, then a
3807
+ * comparison of what each attempt decided and of the final state. Any
3808
+ * difference is a bug in the proxies or the platform model, not in the
3809
+ * handler. The raw side's loop is here too (the same virtual globals and
3810
+ * scripted externals as the proxied side, the same pick of the next event
3811
+ * and the same redelivery rule); a platform writes only how one raw attempt
3812
+ * calls its handler, sharing no proxy code.
3813
+ */
3814
+ /** The raw side cannot abandon an invocation the way the engine does; a stuck handler ends the comparison. */
3815
+ var DifferentialStuck = class extends Error {
3816
+ name = "DifferentialStuck";
3817
+ constructor(message = "raw side: the handler is waiting on something outside the run (no effect in flight, no timer due)") {
3818
+ super(message);
3819
+ }
3820
+ };
3821
+ /**
3822
+ * The Eutaxy side: one run with no faults, one event at a time whatever the
3823
+ * scenario's bound (the raw side cannot interleave), with `attempt` given
3824
+ * each delivery's event, result and log entries.
3825
+ */
3826
+ async function proxiedSide(spec, platform, attempt) {
3827
+ const run = new Run({
3828
+ bounds: {
3829
+ ...spec.bounds,
3830
+ maxConcurrentInvocations: 1
3831
+ },
3832
+ chooser: replayChooser({
3833
+ seed: 0,
3834
+ faults: []
3835
+ })
3836
+ });
3837
+ const attempts = [];
3838
+ const { finish, cleanup } = platform;
3839
+ await runOnce(spec, {
3840
+ name: platform.name,
3841
+ assumptions: platform.assumptions,
3842
+ ...platform.concurrent === void 0 ? {} : { concurrent: platform.concurrent },
3843
+ reset: (s) => platform.reset(s),
3844
+ initialEvents: (s) => platform.initialEvents(s),
3845
+ restrictEvents: (s, keep) => platform.restrictEvents(s, keep),
3846
+ async deliver(event, hooks, s) {
3847
+ const before = run.log.entries.length;
3848
+ const result = await platform.deliver(event, hooks, s);
3849
+ attempts.push(attempt(event, result, run.log.entries.slice(before)));
3850
+ return result;
3851
+ },
3852
+ ...finish ? { finish: (s, hooks) => finish.call(platform, s, hooks) } : {},
3853
+ ...cleanup ? { cleanup: (s) => cleanup.call(platform, s) } : {}
3854
+ }, run);
3855
+ return {
3856
+ attempts,
3857
+ unsupported: run.unsupportedReasons
3858
+ };
3859
+ }
3860
+ /**
3861
+ * The raw side: every event delivered as the engine would deliver it with
3862
+ * no faults and one invocation at a time (the earliest due first, time
3863
+ * moved to a delayed one, an unhandled one delivered again under core's
3864
+ * redelivery rule), each attempt performed by the platform. The attempts'
3865
+ * records, in order.
3866
+ */
3867
+ async function rawRun(spec, side) {
3868
+ const patched = patchGlobals(0);
3869
+ const reasons = [];
3870
+ const unsupported = (reason) => {
3871
+ reasons.push(reason);
3872
+ };
3873
+ const restoreFetch = installScriptedFetch(spec.externals, null, unsupported, () => patched.clock.advance(1));
3874
+ const io = { n: 0 };
3875
+ const settle = (promise) => settleOn(promise, {
3876
+ clock: patched.clock,
3877
+ inFlight: () => io.n,
3878
+ crashed: () => false,
3879
+ stuck: () => {
3880
+ throw new DifferentialStuck();
3881
+ }
3882
+ });
3883
+ const call = async (code) => {
3884
+ try {
3885
+ return {
3886
+ status: "completed",
3887
+ value: await settle(Promise.resolve().then(code))
3888
+ };
3889
+ } catch (error) {
3890
+ if (error instanceof DifferentialStuck) throw error;
3891
+ return {
3892
+ status: "errored",
3893
+ error
3894
+ };
3895
+ }
3896
+ };
3897
+ const attempts = [];
3898
+ const pending = [...side.events];
3899
+ let restore;
3900
+ try {
3901
+ const installed = side.install({
3902
+ clock: patched.clock,
3903
+ io,
3904
+ libraryIo: (perform) => patched.libraryIo(perform),
3905
+ unsupported,
3906
+ settle,
3907
+ call
3908
+ });
3909
+ restore = installed.restore;
3910
+ const { attempt } = installed;
3911
+ while (pending.length > 0) {
3912
+ const [event] = pending.splice(earliestEvent(pending), 1);
3913
+ if (event.at !== void 0 && event.at > patched.clock.now()) patched.clock.advance(event.at - patched.clock.now());
3914
+ const { record, handled } = await attempt(event);
3915
+ attempts.push(record);
3916
+ const next = handled ? null : redelivery(event, side.limit, spec.bounds);
3917
+ if (next) pending.push(next);
3918
+ }
3919
+ } finally {
3920
+ restore?.();
3921
+ restoreFetch();
3922
+ patched.restore();
3923
+ }
3924
+ if (reasons.length > 0) throw new DifferentialStuck(`raw side: ${reasons.join("; ")}`);
3925
+ return attempts;
3926
+ }
3927
+ /** Every difference between the two sides, one readable entry each; none means they agree. */
3928
+ function compareSides(eutaxy, raw, unsupported) {
3929
+ const differences = [];
3930
+ if (unsupported.length > 0) differences.push(`the proxied run touched unsupported APIs: ${unsupported.join("; ")}`);
3931
+ const a = canonicalJson(eutaxy.attempts);
3932
+ const b = canonicalJson(raw.attempts);
3933
+ if (a !== b) differences.push(`attempts differ:\n eutaxy ${a}\n raw ${b}`);
3934
+ const names = /* @__PURE__ */ new Set([...Object.keys(eutaxy.state), ...Object.keys(raw.state)]);
3935
+ for (const name of [...names].sort()) {
3936
+ const x = canonicalJson(eutaxy.state[name] ?? []);
3937
+ const y = canonicalJson(raw.state[name] ?? []);
3938
+ if (x !== y) differences.push(`${name} differs:\n eutaxy ${x}\n raw ${y}`);
3939
+ }
3940
+ return differences;
3941
+ }
3942
+ // packages/engine/src/exhaustive.ts
3943
+ /**
3944
+ * Exhaustive exploration: every schedule within the bounds, each once. A
3945
+ * schedule is the sequence of choices a run makes: a fault or none at each
3946
+ * effect point that may still take one, and the next turn at each decision
3947
+ * of a concurrent run. Runs are deterministic, so forcing a prefix of
3948
+ * choices reproduces the run up to there; the enumerator walks the tree of
3949
+ * choice sequences depth first, one run per leaf, without saving state
3950
+ * (each run starts from the scenario's reset).
3951
+ *
3952
+ * Reduction, when on, uses sleep sets (Godefroid, Partial-Order Methods for
3953
+ * the Verification of Concurrent Systems, 1996): two turns of different
3954
+ * invocations whose effects have different targets commute, so after one
3955
+ * order of them has been explored the other is not. Starting an event and
3956
+ * firing a timer already due are dependent on everything (their options
3957
+ * have no target), so what they run is never reordered. A run whose every option is asleep repeats an
3958
+ * explored order; it still runs (the choices are forced up to it) but is not
3959
+ * counted as a schedule and nothing below it is explored.
3960
+ */
3961
+ /** Whether two turns commute: different invocations, effects on different targets. */
3962
+ function independent(a, b) {
3963
+ return a.invocation !== void 0 && b.invocation !== void 0 && a.invocation !== b.invocation && a.target !== void 0 && b.target !== void 0 && a.target !== b.target;
3964
+ }
3965
+ const asleep = /* @__PURE__ */ new Map();
3966
+ var Enumerator = class {
3967
+ stack = [];
3968
+ depth = 0;
3969
+ /** The depth of the first node in the run just made whose every option was asleep, or null. */
3970
+ blockedAt = null;
3971
+ mismatchReason = null;
3972
+ reduction;
3973
+ constructor(options) {
3974
+ this.reduction = options.reduction;
3975
+ }
3976
+ /** Whether the run just made repeats an explored order (every option at some point was asleep). */
3977
+ get blocked() {
3978
+ return this.blockedAt !== null;
3979
+ }
3980
+ /** Set when a run made different choices than the same prefix did before: not deterministic. */
3981
+ get mismatch() {
3982
+ return this.mismatchReason;
3983
+ }
3984
+ /**
3985
+ * The chooser for the next run: the explored prefix, then the first option
3986
+ * not asleep. Enumerated runs pick their choices and share one seed for
3987
+ * the virtual globals; their turns are recorded, since they do not follow it.
3988
+ */
3989
+ next() {
3990
+ this.depth = 0;
3991
+ this.blockedAt = null;
3992
+ return {
3993
+ seed: 0,
3994
+ recordsTurns: true,
3995
+ choose: (kind, options) => this.choose(kind, options)
3996
+ };
3997
+ }
3998
+ choose(kind, options) {
3999
+ const i = this.depth++;
4000
+ const known = this.stack[i];
4001
+ if (known) {
4002
+ if (!(known.kind === kind && known.options.length === options.length && known.options.every((o, j) => o.label === options[j]?.label)) && this.mismatchReason === null) this.mismatchReason = `choice ${i} differed between runs with the same earlier choices (${known.options.map((o) => o.label).join(", ")} then ${options.map((o) => o.label).join(", ")})`;
4003
+ return known.picked < options.length ? known.picked : 0;
4004
+ }
4005
+ if (this.blockedAt !== null) return 0;
4006
+ const sleep = this.sleepAt(i);
4007
+ let picked = kind === "turn" ? options.findIndex((o) => !sleep.has(o.label)) : 0;
4008
+ if (picked < 0) {
4009
+ this.blockedAt = i;
4010
+ picked = 0;
4011
+ }
4012
+ this.stack.push({
4013
+ kind,
4014
+ options,
4015
+ picked,
4016
+ done: [],
4017
+ sleep
4018
+ });
4019
+ return picked;
4020
+ }
4021
+ /** The sleep set of a new node at depth i, from its parent's. */
4022
+ sleepAt(i) {
4023
+ const parent = this.stack[i - 1];
4024
+ if (!this.reduction || !parent) return asleep;
4025
+ if (parent.kind === "fault") return parent.sleep;
4026
+ const taken = parent.options[parent.picked];
4027
+ if (!taken) return asleep;
4028
+ const sleep = /* @__PURE__ */ new Map();
4029
+ const candidates = [...parent.sleep.values(), ...parent.done.map((j) => parent.options[j])];
4030
+ for (const c of candidates) if (c && independent(c, taken)) sleep.set(c.label, c);
4031
+ return sleep;
4032
+ }
4033
+ /** Move to the next schedule after a run. False once every schedule has been explored. */
4034
+ advance() {
4035
+ this.stack.length = Math.min(this.stack.length, this.depth, (this.blockedAt ?? Infinity) + 1);
4036
+ while (this.stack.length > 0) {
4037
+ const node = this.stack[this.stack.length - 1];
4038
+ if (!node.done.includes(node.picked)) node.done.push(node.picked);
4039
+ const next = node.options.findIndex((o, j) => !node.done.includes(j) && (node.kind === "fault" || !node.sleep.has(o.label)));
4040
+ if (next >= 0) {
4041
+ node.picked = next;
4042
+ return true;
4043
+ }
4044
+ this.stack.pop();
4045
+ }
4046
+ return false;
4047
+ }
4048
+ };
4049
+ /**
4050
+ * The exhaustive half of `explore`: the chooser for each run, what a run
4051
+ * counts for, and starting the enumeration again with the reduction off
4052
+ * once a run shows its turns may not commute.
4053
+ */
4054
+ var ExhaustiveDriver = class {
4055
+ reduction;
4056
+ enumerator;
4057
+ maxFaultsPerRun;
4058
+ schedules = 0;
4059
+ more = true;
4060
+ restart = false;
4061
+ constructor(reduction, maxFaultsPerRun) {
4062
+ this.reduction = reduction;
4063
+ this.maxFaultsPerRun = maxFaultsPerRun;
4064
+ this.enumerator = new Enumerator({ reduction });
4065
+ }
4066
+ /** Whether schedules are left to run. */
4067
+ get hasMore() {
4068
+ return this.more;
4069
+ }
4070
+ /** See `Enumerator.mismatch`. */
4071
+ get mismatch() {
4072
+ return this.enumerator.mismatch;
4073
+ }
4074
+ /** The chooser for the next run, under the run's fault bound. */
4075
+ next() {
4076
+ return limitFaults(this.enumerator.next(), this.maxFaultsPerRun);
4077
+ }
3832
4078
  /**
3833
4079
  * Account for the run just made. False when it only repeated an order the
3834
4080
  * reduction had covered: it is not a new schedule and its checks repeat
@@ -3898,7 +4144,13 @@ async function shrink(spec, platform, schedule, violation, trace, options) {
3898
4144
  if (run.unsupportedReasons.length > 0) continue;
3899
4145
  const found = checkInvariants(log, candidateSpec.invariants).find((v) => sameViolation(v, violation));
3900
4146
  if (found) {
3901
- state = candidate;
4147
+ state = run.schedule.effectsAsTurns === true && candidate.schedule.effectsAsTurns !== true ? {
4148
+ ...candidate,
4149
+ schedule: {
4150
+ ...candidate.schedule,
4151
+ effectsAsTurns: true
4152
+ }
4153
+ } : candidate;
3902
4154
  best = {
3903
4155
  trace: log,
3904
4156
  violation: found
@@ -3943,10 +4195,14 @@ const engineAssumptions = [
3943
4195
  "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)",
3944
4196
  "outbound fetch never reaches the network: requests are answered from the scenario's declared externals, an external's dedupeBy guarantee is honoured by replaying the first response per key, and an undeclared host makes the run UNSUPPORTED"
3945
4197
  ];
3946
- /** What a verdict rests on about concurrency, for these bounds. */
3947
- function concurrencyAssumption(bounds) {
3948
- if (bounds.maxConcurrentInvocations === 1) return "one invocation at a time (maxConcurrentInvocations = 1)";
3949
- 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`;
4198
+ /**
4199
+ * What a verdict rests on about concurrency, for these bounds. `turns`: one
4200
+ * invocation at a time, with every effect a turn since an invocation made
4201
+ * calls in parallel.
4202
+ */
4203
+ function concurrencyAssumption(bounds, turns) {
4204
+ if (bounds.maxConcurrentInvocations === 1 && !turns) return "one invocation at a time (maxConcurrentInvocations = 1)";
4205
+ return `${bounds.maxConcurrentInvocations === 1 ? "one invocation at a time (maxConcurrentInvocations = 1), an object's work after its answer running to rest before the next event starts, the calls an invocation makes in parallel (two awaited together)" : `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`;
3950
4206
  }
3951
4207
  /** Where two JSON values first differ, as a path into them (`.tables.audit[0].at`), with the two values there. */
3952
4208
  function firstDifference(a, b, path = "") {
@@ -4021,112 +4277,13 @@ function explorationAssumption(options) {
4021
4277
  if (!options.exhaustive) return [];
4022
4278
  return ["exhaustive: every placement of faults within maxFaultsPerRun and every order of turns, each run once, until complete or the budget ends (reached.exhaustive says which)", ...reductionOf(options) ? ["partial-order reduction: turns of different invocations whose effects have different targets commute, so one order of them is run; this assumes code between an invocation's effects shares no state with other invocations except through effects and the virtual globals, and once a turn other than an event's start performs an effect on another target than its own, queues an event, or reads virtual time or randomness, or schedules a timer, the reduction is off and every order is run (reached.exhaustive.reduction says whether it stayed on)"] : []];
4023
4279
  }
4024
- /** Deliver events one at a time, each to completion; time passes until a delayed one is due. */
4025
- async function deliverInOrder(spec, platform, run) {
4026
- const pending = [...platform.initialEvents(spec)];
4027
- for (;;) {
4028
- if (pending.length === 0) pending.push(...platform.closingEvents?.(spec) ?? []);
4029
- if (pending.length === 0) return;
4030
- const [event] = pending.splice(earliestEvent(pending), 1);
4031
- if (event.at !== void 0) await run.advanceTo(event.at);
4032
- const result = await platform.deliver(event, run, spec);
4033
- await run.driveAfterWork();
4034
- pending.push(...run.takeQueued(), ...result.followUps);
4035
- }
4036
- }
4037
- /**
4038
- * Deliver events with up to `maxConcurrentInvocations` in flight. Each turn
4039
- * is a seeded pick: one parked invocation performs its effect and runs to
4040
- * its next one, while a slot is free the next event starts, or a timer
4041
- * already due fires. When nothing is parked, no event can start and no
4042
- * timer is due, the next timer fires (time passes to it), and when nothing
4043
- * can move the remaining invocations are abandoned.
4044
- */
4045
- async function deliverConcurrently(spec, platform, run) {
4046
- const pending = [...platform.initialEvents(spec)];
4047
- let active = [];
4048
- for (;;) {
4049
- const queuedBefore = pending.length;
4050
- for (const d of active) {
4051
- if (!d.outcome) continue;
4052
- if ("error" in d.outcome) throw d.outcome.error;
4053
- pending.push(...d.outcome.result.followUps);
4054
- }
4055
- active = active.filter((d) => !d.outcome);
4056
- pending.push(...run.takeQueued());
4057
- if (pending.length > queuedBefore) run.queuedEvents();
4058
- if (active.length === 0 && pending.length === 0 && !run.hasAfterWork()) {
4059
- pending.push(...platform.closingEvents?.(spec) ?? []);
4060
- if (pending.length === 0) return;
4061
- run.queuedEvents();
4062
- }
4063
- const next = pending.length > 0 ? earliestEvent(pending) : -1;
4064
- const eventAt = pending[next]?.at ?? 0;
4065
- const due = next >= 0 && eventAt <= run.now();
4066
- const canStart = active.length < spec.bounds.maxConcurrentInvocations && due;
4067
- const afterWorkOnly = active.length === 0 && run.hasAfterWork();
4068
- const timerDue = run.nextTimerDue(afterWorkOnly);
4069
- const untilEvent = next >= 0 && !due && active.length < spec.bounds.maxConcurrentInvocations && (timerDue ?? Number.POSITIVE_INFINITY) > eventAt;
4070
- const turn = run.takeTurn(canStart, afterWorkOnly, untilEvent || timerDue !== void 0);
4071
- if (turn === "start") {
4072
- const [event] = pending.splice(next, 1);
4073
- const d = {
4074
- started: run.startDelivery(() => platform.deliver(event, run, spec)),
4075
- outcome: null
4076
- };
4077
- d.started.promise.then((result) => {
4078
- d.outcome = { result };
4079
- run.rested();
4080
- }, (error) => {
4081
- d.outcome = { error };
4082
- run.rested();
4083
- });
4084
- active.push(d);
4085
- } else if (turn === "none" && untilEvent) {
4086
- if (!await run.advanceTo(eventAt)) continue;
4087
- } else if (turn === "none" && !(active.length > 0 || !run.hasAfterWork() ? run.fireTimer() : run.fireAfterWorkTimer()) && run.settleAfterWork() === 0) {
4088
- const stuck = active.flatMap((d) => d.started.invocation() ?? []);
4089
- if (run.abandon(stuck) === 0) {
4090
- const ending = active.filter((d) => run.hasCrashed(d.started.invocation()));
4091
- if (!await run.ended(ending.map((d) => d.started.promise))) throw new Error(`the ${platform.name} platform's delivery made no progress and cannot be abandoned`);
4092
- }
4093
- }
4094
- await run.quiesce();
4095
- }
4096
- }
4097
- /** Run the scenario once under the given run's fault decisions and return its log. */
4098
- async function runOnce(spec, platform, run) {
4099
- await platform.reset(spec);
4100
- run.install(spec.externals);
4101
- try {
4102
- try {
4103
- if (!run.concurrent) await deliverInOrder(spec, platform, run);
4104
- else if (platform.concurrent) await deliverConcurrently(spec, platform, run);
4105
- else throw new Error(`the ${platform.name} platform delivers one event at a time`);
4106
- } finally {
4107
- run.uninstall();
4108
- }
4109
- await platform.finish?.(spec, run);
4110
- } finally {
4111
- await platform.cleanup?.(spec);
4112
- }
4113
- return run.log;
4114
- }
4115
- /** Re-run a recorded schedule exactly and return the whole run (log and support status). */
4116
- async function replayRun(spec, platform, schedule) {
4117
- const run = new Run({
4118
- bounds: spec.bounds,
4119
- chooser: replayChooser(schedule)
4120
- });
4121
- await runOnce(spec, platform, run);
4122
- return run;
4123
- }
4124
4280
  /** One run of a pinned schedule under one seed: the run, its chooser and its log. */
4125
- async function pinnedRun(spec, platform, pinned, seed) {
4281
+ async function pinnedRun(spec, platform, pinned, seed, turns) {
4126
4282
  const chooser = pinnedChooser(pinned, seed);
4127
4283
  const run = new Run({
4128
4284
  bounds: spec.bounds,
4129
- chooser
4285
+ chooser,
4286
+ turns: turns || pinned.effectsAsTurns === true
4130
4287
  });
4131
4288
  return {
4132
4289
  run,
@@ -4141,7 +4298,9 @@ async function pinnedRun(spec, platform, pinned, seed) {
4141
4298
  async function runPinned(spec, platform, pinned, seed = pinnedSeeds(pinned)[0] ?? 0) {
4142
4299
  const errors = validatePinnedSchedules([pinned]);
4143
4300
  if (errors.length > 0) throw new Error(errors.join("; "));
4144
- const { run, chooser, log } = await pinnedRun(spec, platform, pinned, seed);
4301
+ if (pinned.effectsAsTurns === true) mustTakeTurns(platform, `pinned schedule ${JSON.stringify(pinned.name)}`);
4302
+ let { run, chooser, log } = await pinnedRun(spec, platform, pinned, seed, false);
4303
+ if (run.parallelCalls?.turnsWouldOrder === true && takesTurns(platform)) ({run, chooser, log} = await pinnedRun(spec, platform, pinned, seed, true));
4145
4304
  return {
4146
4305
  log,
4147
4306
  schedule: run.schedule,
@@ -4159,6 +4318,27 @@ async function replay(spec, platform, schedule) {
4159
4318
  * found, and return the verdict. At most 100 runs of exploration unless `maxRuns` says otherwise.
4160
4319
  */
4161
4320
  async function explore(scenario, platform, options) {
4321
+ const start = (options.now ?? (() => Date.now()))();
4322
+ const first = await exploreAs(scenario, platform, options, {
4323
+ turns: false,
4324
+ start,
4325
+ runs: 0
4326
+ });
4327
+ if (!("parallelCalls" in first)) return first;
4328
+ const again = await exploreAs(scenario, platform, options, {
4329
+ turns: true,
4330
+ start,
4331
+ runs: first.runs
4332
+ });
4333
+ if ("parallelCalls" in again) throw new Error("a run whose effects are turns reported parallel calls");
4334
+ return again;
4335
+ }
4336
+ /**
4337
+ * `explore`, with every effect a turn whatever the bounds (`mode.turns`) or
4338
+ * not; `mode.start` and `mode.runs` are when the exploration began and the
4339
+ * runs it has made already.
4340
+ */
4341
+ async function exploreAs(scenario, platform, options, mode) {
4162
4342
  const budgetMs = options.budgetMs;
4163
4343
  if (budgetMs !== void 0 && !(Number.isFinite(budgetMs) && budgetMs > 0)) throw new Error(`budgetMs must be a positive finite number, got ${budgetMs}`);
4164
4344
  const spec = budgetMs === void 0 ? scenario : {
@@ -4177,17 +4357,33 @@ async function explore(scenario, platform, options) {
4177
4357
  ...engineAssumptions.slice(0, 1),
4178
4358
  faultAssumption(spec.bounds),
4179
4359
  ...engineAssumptions.slice(1),
4180
- concurrencyAssumption(spec.bounds),
4360
+ concurrencyAssumption(spec.bounds, mode.turns),
4181
4361
  ...explorationAssumption(options),
4182
4362
  ...spec.pinned === void 0 ? [] : [pinnedAssumption(spec.pinned)],
4183
4363
  ...platform.assumptions
4184
4364
  ];
4185
- const start = now();
4365
+ const start = mode.start;
4186
4366
  const reached = {
4187
- runs: 0,
4367
+ runs: mode.runs,
4188
4368
  effectPoints: 0,
4189
4369
  faultsInjected: 0
4190
4370
  };
4371
+ /**
4372
+ * Whether `run` showed an invocation's calls in parallel in an exploration that leaves them to
4373
+ * real time, on a platform where their effects can be turns: the exploration starts over.
4374
+ */
4375
+ const startsOver = (run) => !mode.turns && takesTurns(platform) && (run.parallelCalls?.turnsWouldOrder === true || run.schedule.effectsAsTurns === true);
4376
+ const over = (run) => ({
4377
+ parallelCalls: run.parallelCalls?.calls ?? "a replay showed calls in parallel",
4378
+ runs: reached.runs
4379
+ });
4380
+ /** The first parallel calls a run showed that nothing orders: their effects cannot be turns. */
4381
+ let leftToRealTime;
4382
+ /**
4383
+ * What a run that did not replay may owe to such calls, added to its reason; empty when none
4384
+ * were seen. It says they can make two runs differ, not that they did.
4385
+ */
4386
+ const unorderedCalls = () => leftToRealTime === void 0 ? "" : `; the run made calls in parallel that nothing orders here, and which of them lands first is real time's to say: ${leftToRealTime.calls} (${leftToRealTime.turnsWouldOrder ? `the ${platform.name} platform delivers one event at a time` : "they were made inside an effect that runs as one turn, as an object's are inside blockConcurrencyWhile"})`;
4191
4387
  const done = () => ({
4192
4388
  ...reached,
4193
4389
  elapsedMs: now() - start
@@ -4213,6 +4409,8 @@ async function explore(scenario, platform, options) {
4213
4409
  });
4214
4410
  if (spec.bounds.maxConcurrentInvocations > 1 && !concurrencySupported) return unsupported("unsupported_bounds", "maxConcurrentInvocations above 1 needs AsyncLocalStorage (Node, or workerd with nodejs_compat or nodejs_als)");
4215
4411
  if (spec.bounds.maxConcurrentInvocations > 1 && !platform.concurrent) return unsupported("unsupported_bounds", `maxConcurrentInvocations above 1 is not supported on the ${platform.name} platform yet`);
4412
+ const marked = (spec.pinned ?? []).find((p) => p.effectsAsTurns === true);
4413
+ if (marked !== void 0 && !takesTurns(platform)) return unsupported("unsupported_bounds", `pinned schedule ${JSON.stringify(marked.name)} was recorded with every effect a turn (effectsAsTurns), which ${cannotTakeTurns(platform)}`);
4216
4414
  /**
4217
4415
  * A run met something outside the model: the verdict carries its schedule and, when the run
4218
4416
  * replayed alone by its faults' calls gets there again (checked here, with one more run), the
@@ -4223,7 +4421,7 @@ async function explore(scenario, platform, options) {
4223
4421
  const reason = run.unsupportedReasons.join("; ");
4224
4422
  const verdict = unsupported("unsupported_api", reason, run.schedule);
4225
4423
  const replay = run.asPinned("the run that reached UNSUPPORTED");
4226
- const again = await pinnedRun(spec, platform, replay, run.schedule.seed);
4424
+ const again = await pinnedRun(spec, platform, replay, run.schedule.seed, mode.turns);
4227
4425
  reached.runs++;
4228
4426
  return again.chooser.unplaced().length === 0 && again.run.unsupportedReasons.join("; ") === reason ? {
4229
4427
  ...verdict,
@@ -4243,9 +4441,11 @@ async function explore(scenario, platform, options) {
4243
4441
  const replayedRun = await replayRun(spec, platform, schedule);
4244
4442
  const replayed = replayedRun.log;
4245
4443
  reached.runs++;
4444
+ if (startsOver(replayedRun)) return over(replayedRun);
4445
+ leftToRealTime ??= replayedRun.parallelCalls;
4246
4446
  if (replayedRun.unsupportedReasons.length > 0) return unsupported("unsupported_api", replayedRun.unsupportedReasons.join("; "), schedule);
4247
4447
  const differed = whatDiffered(log, replayed);
4248
- if (differed) return unsupported("not_replayable", `the violating run of seed ${schedule.seed} did not reproduce on replay: ${differed}`, schedule);
4448
+ if (differed) return unsupported("not_replayable", `the violating run of seed ${schedule.seed} did not reproduce on replay: ${differed}${unorderedCalls()}`, schedule);
4249
4449
  if (pinned !== void 0) return {
4250
4450
  ...base,
4251
4451
  kind: "VIOLATED",
@@ -4268,6 +4468,10 @@ async function explore(scenario, platform, options) {
4268
4468
  now
4269
4469
  });
4270
4470
  reached.runs += shrunk.runs;
4471
+ if (!mode.turns && shrunk.schedule.effectsAsTurns === true) return {
4472
+ parallelCalls: "a replay showed calls in parallel",
4473
+ runs: reached.runs
4474
+ };
4271
4475
  return {
4272
4476
  ...base,
4273
4477
  kind: "VIOLATED",
@@ -4292,8 +4496,10 @@ async function explore(scenario, platform, options) {
4292
4496
  */
4293
4497
  const witnesses = [];
4294
4498
  for (const pinned of spec.pinned ?? []) for (const seed of pinnedSeeds(pinned)) {
4295
- const { run, chooser, log } = await pinnedRun(spec, platform, pinned, seed);
4499
+ const { run, chooser, log } = await pinnedRun(spec, platform, pinned, seed, mode.turns);
4296
4500
  reached.runs++;
4501
+ if (startsOver(run)) return over(run);
4502
+ leftToRealTime ??= run.parallelCalls;
4297
4503
  reached.effectPoints += run.effectPoints;
4298
4504
  reached.faultsInjected += run.faultsInjected;
4299
4505
  if (run.unsupportedReasons.length > 0) return await unsupportedApi(run);
@@ -4327,10 +4533,13 @@ async function explore(scenario, platform, options) {
4327
4533
  faultPlan,
4328
4534
  faultProbability,
4329
4535
  maxFaultsPerRun: spec.bounds.maxFaultsPerRun
4330
- })
4536
+ }),
4537
+ turns: mode.turns
4331
4538
  });
4332
4539
  const log = await runOnce(spec, platform, run);
4333
4540
  reached.runs++;
4541
+ if (startsOver(run)) return over(run);
4542
+ leftToRealTime ??= run.parallelCalls;
4334
4543
  if (run.faultsInjected === 0) baseline = Math.max(baseline, run.eligiblePoints);
4335
4544
  longest = Math.max(longest, run.eligiblePoints);
4336
4545
  if (run.eligiblePoints > 0) anyEligible = true;
@@ -4353,9 +4562,11 @@ async function explore(scenario, platform, options) {
4353
4562
  for (const witness of [...witnesses].reverse()) {
4354
4563
  const again = await replayRun(spec, platform, witness.schedule);
4355
4564
  reached.runs++;
4565
+ if (startsOver(again)) return over(again);
4566
+ leftToRealTime ??= again.parallelCalls;
4356
4567
  if (again.unsupportedReasons.length > 0) return unsupported("unsupported_api", again.unsupportedReasons.join("; "), witness.schedule);
4357
4568
  const differed = whatDiffered(witness.log, again.log);
4358
- if (differed) return unsupported("module_state_leak", `run seed ${witness.schedule.seed} produced a different log when replayed after other runs: state is leaking between runs (module-level variables, or a binding Eutaxy does not reset); ${differed}`, witness.schedule);
4569
+ if (differed) return leftToRealTime === void 0 ? unsupported("module_state_leak", `run seed ${witness.schedule.seed} produced a different log when replayed after other runs: state is leaking between runs (module-level variables, or a binding Eutaxy does not reset); ${differed}`, witness.schedule) : unsupported("not_replayable", `run seed ${witness.schedule.seed} produced a different log when replayed after other runs: either state is leaking between runs (module-level variables, or a binding Eutaxy does not reset) or two calls made in parallel landed in another order; ${differed}${unorderedCalls()}`, witness.schedule);
4359
4570
  }
4360
4571
  return {
4361
4572
  ...base,
@@ -4364,145 +4575,6 @@ async function explore(scenario, platform, options) {
4364
4575
  reached: doneNow()
4365
4576
  };
4366
4577
  }
4367
- // packages/engine/src/differential.ts
4368
- /**
4369
- * The platform-neutral part of a differential check: the same fault-free
4370
- * scenario once through Eutaxy and once against the raw bindings, then a
4371
- * comparison of what each attempt decided and of the final state. Any
4372
- * difference is a bug in the proxies or the platform model, not in the
4373
- * handler. The raw side's loop is here too (the same virtual globals and
4374
- * scripted externals as the proxied side, the same pick of the next event
4375
- * and the same redelivery rule); a platform writes only how one raw attempt
4376
- * calls its handler, sharing no proxy code.
4377
- */
4378
- /** The raw side cannot abandon an invocation the way the engine does; a stuck handler ends the comparison. */
4379
- var DifferentialStuck = class extends Error {
4380
- name = "DifferentialStuck";
4381
- constructor(message = "raw side: the handler is waiting on something outside the run (no effect in flight, no timer due)") {
4382
- super(message);
4383
- }
4384
- };
4385
- /**
4386
- * The Eutaxy side: one run with no faults, one event at a time whatever the
4387
- * scenario's bound (the raw side cannot interleave), with `attempt` given
4388
- * each delivery's event, result and log entries.
4389
- */
4390
- async function proxiedSide(spec, platform, attempt) {
4391
- const run = new Run({
4392
- bounds: {
4393
- ...spec.bounds,
4394
- maxConcurrentInvocations: 1
4395
- },
4396
- chooser: replayChooser({
4397
- seed: 0,
4398
- faults: []
4399
- })
4400
- });
4401
- const attempts = [];
4402
- const { finish, cleanup } = platform;
4403
- await runOnce(spec, {
4404
- name: platform.name,
4405
- assumptions: platform.assumptions,
4406
- ...platform.concurrent === void 0 ? {} : { concurrent: platform.concurrent },
4407
- reset: (s) => platform.reset(s),
4408
- initialEvents: (s) => platform.initialEvents(s),
4409
- restrictEvents: (s, keep) => platform.restrictEvents(s, keep),
4410
- async deliver(event, hooks, s) {
4411
- const before = run.log.entries.length;
4412
- const result = await platform.deliver(event, hooks, s);
4413
- attempts.push(attempt(event, result, run.log.entries.slice(before)));
4414
- return result;
4415
- },
4416
- ...finish ? { finish: (s, hooks) => finish.call(platform, s, hooks) } : {},
4417
- ...cleanup ? { cleanup: (s) => cleanup.call(platform, s) } : {}
4418
- }, run);
4419
- return {
4420
- attempts,
4421
- unsupported: run.unsupportedReasons
4422
- };
4423
- }
4424
- /**
4425
- * The raw side: every event delivered as the engine would deliver it with
4426
- * no faults and one invocation at a time (the earliest due first, time
4427
- * moved to a delayed one, an unhandled one delivered again under core's
4428
- * redelivery rule), each attempt performed by the platform. The attempts'
4429
- * records, in order.
4430
- */
4431
- async function rawRun(spec, side) {
4432
- const patched = patchGlobals(0);
4433
- const reasons = [];
4434
- const unsupported = (reason) => {
4435
- reasons.push(reason);
4436
- };
4437
- const restoreFetch = installScriptedFetch(spec.externals, null, unsupported, () => patched.clock.advance(1));
4438
- const io = { n: 0 };
4439
- const settle = (promise) => settleOn(promise, {
4440
- clock: patched.clock,
4441
- inFlight: () => io.n,
4442
- crashed: () => false,
4443
- stuck: () => {
4444
- throw new DifferentialStuck();
4445
- }
4446
- });
4447
- const call = async (code) => {
4448
- try {
4449
- return {
4450
- status: "completed",
4451
- value: await settle(Promise.resolve().then(code))
4452
- };
4453
- } catch (error) {
4454
- if (error instanceof DifferentialStuck) throw error;
4455
- return {
4456
- status: "errored",
4457
- error
4458
- };
4459
- }
4460
- };
4461
- const attempts = [];
4462
- const pending = [...side.events];
4463
- let restore;
4464
- try {
4465
- const installed = side.install({
4466
- clock: patched.clock,
4467
- io,
4468
- libraryIo: (perform) => patched.libraryIo(perform),
4469
- unsupported,
4470
- settle,
4471
- call
4472
- });
4473
- restore = installed.restore;
4474
- const { attempt } = installed;
4475
- while (pending.length > 0) {
4476
- const [event] = pending.splice(earliestEvent(pending), 1);
4477
- if (event.at !== void 0 && event.at > patched.clock.now()) patched.clock.advance(event.at - patched.clock.now());
4478
- const { record, handled } = await attempt(event);
4479
- attempts.push(record);
4480
- const next = handled ? null : redelivery(event, side.limit, spec.bounds);
4481
- if (next) pending.push(next);
4482
- }
4483
- } finally {
4484
- restore?.();
4485
- restoreFetch();
4486
- patched.restore();
4487
- }
4488
- if (reasons.length > 0) throw new DifferentialStuck(`raw side: ${reasons.join("; ")}`);
4489
- return attempts;
4490
- }
4491
- /** Every difference between the two sides, one readable entry each; none means they agree. */
4492
- function compareSides(eutaxy, raw, unsupported) {
4493
- const differences = [];
4494
- if (unsupported.length > 0) differences.push(`the proxied run touched unsupported APIs: ${unsupported.join("; ")}`);
4495
- const a = canonicalJson(eutaxy.attempts);
4496
- const b = canonicalJson(raw.attempts);
4497
- if (a !== b) differences.push(`attempts differ:\n eutaxy ${a}\n raw ${b}`);
4498
- const names = /* @__PURE__ */ new Set([...Object.keys(eutaxy.state), ...Object.keys(raw.state)]);
4499
- for (const name of [...names].sort()) {
4500
- const x = canonicalJson(eutaxy.state[name] ?? []);
4501
- const y = canonicalJson(raw.state[name] ?? []);
4502
- if (x !== y) differences.push(`${name} differs:\n eutaxy ${x}\n raw ${y}`);
4503
- }
4504
- return differences;
4505
- }
4506
4578
  // packages/engine/src/observe.ts
4507
4579
  /**
4508
4580
  * Observe a module's pure core functions while runs are installed: each call
@@ -4582,6 +4654,6 @@ function observeCore(namespace, functions) {
4582
4654
  }
4583
4655
  };
4584
4656
  }
4585
- export { readFaults as A, patchProperty as C, checkInvariant as D, validateScenario as E, seedPrng as F, getPath as I, invocationOf as L, nextFloat as M, nextInt as N, checkInvariants as O, nextU32 as P, redelivery as R, virtualEpoch as S, defaultBounds as T, parseBody as _, explore as a, withoutNetwork as b, restrictSpec as c, note as d, runInvocation as f, isRedirect as g, findResponse as h, rawRun as i, writeFaults as j, decisionFaults as k, decide as l, InjectedEffectError as m, compareSides as n, replay as o, CrashSignal as p, proxiedSide as r, runPinned as s, observeCore as t, hostInvocation as u, replyOf as v, toJson as w, realTick as x, toResponse as y, canonicalJson as z };
4657
+ export { readFaults as A, patchProperty as C, checkInvariant as D, validateScenario as E, redelivery as F, getPath as M, jsonEqual as N, checkInvariants as O, invocationOf as P, virtualEpoch as S, defaultBounds as T, parseBody as _, restrictSpec as a, withoutNetwork as b, rawRun as c, note as d, runInvocation as f, isRedirect as g, findResponse as h, runPinned as i, writeFaults as j, decisionFaults as k, decide as l, InjectedEffectError as m, explore as n, compareSides as o, CrashSignal as p, replay as r, proxiedSide as s, observeCore as t, hostInvocation as u, replyOf as v, toJson as w, realTick as x, toResponse as y };
4586
4658
 
4587
- //# sourceMappingURL=src-Whn0RMSh.mjs.map
4659
+ //# sourceMappingURL=src-D-MeEFn3.mjs.map