eutaxy 0.4.0 → 0.5.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.
@@ -113,6 +113,10 @@ function recomputePerMessageExpected(invariants, bodies) {
113
113
  };
114
114
  });
115
115
  }
116
+ /** The log target decisions of a core function are recorded under. */
117
+ function decisionTarget(fn) {
118
+ return `Core:${fn}`;
119
+ }
116
120
  /** The tables in the last snapshot recorded for a target, or undefined when none was. */
117
121
  function lastSnapshot(log, target) {
118
122
  for (let i = log.entries.length - 1; i >= 0; i--) {
@@ -204,8 +208,10 @@ function keyOf(record, path) {
204
208
  }
205
209
  function checkInvariant(log, inv) {
206
210
  switch (inv.kind) {
211
+ case "refines": return checkRefines(log, inv);
207
212
  case "everyRow": return checkEveryRow(log, inv);
208
213
  case "implies": return checkImplies(log, inv);
214
+ case "unique": return checkUnique(log, inv);
209
215
  case "atMostOncePerKey": {
210
216
  const seen = /* @__PURE__ */ new Map();
211
217
  for (const e of selectEffects(log, inv.effect)) {
@@ -259,6 +265,31 @@ function checkEveryRow(log, inv) {
259
265
  evidence: snapshotSeq(log, inv.query.target)
260
266
  };
261
267
  }
268
+ function checkUnique(log, inv) {
269
+ const rows = queryRows(log, inv.query);
270
+ if (rows === void 0) return {
271
+ invariant: inv.name,
272
+ message: `no snapshot of ${inv.query.target} was recorded`,
273
+ keys: [],
274
+ evidence: []
275
+ };
276
+ const counts = /* @__PURE__ */ new Map();
277
+ for (const r of rows) {
278
+ const v = getPath(r, inv.path);
279
+ if (v === void 0 || v === null) continue;
280
+ const k = canonicalJson(v);
281
+ counts.set(k, (counts.get(k) ?? 0) + 1);
282
+ }
283
+ const shared = [...counts].filter(([, n]) => n > 1);
284
+ if (shared.length === 0) return null;
285
+ const shown = shared.map(([k, n]) => `${n} rows of ${inv.query.table} in ${inv.query.target} share ${inv.path} = ${k}`);
286
+ return {
287
+ invariant: inv.name,
288
+ message: shown.join("; "),
289
+ keys: shared.map(([k]) => k),
290
+ evidence: snapshotSeq(log, inv.query.target)
291
+ };
292
+ }
262
293
  function checkImplies(log, inv) {
263
294
  const rows = queryRows(log, inv.state);
264
295
  if (rows === void 0) return {
@@ -288,6 +319,63 @@ function checkImplies(log, inv) {
288
319
  evidence
289
320
  };
290
321
  }
322
+ function checkRefines(log, inv) {
323
+ const target = decisionTarget(inv.decision);
324
+ const before = (seq, invocation, pick) => {
325
+ let found;
326
+ for (const e of log.entries) {
327
+ if (e.seq >= seq) break;
328
+ if (e.invocation === invocation && pick(e)) found = e;
329
+ }
330
+ return found;
331
+ };
332
+ for (const effect of selectEffects(log, inv.effect)) {
333
+ const what = `${effect.target} ${effect.op} (seq ${effect.seq}) in ${effect.invocation}`;
334
+ const decision = before(effect.seq, effect.invocation, (e) => e.target === target && e.kind === "result" && getPath(e.payload, "error") === void 0);
335
+ if (!decision) return {
336
+ invariant: inv.name,
337
+ message: `${what} carries out no decision: ${inv.decision} was not called before it in that invocation`,
338
+ keys: ["no_decision"],
339
+ evidence: [effect.seq]
340
+ };
341
+ for (const pair of inv.follows ?? []) {
342
+ const got = getPath(effect.payload, pair.effect);
343
+ const want = getPath(decision.payload, pair.decision);
344
+ if (want === void 0 ? got !== void 0 : !jsonEqual(got, want)) {
345
+ const show = (v) => v === void 0 ? "nothing" : canonicalJson(v);
346
+ return {
347
+ invariant: inv.name,
348
+ message: `${what} does not follow the decision at seq ${decision.seq}: ${pair.effect} is ${show(got)} but the decision's ${pair.decision} is ${show(want)}`,
349
+ keys: ["not_followed", pair.effect],
350
+ evidence: [decision.seq, effect.seq]
351
+ };
352
+ }
353
+ }
354
+ const state = inv.state;
355
+ if (!state) continue;
356
+ const read = before(decision.seq, effect.invocation, (e) => matches(e, state.read));
357
+ if (!read) return {
358
+ invariant: inv.name,
359
+ message: `${what} carries out the decision at seq ${decision.seq}, which rests on no read of the state: ${state.read.target} ${state.read.op ?? "*"} was not read before it in that invocation`,
360
+ keys: ["no_read"],
361
+ evidence: [decision.seq, effect.seq]
362
+ };
363
+ const key = state.key === void 0 ? void 0 : keyOf(read, state.key);
364
+ const write = log.entries.find((e) => e.seq > read.seq && e.seq < effect.seq && e.invocation !== effect.invocation && matches(e, state.write) && (state.key === void 0 || keyOf(e, state.key) === key));
365
+ if (write) return {
366
+ invariant: inv.name,
367
+ message: `${what} carries out a decision made on a stale read: the decision at seq ${decision.seq} rests on the read at seq ${read.seq}${key === void 0 ? "" : ` of ${key}`}, and ${write.invocation} changed it at seq ${write.seq} before the effect committed`,
368
+ keys: ["stale_read", ...key === void 0 ? [] : [key]],
369
+ evidence: [
370
+ read.seq,
371
+ decision.seq,
372
+ write.seq,
373
+ effect.seq
374
+ ]
375
+ };
376
+ }
377
+ return null;
378
+ }
291
379
  function checkInvariants(log, invariants) {
292
380
  const out = [];
293
381
  for (const inv of invariants) {
@@ -326,6 +414,12 @@ function validateScenario(spec) {
326
414
  else if (names.has(inv.name)) errors.push(`duplicate invariant name ${JSON.stringify(inv.name)}`);
327
415
  names.add(inv.name);
328
416
  }
417
+ const specs = /* @__PURE__ */ new Set();
418
+ for (const m of spec.specs ?? []) {
419
+ if (!m) errors.push("every specs entry needs a module path");
420
+ else if (specs.has(m)) errors.push(`duplicate specs module ${JSON.stringify(m)}`);
421
+ specs.add(m);
422
+ }
329
423
  const ext = /* @__PURE__ */ new Set();
330
424
  for (const e of spec.externals) {
331
425
  if (!e.name) errors.push("every external needs a name");
@@ -354,7 +448,7 @@ function shrinkCandidates(state) {
354
448
  state.schedule.faults.forEach((_, i) => {
355
449
  out.push({
356
450
  schedule: {
357
- seed: state.schedule.seed,
451
+ ...state.schedule,
358
452
  faults: state.schedule.faults.filter((_, j) => j !== i)
359
453
  },
360
454
  keepIds: state.keepIds
@@ -363,7 +457,7 @@ function shrinkCandidates(state) {
363
457
  if (state.keepIds.length > 1) state.keepIds.forEach((id) => {
364
458
  out.push({
365
459
  schedule: {
366
- seed: state.schedule.seed,
460
+ ...state.schedule,
367
461
  faults: state.schedule.faults.filter((f) => !f.invocation.startsWith(`${id}#`))
368
462
  },
369
463
  keepIds: state.keepIds.filter((k) => k !== id)
@@ -371,6 +465,12 @@ function shrinkCandidates(state) {
371
465
  });
372
466
  return out;
373
467
  }
468
+ // packages/engine/src/context.ts
469
+ /** A new async context slot, or null where the host has no AsyncLocalStorage. */
470
+ function asyncScope() {
471
+ const mod = typeof process !== "undefined" ? process?.getBuiltinModule?.("node:async_hooks") : void 0;
472
+ return mod?.AsyncLocalStorage ? new mod.AsyncLocalStorage() : null;
473
+ }
374
474
  // packages/engine/src/clock.ts
375
475
  /**
376
476
  * The virtual clock and the globals patch. Within a run, Date, Math.random,
@@ -387,16 +487,25 @@ const realSetTimeout = globalThis.setTimeout.bind(globalThis);
387
487
  const realSetInterval = globalThis.setInterval.bind(globalThis);
388
488
  const realClearTimeout = globalThis.clearTimeout.bind(globalThis);
389
489
  const realClearInterval = globalThis.clearInterval.bind(globalThis);
390
- const libraryScope = (() => {
391
- const mod = typeof process !== "undefined" ? process?.getBuiltinModule?.("node:async_hooks") : void 0;
392
- return mod?.AsyncLocalStorage ? new mod.AsyncLocalStorage() : null;
393
- })();
490
+ /**
491
+ * Tells library code apart from handler code while an effect's real I/O runs.
492
+ * SDKs back off and time out with timers, which must be real; a handler timer
493
+ * scheduled meanwhile must stay virtual. Node's AsyncLocalStorage follows the
494
+ * library's promise chains and I/O callbacks but not the handler's own
495
+ * continuations. Where it is unavailable (workerd without Node compatibility)
496
+ * every timer stays virtual; the Cloudflare bindings do not use timers.
497
+ */
498
+ const libraryScope = asyncScope();
394
499
  var VirtualClock = class {
395
500
  time = virtualEpoch;
396
501
  timers = [];
397
502
  nextId = 1;
398
503
  /** The invocation whose code is running; timers scheduled now belong to it. */
399
504
  owner = null;
505
+ /** Set by a concurrent run: who is running, asked when a timer is scheduled (overrides `owner`). */
506
+ ownerNow = null;
507
+ /** Set by a concurrent run: binds a callback to the async context it was scheduled in. */
508
+ bind = null;
400
509
  now() {
401
510
  return this.time;
402
511
  }
@@ -408,10 +517,10 @@ var VirtualClock = class {
408
517
  const timer = {
409
518
  id: this.nextId++,
410
519
  due: this.time + ms,
411
- callback,
520
+ callback: this.bind ? this.bind(callback) : callback,
412
521
  args,
413
522
  interval,
414
- owner: this.owner
523
+ owner: this.ownerNow ? this.ownerNow() : this.owner
415
524
  };
416
525
  this.timers.push(timer);
417
526
  return timer.id;
@@ -436,11 +545,23 @@ var VirtualClock = class {
436
545
  cancelOwner(owner) {
437
546
  this.timers = this.timers.filter((t) => t.owner !== owner);
438
547
  }
548
+ earliest() {
549
+ let earliest = this.timers[0];
550
+ for (const t of this.timers) if (earliest && (t.due < earliest.due || t.due === earliest.due && t.id < earliest.id)) earliest = t;
551
+ return earliest;
552
+ }
553
+ /** When the next timer is due, or undefined when none is pending. */
554
+ nextDue() {
555
+ return this.earliest()?.due;
556
+ }
557
+ /** Who set the timer `fireNext` would run: an invocation, null for none, undefined when no timer is pending. */
558
+ nextOwner() {
559
+ return this.earliest()?.owner;
560
+ }
439
561
  /** Advance to the earliest due timer and run it. False when none is pending. */
440
562
  fireNext() {
441
- if (this.timers.length === 0) return false;
442
- let earliest = this.timers[0];
443
- for (const t of this.timers) if (t.due < earliest.due || t.due === earliest.due && t.id < earliest.id) earliest = t;
563
+ const earliest = this.earliest();
564
+ if (!earliest) return false;
444
565
  if (earliest.due > this.time) this.time = earliest.due;
445
566
  if (earliest.interval === null) this.timers = this.timers.filter((t) => t !== earliest);
446
567
  else earliest.due = this.time + earliest.interval;
@@ -483,16 +604,40 @@ var VirtualRandom = class {
483
604
  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
484
605
  }
485
606
  };
607
+ /** Web Crypto's asynchronous methods: real work that always finishes on its own. */
608
+ const subtleMethods = [
609
+ "encrypt",
610
+ "decrypt",
611
+ "sign",
612
+ "verify",
613
+ "digest",
614
+ "generateKey",
615
+ "deriveKey",
616
+ "deriveBits",
617
+ "importKey",
618
+ "exportKey",
619
+ "wrapKey",
620
+ "unwrapKey"
621
+ ];
486
622
  /** Replace the nondeterministic globals for one run. Returns the handle that restores them. */
487
- function patchGlobals(seed) {
623
+ function patchGlobals(seed, options = {}) {
488
624
  const clock = new VirtualClock();
489
625
  const random = new VirtualRandom(seed);
626
+ const reads = { count: 0 };
627
+ const inLibrary = () => libraryScope?.getStore() === true;
628
+ /** Counts a read of the shared virtual state, an effect's own I/O included: its result may depend on it. */
629
+ const read = () => {
630
+ reads.count++;
631
+ };
490
632
  const g = globalThis;
491
- const saved = /* @__PURE__ */ new Map();
633
+ const saved = [];
492
634
  const define = (target, key, value) => {
493
- const owner = target === g ? g : target;
494
- saved.set(key, Object.getOwnPropertyDescriptor(owner, key));
495
- Object.defineProperty(owner, key, {
635
+ saved.push({
636
+ target,
637
+ key,
638
+ descriptor: Object.getOwnPropertyDescriptor(target, key)
639
+ });
640
+ Object.defineProperty(target, key, {
496
641
  value,
497
642
  configurable: true,
498
643
  writable: true,
@@ -501,6 +646,7 @@ function patchGlobals(seed) {
501
646
  };
502
647
  const RealDate = Date;
503
648
  const VirtualDate = function(...args) {
649
+ if (new.target === void 0 || args.length === 0) read();
504
650
  if (new.target === void 0) return new RealDate(clock.now()).toString();
505
651
  return Reflect.construct(RealDate, args.length === 0 ? [clock.now()] : args, new.target);
506
652
  };
@@ -510,16 +656,29 @@ function patchGlobals(seed) {
510
656
  writable: false
511
657
  });
512
658
  Object.defineProperty(VirtualDate, "now", {
513
- value: () => clock.now(),
659
+ value: () => {
660
+ read();
661
+ return clock.now();
662
+ },
514
663
  configurable: true,
515
664
  writable: true
516
665
  });
517
666
  Object.defineProperty(VirtualDate, "name", { value: "Date" });
518
667
  define(g, "Date", VirtualDate);
519
- define(Math, "random", () => random.float());
520
- const inLibrary = () => libraryScope?.getStore() === true;
521
- define(g, "setTimeout", (cb, ms, ...args) => inLibrary() ? realSetTimeout(cb, ms, ...args) : clock.setTimeout(cb, ms, ...args));
522
- define(g, "setInterval", (cb, ms, ...args) => inLibrary() ? realSetInterval(cb, ms, ...args) : clock.setInterval(cb, ms, ...args));
668
+ define(Math, "random", () => {
669
+ read();
670
+ return random.float();
671
+ });
672
+ define(g, "setTimeout", (cb, ms, ...args) => {
673
+ if (inLibrary()) return realSetTimeout(cb, ms, ...args);
674
+ read();
675
+ return clock.setTimeout(cb, ms, ...args);
676
+ });
677
+ define(g, "setInterval", (cb, ms, ...args) => {
678
+ if (inLibrary()) return realSetInterval(cb, ms, ...args);
679
+ read();
680
+ return clock.setInterval(cb, ms, ...args);
681
+ });
523
682
  define(g, "clearTimeout", (id) => {
524
683
  if (clock.owns(id)) clock.clear(id);
525
684
  else realClearTimeout(id);
@@ -529,47 +688,69 @@ function patchGlobals(seed) {
529
688
  else realClearInterval(id);
530
689
  });
531
690
  const perf = g["performance"];
532
- if (perf && typeof perf === "object") define(perf, "now", () => clock.now() - virtualEpoch);
691
+ if (perf && typeof perf === "object") define(perf, "now", () => {
692
+ read();
693
+ return clock.now() - virtualEpoch;
694
+ });
533
695
  const cryptoObj = g["crypto"];
534
696
  if (cryptoObj && typeof cryptoObj === "object") {
535
- define(cryptoObj, "randomUUID", () => random.uuid());
536
- define(cryptoObj, "getRandomValues", (view) => random.fill(view));
697
+ define(cryptoObj, "randomUUID", () => {
698
+ read();
699
+ return random.uuid();
700
+ });
701
+ define(cryptoObj, "getRandomValues", (view) => {
702
+ read();
703
+ return random.fill(view);
704
+ });
705
+ const subtle = cryptoObj.subtle;
706
+ const trackIo = options.trackIo;
707
+ if (trackIo && subtle && typeof subtle === "object") for (const name of subtleMethods) {
708
+ const real = subtle[name];
709
+ if (typeof real !== "function") continue;
710
+ define(subtle, name, function(...args) {
711
+ return trackIo(Promise.resolve(real.apply(this, args)));
712
+ });
713
+ }
537
714
  }
538
715
  let restored = false;
539
- const targets = {
540
- Date: g,
541
- random: Math,
542
- setTimeout: g,
543
- setInterval: g,
544
- clearTimeout: g,
545
- clearInterval: g
546
- };
547
- if (perf && typeof perf === "object") targets["now"] = perf;
548
- if (cryptoObj && typeof cryptoObj === "object") {
549
- targets["randomUUID"] = cryptoObj;
550
- targets["getRandomValues"] = cryptoObj;
551
- }
552
716
  return {
553
717
  clock,
554
718
  random,
719
+ reads,
555
720
  libraryIo(perform) {
556
721
  return libraryScope ? libraryScope.run(true, perform) : perform();
557
722
  },
558
723
  restore() {
559
724
  if (restored) return;
560
725
  restored = true;
561
- for (const [key, descriptor] of saved) {
562
- const target = targets[key];
563
- if (descriptor) Object.defineProperty(target, key, descriptor);
564
- else delete target[key];
565
- }
726
+ for (const { target, key, descriptor } of saved.reverse()) if (descriptor) Object.defineProperty(target, key, descriptor);
727
+ else delete target[key];
566
728
  }
567
729
  };
568
730
  }
731
+ /** A real-time deadline: `expired` resolves after `ms` unless cancelled first. */
732
+ function realDeadline(ms) {
733
+ let handle;
734
+ return {
735
+ expired: new Promise((resolve) => {
736
+ handle = realSetTimeout(() => resolve("expired"), ms);
737
+ }),
738
+ cancel: () => realClearTimeout(handle)
739
+ };
740
+ }
569
741
  /** Yield to the real event loop so microtasks and pending I/O can make progress. */
570
742
  function realTick() {
571
743
  return new Promise((resolve) => realSetTimeout(() => resolve(), 0));
572
744
  }
745
+ const realSetImmediate = globalThis.setImmediate?.bind(globalThis);
746
+ /**
747
+ * Let every pending microtask run, and I/O callbacks that are already due:
748
+ * one turn of the real event loop without a timer's delay where the host has
749
+ * `setImmediate`, else a zero timer.
750
+ */
751
+ function drainMicrotasks() {
752
+ return realSetImmediate ? new Promise((resolve) => realSetImmediate(() => resolve())) : realTick();
753
+ }
573
754
  /**
574
755
  * Wait for a promise under the virtual clock: while it is pending, let real
575
756
  * I/O complete, and when the invocation is idle fire the next due timer.
@@ -600,6 +781,87 @@ async function settleOn(promise, ctx) {
600
781
  return new Promise(() => {});
601
782
  }
602
783
  }
784
+ // packages/engine/src/exhaustive.ts
785
+ /** Whether two turns commute: different invocations, effects on different targets. */
786
+ function independent(a, b) {
787
+ 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;
788
+ }
789
+ const asleep = /* @__PURE__ */ new Map();
790
+ var Enumerator = class {
791
+ stack = [];
792
+ depth = 0;
793
+ /** The depth of the first node in the run just made whose every option was asleep, or null. */
794
+ blockedAt = null;
795
+ mismatchReason = null;
796
+ reduction;
797
+ constructor(options) {
798
+ this.reduction = options.reduction;
799
+ }
800
+ /** Whether the run just made repeats an explored order (every option at some point was asleep). */
801
+ get blocked() {
802
+ return this.blockedAt !== null;
803
+ }
804
+ /** Set when a run made different choices than the same prefix did before: not deterministic. */
805
+ get mismatch() {
806
+ return this.mismatchReason;
807
+ }
808
+ /** The chooser for the next run: the explored prefix, then the first option not asleep. */
809
+ next() {
810
+ this.depth = 0;
811
+ this.blockedAt = null;
812
+ return { choose: (kind, options) => this.choose(kind, options) };
813
+ }
814
+ choose(kind, options) {
815
+ const i = this.depth++;
816
+ const known = this.stack[i];
817
+ if (known) {
818
+ 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(", ")})`;
819
+ return known.picked < options.length ? known.picked : 0;
820
+ }
821
+ if (this.blockedAt !== null) return 0;
822
+ const sleep = this.sleepAt(i);
823
+ let picked = kind === "turn" ? options.findIndex((o) => !sleep.has(o.label)) : 0;
824
+ if (picked < 0) {
825
+ this.blockedAt = i;
826
+ picked = 0;
827
+ }
828
+ this.stack.push({
829
+ kind,
830
+ options,
831
+ picked,
832
+ done: [],
833
+ sleep
834
+ });
835
+ return picked;
836
+ }
837
+ /** The sleep set of a new node at depth i, from its parent's. */
838
+ sleepAt(i) {
839
+ const parent = this.stack[i - 1];
840
+ if (!this.reduction || !parent) return asleep;
841
+ if (parent.kind === "fault") return parent.sleep;
842
+ const taken = parent.options[parent.picked];
843
+ if (!taken) return asleep;
844
+ const sleep = /* @__PURE__ */ new Map();
845
+ const candidates = [...parent.sleep.values(), ...parent.done.map((j) => parent.options[j])];
846
+ for (const c of candidates) if (c && independent(c, taken)) sleep.set(c.label, c);
847
+ return sleep;
848
+ }
849
+ /** Move to the next schedule after a run. False once every schedule has been explored. */
850
+ advance() {
851
+ this.stack.length = Math.min(this.stack.length, this.depth, (this.blockedAt ?? Infinity) + 1);
852
+ while (this.stack.length > 0) {
853
+ const node = this.stack[this.stack.length - 1];
854
+ if (!node.done.includes(node.picked)) node.done.push(node.picked);
855
+ const next = node.options.findIndex((o, j) => !node.done.includes(j) && (node.kind === "fault" || !node.sleep.has(o.label)));
856
+ if (next >= 0) {
857
+ node.picked = next;
858
+ return true;
859
+ }
860
+ this.stack.pop();
861
+ }
862
+ return false;
863
+ }
864
+ };
603
865
  // packages/engine/src/fetch.ts
604
866
  const FAULTS = [
605
867
  "crash_before",
@@ -760,12 +1022,49 @@ function installScriptedFetch(externals, hooks, unsupported, afterRequest) {
760
1022
  else delete g.fetch;
761
1023
  };
762
1024
  }
1025
+ /**
1026
+ * Run platform work (a reset, a snapshot) with no network: `fetch` rejects
1027
+ * while it runs. Reports whether anything tried, so code that runs outside
1028
+ * the simulation (an object's constructor during a reset) cannot reach the
1029
+ * network unseen.
1030
+ */
1031
+ async function withoutNetwork(work) {
1032
+ let requested = false;
1033
+ const saved = Object.getOwnPropertyDescriptor(globalThis, "fetch");
1034
+ Object.defineProperty(globalThis, "fetch", {
1035
+ value: async () => {
1036
+ requested = true;
1037
+ throw new TypeError("network access is blocked while Eutaxy resets or snapshots state");
1038
+ },
1039
+ configurable: true,
1040
+ writable: true
1041
+ });
1042
+ try {
1043
+ return {
1044
+ value: await work(),
1045
+ requested
1046
+ };
1047
+ } finally {
1048
+ if (saved) Object.defineProperty(globalThis, "fetch", saved);
1049
+ else delete globalThis.fetch;
1050
+ }
1051
+ }
763
1052
  // packages/engine/src/run.ts
764
1053
  /**
765
1054
  * One run of a scenario: the effect log being built, the fault decisions
766
1055
  * (drawn during exploration, looked up during replay), and the invocations
767
1056
  * in flight. Proxies in the platform package call `effect`/`effectSync`
768
1057
  * around every real effect; everything else is engine-internal.
1058
+ *
1059
+ * With `maxConcurrentInvocations` above 1 the run is concurrent: several
1060
+ * invocations are in flight. Each asynchronous effect is a turn: the
1061
+ * invocation parks there, and once every invocation has parked, finished or
1062
+ * gone idle the run picks which parked one goes next (or whether a new event
1063
+ * starts) from a stream seeded by the schedule's seed. Exploration and
1064
+ * replay make the same picks, so the schedule needs no record of them. Each
1065
+ * delivery runs in its own async context, so an effect is attributed to the
1066
+ * invocation whose code made it even when a promise shared between
1067
+ * invocations resumes one during another's turn.
769
1068
  */
770
1069
  /** Thrown into user code by a synchronous effect that crashes the invocation. */
771
1070
  var CrashSignal = class extends Error {
@@ -792,6 +1091,8 @@ var InvocationState = class {
792
1091
  onCrash;
793
1092
  /** Effect points seen so far in this invocation; the next effect's ordinal. */
794
1093
  ordinal = 0;
1094
+ /** Times this invocation has parked for a turn; names its next turn the same in every run. */
1095
+ parks = 0;
795
1096
  crashedFlag = false;
796
1097
  resolveCrashed = () => {};
797
1098
  id;
@@ -812,6 +1113,64 @@ var InvocationState = class {
812
1113
  this.resolveCrashed();
813
1114
  }
814
1115
  };
1116
+ const deliveryScope = asyncScope();
1117
+ /**
1118
+ * An effect being performed. An effect made inside it is nested in it; when
1119
+ * a crash is injected there, the nested effect hangs like any crashed
1120
+ * effect and tells this frame, so the enclosing effect ends too. User code
1121
+ * never sees the crash as an error it could catch.
1122
+ */
1123
+ var Frame = class {
1124
+ /** The invocation whose effect this is. */
1125
+ invocation;
1126
+ /** Whether the effect hosts user code that makes effects of its own (`hostsEffects`). */
1127
+ hosts;
1128
+ /** False once the effect's perform has ended. */
1129
+ active = true;
1130
+ /** The effect's `onAbandon`, called where the crash happens (inside the hosted code's context). */
1131
+ onAbandon;
1132
+ /** The effect's `mayPark`: whether an effect its hosted code makes may wait for a turn now. */
1133
+ mayPark;
1134
+ /** The hosting effect this one was made inside of and waited for a turn under, if any. */
1135
+ parent;
1136
+ /** Effects the hosted code made that are parked or running now. */
1137
+ children = 0;
1138
+ /** Of those, the ones parked, or running but only waiting on parked effects of their own. */
1139
+ waitingChildren = 0;
1140
+ abandoned = false;
1141
+ wake = () => {};
1142
+ crashed = new Promise((resolve) => {
1143
+ this.wake = () => resolve("nested_crash");
1144
+ });
1145
+ constructor(invocation, hosts, options) {
1146
+ this.invocation = invocation;
1147
+ this.hosts = hosts;
1148
+ this.onAbandon = options.onAbandon;
1149
+ this.mayPark = options.mayPark ?? (() => true);
1150
+ }
1151
+ /** Its hosted code is only waiting on effects of its own that are parked (however deep). */
1152
+ isWaiting() {
1153
+ return this.children > 0 && this.waitingChildren === this.children;
1154
+ }
1155
+ crash() {
1156
+ this.abandon();
1157
+ this.wake();
1158
+ }
1159
+ abandon() {
1160
+ if (this.abandoned) return;
1161
+ this.abandoned = true;
1162
+ this.onAbandon?.();
1163
+ }
1164
+ };
1165
+ /** The frame of the effect whose `perform` the current code runs inside. */
1166
+ const effectScope = asyncScope();
1167
+ /** The run whose globals are installed, if any: where code observed from outside records into. */
1168
+ let installed = null;
1169
+ function installedRun() {
1170
+ return installed;
1171
+ }
1172
+ /** Whether this host can run concurrent invocations: attribution needs async context. */
1173
+ const concurrencySupported = deliveryScope !== null;
815
1174
  /** A promise that never settles: how an abandoned invocation experiences a crash. */
816
1175
  function hang() {
817
1176
  return new Promise(() => {});
@@ -824,23 +1183,55 @@ var Run = class {
824
1183
  invocations = /* @__PURE__ */ new Map();
825
1184
  reasons = [];
826
1185
  inFlight = 0;
1186
+ /** Effects being performed, innermost last (the nesting test where there is no async context). */
1187
+ frames = [];
1188
+ /** Per invocation, its effects with `hostsEffects` being performed, innermost last. */
1189
+ hosting = /* @__PURE__ */ new Map();
1190
+ /** Effects with `hostsEffects` being performed now, across invocations. */
1191
+ hostingNow = 0;
827
1192
  patched = null;
828
1193
  restoreFetch = null;
829
1194
  /** The invocation whose code is running (one at a time); outbound fetches are attributed to it. */
830
1195
  current = "";
1196
+ /** Concurrent runs only: invocations waiting at an effect for their turn. */
1197
+ parked = [];
1198
+ /** The turns picked at decisions with more than one option, in order (see Schedule.turns). */
1199
+ turnPicks = [];
1200
+ /** Turns taken from `schedule.turns` so far, when replaying recorded turns. */
1201
+ turnReplayed = 0;
1202
+ /** Events started so far, to name the next start the same in every run. */
1203
+ starts = 0;
1204
+ /** The target of the turn running since the last decision; null for an event's start or none. */
1205
+ turnTarget = null;
1206
+ turnsCommuteNot = false;
1207
+ parkSeq = 0;
1208
+ /** Events a platform queued during a delivery, for the run loop to pick up. */
1209
+ queued = [];
1210
+ /** Concurrent runs only: woken whenever an invocation parks, a delivery ends or I/O completes. */
1211
+ progressWaiters = [];
1212
+ /** Concurrent runs only: the order invocations started in, which orders the parked ones. */
1213
+ startOrder = /* @__PURE__ */ new Map();
1214
+ /** Concurrent runs only: the picks among parked invocations, drawn apart from fault decisions. */
1215
+ turns;
1216
+ /** Whether several invocations may be in flight (`maxConcurrentInvocations` above 1). */
1217
+ concurrent;
831
1218
  options;
832
1219
  constructor(options) {
833
1220
  this.options = options;
834
1221
  this.prng = seedPrng(options.schedule.seed);
1222
+ this.turns = seedPrng(`turns:${options.schedule.seed}`);
1223
+ this.concurrent = options.bounds.maxConcurrentInvocations > 1;
835
1224
  }
836
1225
  get log() {
837
1226
  return this.logState;
838
1227
  }
839
1228
  /** The schedule as actually executed: input decisions during replay, drawn ones during exploration. */
840
1229
  get schedule() {
1230
+ const recorded = this.options.chooser !== void 0 || this.options.schedule.turns !== void 0;
841
1231
  return {
842
1232
  seed: this.options.schedule.seed,
843
- faults: [...this.faults]
1233
+ faults: [...this.faults],
1234
+ ...recorded ? { turns: [...this.turnPicks] } : {}
844
1235
  };
845
1236
  }
846
1237
  get effectPoints() {
@@ -849,18 +1240,65 @@ var Run = class {
849
1240
  get faultsInjected() {
850
1241
  return this.faults.length;
851
1242
  }
1243
+ /**
1244
+ * Whether a turn other than an event's start did more than its own effect:
1245
+ * performed an effect on another target (synchronous, or nested in it),
1246
+ * queued events, or read virtual time or randomness (effects advance the clock and draws the
1247
+ * stream). Turns told apart by their parked effects' targets need not
1248
+ * commute then. A start is ordered against every turn anyway, so what it
1249
+ * does does not count.
1250
+ */
1251
+ get turnsMayNotCommute() {
1252
+ this.endSegment();
1253
+ return this.turnsCommuteNot;
1254
+ }
1255
+ /**
1256
+ * Concurrent runs: events were queued since the last decision (follow-ups
1257
+ * of a delivery that ended, or `enqueue`). The queue's order is shared, so
1258
+ * within a turn this is another dependence.
1259
+ */
1260
+ queuedEvents() {
1261
+ if (this.turnTarget !== null) this.turnsCommuteNot = true;
1262
+ }
1263
+ /** Close the code run since the last decision, noting whether a turn read the shared virtual state. */
1264
+ endSegment() {
1265
+ const reads = this.patched?.reads;
1266
+ if (!reads) return;
1267
+ if (this.turnTarget !== null && reads.count > 0) this.turnsCommuteNot = true;
1268
+ reads.count = 0;
1269
+ }
852
1270
  get unsupportedReasons() {
853
1271
  return this.reasons;
854
1272
  }
855
1273
  /** Replace the nondeterministic globals and `fetch` for this run. Call `uninstall` in a finally. */
856
1274
  install(externals = []) {
857
- if (!this.patched) this.patched = patchGlobals(this.options.schedule.seed);
1275
+ installed = this;
1276
+ if (!this.patched) {
1277
+ this.patched = patchGlobals(this.options.schedule.seed, { trackIo: (work) => {
1278
+ this.inFlight++;
1279
+ return work.finally(() => {
1280
+ this.inFlight--;
1281
+ if (this.concurrent) this.progressed();
1282
+ });
1283
+ } });
1284
+ if (this.concurrent) {
1285
+ const clock = this.patched.clock;
1286
+ clock.ownerNow = () => this.running();
1287
+ clock.bind = (callback) => {
1288
+ const cell = deliveryScope?.getStore();
1289
+ if (!cell || !deliveryScope) return callback;
1290
+ const scope = deliveryScope;
1291
+ return (...args) => scope.run(cell, () => callback(...args));
1292
+ };
1293
+ }
1294
+ }
858
1295
  if (!this.restoreFetch) this.restoreFetch = installScriptedFetch(externals, {
859
1296
  hooks: this,
860
- invocation: () => this.current
1297
+ invocation: () => this.running()
861
1298
  }, (reason) => this.unsupported(reason));
862
1299
  }
863
1300
  uninstall() {
1301
+ if (installed === this) installed = null;
864
1302
  this.restoreFetch?.();
865
1303
  this.restoreFetch = null;
866
1304
  this.patched?.restore();
@@ -874,20 +1312,61 @@ var Run = class {
874
1312
  pendingTimers() {
875
1313
  return this.patched?.clock.pendingTimers() ?? 0;
876
1314
  }
877
- startInvocation(id) {
1315
+ startInvocation(id, options = {}) {
878
1316
  if (this.invocations.has(id)) throw new Error(`invocation ${id} already started`);
879
1317
  const inv = new InvocationState(id, () => this.patched?.clock.cancelOwner(id));
880
1318
  this.invocations.set(id, inv);
881
- if (this.patched) this.patched.clock.owner = id;
882
- this.current = id;
1319
+ if (options.bookkeeping) return inv;
1320
+ if (this.concurrent) {
1321
+ this.startOrder.set(id, this.startOrder.size);
1322
+ const cell = deliveryScope?.getStore();
1323
+ if (cell && cell.id === null) {
1324
+ cell.id = id;
1325
+ this.runAs(id);
1326
+ }
1327
+ return inv;
1328
+ }
1329
+ this.runAs(id);
883
1330
  return inv;
884
1331
  }
1332
+ enqueue(event) {
1333
+ this.queued.push(event);
1334
+ if (this.concurrent) this.progressed();
1335
+ }
1336
+ /** Events platforms queued with `enqueue` since the last call. */
1337
+ takeQueued() {
1338
+ const queued = this.queued;
1339
+ this.queued = [];
1340
+ return queued;
1341
+ }
1342
+ hostingFrames(invocation) {
1343
+ let frames = this.hosting.get(invocation);
1344
+ if (!frames) {
1345
+ frames = [];
1346
+ this.hosting.set(invocation, frames);
1347
+ }
1348
+ return frames;
1349
+ }
1350
+ running() {
1351
+ if (!this.concurrent) return this.current;
1352
+ return deliveryScope?.getStore()?.id ?? this.current;
1353
+ }
1354
+ runAs(id) {
1355
+ if (this.patched) this.patched.clock.owner = id;
1356
+ if (id !== null) this.current = id;
1357
+ }
885
1358
  invocation(id) {
886
1359
  const inv = this.invocations.get(id);
887
1360
  if (!inv) throw new Error(`effect from unknown invocation ${id}`);
888
1361
  return inv;
889
1362
  }
890
1363
  decide(point, ordinal) {
1364
+ const chooser = this.options.chooser;
1365
+ if (chooser && this.options.mode === "explore") {
1366
+ if (point.allowed.length === 0 || this.faults.length >= this.options.bounds.maxFaultsPerRun) return null;
1367
+ const i = chooser.choose("fault", [{ label: "none" }, ...point.allowed.map((f) => ({ label: f }))]);
1368
+ return i === 0 ? null : point.allowed[i - 1] ?? null;
1369
+ }
891
1370
  if (this.options.mode === "replay") {
892
1371
  const d = this.options.schedule.faults.find((f) => f.invocation === point.invocation && f.ordinal === ordinal);
893
1372
  return d && point.allowed.includes(d.fault) ? d.fault : null;
@@ -900,6 +1379,7 @@ var Run = class {
900
1379
  return fault;
901
1380
  }
902
1381
  record(point, kind, payload) {
1382
+ if (kind === "result" && this.turnTarget !== null && point.target !== this.turnTarget) this.turnsCommuteNot = true;
903
1383
  this.logState = appendEffect(this.logState, {
904
1384
  kind,
905
1385
  invocation: point.invocation,
@@ -923,9 +1403,75 @@ var Run = class {
923
1403
  });
924
1404
  return fault;
925
1405
  }
926
- async effect(point, perform, summarize) {
1406
+ async effect(point, perform, summarize, options = {}) {
927
1407
  const inv = this.invocation(point.invocation);
928
1408
  if (inv.isCrashed()) return hang();
1409
+ const store = effectScope?.getStore();
1410
+ const live = store?.active && store.invocation === point.invocation ? store : void 0;
1411
+ const enclosing = effectScope ? live ?? this.hosting.get(point.invocation)?.at(-1) : this.frames.at(-1);
1412
+ const nested = enclosing !== void 0;
1413
+ if (this.concurrent && !nested) {
1414
+ await new Promise((go) => {
1415
+ this.parked.push({
1416
+ inv,
1417
+ seq: this.parkSeq++,
1418
+ go,
1419
+ option: this.turnOption(inv, point)
1420
+ });
1421
+ this.progressed();
1422
+ });
1423
+ if (inv.isCrashed()) return hang();
1424
+ } else if (this.concurrent && enclosing?.hosts && enclosing.mayPark()) {
1425
+ const host = enclosing;
1426
+ let released = false;
1427
+ this.adjust(host, () => {
1428
+ host.children++;
1429
+ host.waitingChildren++;
1430
+ });
1431
+ this.parked.push({
1432
+ inv,
1433
+ seq: this.parkSeq++,
1434
+ go: () => released = true,
1435
+ host,
1436
+ option: this.turnOption(inv, point)
1437
+ });
1438
+ this.progressed();
1439
+ while (!released && !inv.isCrashed()) await realTick();
1440
+ if (!released) {
1441
+ this.adjust(host, () => {
1442
+ host.children--;
1443
+ host.waitingChildren--;
1444
+ });
1445
+ return hang();
1446
+ }
1447
+ try {
1448
+ return await this.performEffect(point, perform, summarize, options, inv, enclosing, host);
1449
+ } finally {
1450
+ this.adjust(host, () => host.children--);
1451
+ }
1452
+ }
1453
+ return this.performEffect(point, perform, summarize, options, inv, enclosing);
1454
+ }
1455
+ /**
1456
+ * Change a hosting frame's children and keep `inFlight` in step: a frame
1457
+ * counts in flight unless it is only waiting on parked effects of its own,
1458
+ * and a frame that starts or stops waiting does so for its parent too.
1459
+ */
1460
+ adjust(frame, change) {
1461
+ const before = frame.isWaiting();
1462
+ change();
1463
+ const after = frame.isWaiting();
1464
+ if (before === after) return;
1465
+ if (frame.active) this.inFlight += after ? -1 : 1;
1466
+ const parent = frame.parent;
1467
+ if (frame.active && parent) this.adjust(parent, () => parent.waitingChildren += after ? 1 : -1);
1468
+ }
1469
+ /** The effect once it has its turn: the fault, the perform under its deadline, the record. */
1470
+ async performEffect(point, perform, summarize, options, inv, enclosing, host) {
1471
+ const dead = () => {
1472
+ enclosing?.crash();
1473
+ return hang();
1474
+ };
929
1475
  const fault = this.open(point, inv);
930
1476
  if (fault === "crash_before" || fault === "cut_off") {
931
1477
  this.record(point, "fault", {
@@ -933,7 +1479,7 @@ var Run = class {
933
1479
  fault
934
1480
  });
935
1481
  inv.crash();
936
- return hang();
1482
+ return dead();
937
1483
  }
938
1484
  if (fault === "error") {
939
1485
  this.record(point, "fault", {
@@ -942,21 +1488,67 @@ var Run = class {
942
1488
  });
943
1489
  throw new InjectedEffectError(point, fault);
944
1490
  }
945
- let value;
1491
+ let settled;
1492
+ const deadline = realDeadline(this.options.bounds.budgetMs);
1493
+ const frame = new Frame(point.invocation, point.hostsEffects === true, options);
1494
+ frame.parent = host;
1495
+ const hosted = point.hostsEffects ? this.hostingFrames(point.invocation) : void 0;
946
1496
  this.inFlight++;
1497
+ this.frames.push(frame);
1498
+ hosted?.push(frame);
1499
+ if (hosted) this.hostingNow++;
947
1500
  try {
948
- value = await (this.patched ? this.patched.libraryIo(perform) : perform());
1501
+ const inside = () => effectScope ? effectScope.run(frame, perform) : perform();
1502
+ const io = this.patched ? this.patched.libraryIo(inside) : inside();
1503
+ settled = await Promise.race([
1504
+ io.then((value) => ({
1505
+ ok: true,
1506
+ value
1507
+ }), (error) => ({
1508
+ ok: false,
1509
+ error
1510
+ })),
1511
+ deadline.expired,
1512
+ frame.crashed
1513
+ ]);
949
1514
  } catch (err) {
1515
+ settled = {
1516
+ ok: false,
1517
+ error: err
1518
+ };
1519
+ } finally {
1520
+ deadline.cancel();
1521
+ if (hosted) {
1522
+ hosted.splice(hosted.lastIndexOf(frame), 1);
1523
+ this.hostingNow--;
1524
+ }
1525
+ this.frames.splice(this.frames.lastIndexOf(frame), 1);
1526
+ if (!frame.isWaiting()) this.inFlight--;
1527
+ else if (frame.parent) {
1528
+ const parent = frame.parent;
1529
+ this.adjust(parent, () => parent.waitingChildren--);
1530
+ }
1531
+ frame.active = false;
1532
+ frame.parent = void 0;
1533
+ this.patched?.clock.advance(1);
1534
+ if (this.concurrent) this.progressed();
1535
+ }
1536
+ if (settled === "expired") {
1537
+ this.unsupported(`${point.target} ${point.op} did not complete within ${this.options.bounds.budgetMs} ms of real time`);
1538
+ inv.crash();
1539
+ frame.abandon();
1540
+ return hang();
1541
+ }
1542
+ if (settled === "nested_crash") return dead();
1543
+ if (!settled.ok) {
950
1544
  this.record(point, "result", {
951
1545
  args: point.args,
952
1546
  result: null,
953
- error: String(err)
1547
+ error: String(settled.error)
954
1548
  });
955
- throw err;
956
- } finally {
957
- this.inFlight--;
958
- this.patched?.clock.advance(1);
1549
+ throw settled.error;
959
1550
  }
1551
+ const value = settled.value;
960
1552
  this.record(point, "result", {
961
1553
  args: point.args,
962
1554
  result: summarize(value)
@@ -968,7 +1560,7 @@ var Run = class {
968
1560
  fault
969
1561
  });
970
1562
  inv.crash();
971
- return hang();
1563
+ return dead();
972
1564
  }
973
1565
  if (fault === "ambiguous") {
974
1566
  this.record(point, "fault", {
@@ -1035,6 +1627,7 @@ var Run = class {
1035
1627
  }
1036
1628
  settle(promise, invocation) {
1037
1629
  const inv = this.invocation(invocation);
1630
+ if (this.concurrent) return Promise.race([promise, inv.crashed.then(() => hang())]);
1038
1631
  const patched = this.patched;
1039
1632
  if (patched) patched.clock.owner = invocation;
1040
1633
  this.current = invocation;
@@ -1049,6 +1642,147 @@ var Run = class {
1049
1642
  }
1050
1643
  });
1051
1644
  }
1645
+ /** Concurrent runs: start a delivery in its own async context. */
1646
+ startDelivery(deliver) {
1647
+ if (!deliveryScope) throw new Error("concurrent invocations need AsyncLocalStorage");
1648
+ const cell = { id: null };
1649
+ this.runAs(null);
1650
+ return {
1651
+ promise: deliveryScope.run(cell, deliver),
1652
+ invocation: () => cell.id
1653
+ };
1654
+ }
1655
+ /** Concurrent runs: something moved (an invocation parked, a delivery ended, I/O completed). */
1656
+ progressed() {
1657
+ if (this.hostingNow > 0) return;
1658
+ const waiters = this.progressWaiters;
1659
+ this.progressWaiters = [];
1660
+ for (const wake of waiters) wake();
1661
+ }
1662
+ /**
1663
+ * Concurrent runs: wait until the running invocation has parked, finished
1664
+ * or gone idle. Parking, a delivery ending and I/O completing wake the wait
1665
+ * at once; then every pending microtask runs, so continuations the turn set
1666
+ * off have run too. Code waiting on anything else gets one zero timer, the
1667
+ * same allowance the sequential path gives, before it counts as idle.
1668
+ */
1669
+ async quiesce() {
1670
+ for (;;) {
1671
+ await Promise.race([new Promise((wake) => this.progressWaiters.push(wake)), realTick()]);
1672
+ await drainMicrotasks();
1673
+ if (this.inFlight === 0) return;
1674
+ }
1675
+ }
1676
+ /**
1677
+ * Concurrent runs: pick the next turn among the parked invocations and,
1678
+ * when `canStart`, starting the next event. Parked invocations are ordered
1679
+ * by start, then by when they parked, so the pick does not depend on
1680
+ * real-time arrival. Returns what was picked; "turn" has already released it.
1681
+ */
1682
+ takeTurn(canStart) {
1683
+ const order = (inv) => this.startOrder.get(inv.id) ?? 0;
1684
+ this.parked = this.parked.filter((p) => !p.inv.isCrashed()).sort((a, b) => order(a.inv) - order(b.inv) || a.seq - b.seq);
1685
+ const options = this.parked.length + (canStart ? 1 : 0);
1686
+ this.endSegment();
1687
+ this.turnTarget = null;
1688
+ if (options === 0) return "none";
1689
+ let pick = 0;
1690
+ if (options > 1) {
1691
+ pick = this.pickTurn(options, canStart);
1692
+ this.turnPicks.push(pick);
1693
+ } else if (this.options.chooser && this.options.mode === "explore") this.options.chooser.choose("turn", this.turnOptions(canStart));
1694
+ const [chosen] = pick < this.parked.length ? this.parked.splice(pick, 1) : [];
1695
+ if (!chosen) {
1696
+ this.starts++;
1697
+ return "start";
1698
+ }
1699
+ this.turnTarget = chosen.option.target ?? null;
1700
+ this.runAs(chosen.inv.id);
1701
+ const host = chosen.host;
1702
+ if (host) this.adjust(host, () => host.waitingChildren--);
1703
+ chosen.go();
1704
+ return "turn";
1705
+ }
1706
+ /** A parked invocation's next turn as a choice. */
1707
+ turnOption(inv, point) {
1708
+ return {
1709
+ label: `${inv.id}@${inv.parks++}`,
1710
+ invocation: inv.id,
1711
+ target: point.target
1712
+ };
1713
+ }
1714
+ /** The turns on offer, as choices: the parked invocations in order, then starting the next event. */
1715
+ turnOptions(canStart) {
1716
+ return [...this.parked.map((p) => p.option), ...canStart ? [{ label: `start:${this.starts}` }] : []];
1717
+ }
1718
+ /** The turn at a decision with more than one option: recorded, chosen, or drawn from the seed. */
1719
+ pickTurn(options, canStart) {
1720
+ const recorded = this.options.schedule.turns;
1721
+ if (this.options.mode === "replay" && recorded) {
1722
+ const i = recorded[this.turnReplayed++] ?? 0;
1723
+ return i < options ? i : 0;
1724
+ }
1725
+ const chooser = this.options.chooser;
1726
+ if (chooser && this.options.mode === "explore") return chooser.choose("turn", this.turnOptions(canStart));
1727
+ const [i, next] = nextInt(this.turns, options);
1728
+ this.turns = next;
1729
+ return i;
1730
+ }
1731
+ /**
1732
+ * Let virtual time pass until `at`: timers due by then fire first, in due
1733
+ * order, as the invocations that set them, each followed by the work it
1734
+ * sets off. No-op when `at` is not ahead.
1735
+ */
1736
+ async advanceTo(at) {
1737
+ const clock = this.patched?.clock;
1738
+ if (!clock) return;
1739
+ for (let due = clock.nextDue(); due !== void 0 && due <= at; due = clock.nextDue()) {
1740
+ this.runAs(clock.nextOwner() ?? null);
1741
+ clock.fireNext();
1742
+ do
1743
+ await drainMicrotasks();
1744
+ while (this.inFlight > 0);
1745
+ }
1746
+ clock.advance(at - clock.now());
1747
+ }
1748
+ /** When the next virtual timer is due, or undefined when none is pending. */
1749
+ nextTimerDue() {
1750
+ return this.patched?.clock.nextDue();
1751
+ }
1752
+ /** Concurrent runs: fire the next due timer as the invocation that set it. False when none is pending. */
1753
+ fireTimer() {
1754
+ const clock = this.patched?.clock;
1755
+ if (!clock) return false;
1756
+ const owner = clock.nextOwner();
1757
+ if (owner === void 0) return false;
1758
+ this.runAs(owner);
1759
+ return clock.fireNext();
1760
+ }
1761
+ /**
1762
+ * Concurrent runs: nothing can make progress; abandon these invocations so
1763
+ * the run can end. Returns how many were still alive.
1764
+ */
1765
+ abandon(ids) {
1766
+ let abandoned = 0;
1767
+ for (const id of ids) {
1768
+ const inv = this.invocations.get(id);
1769
+ if (!inv || inv.isCrashed()) continue;
1770
+ this.unsupported(`invocation ${id} is waiting on something Eutaxy cannot see (no effect in flight, no timer due)`);
1771
+ inv.crash();
1772
+ abandoned++;
1773
+ }
1774
+ return abandoned;
1775
+ }
1776
+ /** A call of a pure core function, recorded as a decision of the invocation running now (see `observeCore`). */
1777
+ decision(fn, payload) {
1778
+ this.logState = appendEffect(this.logState, {
1779
+ kind: "result",
1780
+ invocation: this.running(),
1781
+ target: decisionTarget(fn),
1782
+ op: "decide",
1783
+ payload
1784
+ });
1785
+ }
1052
1786
  snapshot(invocation, target, payload) {
1053
1787
  this.logState = appendEffect(this.logState, {
1054
1788
  kind: "snapshot",
@@ -1127,25 +1861,95 @@ async function shrink(spec, platform, schedule, violation, trace, options) {
1127
1861
  const engineAssumptions = [
1128
1862
  "schedule points are effect boundaries: proxied bindings, patched timers and fetch; other awaits run in program order",
1129
1863
  "faults: crash_before, crash_after, ambiguous, error at any effect point; redelivery per the platform's queue model",
1130
- "one invocation at a time (maxConcurrentInvocations = 1)",
1131
1864
  "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",
1132
1865
  "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",
1866
+ "an effect whose real I/O takes longer than the scenario's budgetMs is treated as hung: the run is UNSUPPORTED and names the effect",
1133
1867
  "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",
1134
1868
  "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)",
1135
1869
  "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"
1136
1870
  ];
1871
+ /** What a verdict rests on about concurrency, for these bounds. */
1872
+ function concurrencyAssumption(bounds) {
1873
+ if (bounds.maxConcurrentInvocations === 1) return "one invocation at a time (maxConcurrentInvocations = 1)";
1874
+ 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`;
1875
+ }
1876
+ /** The pending event to deliver next: the earliest by `at`, then the first queued. */
1877
+ function nextEvent(pending) {
1878
+ let best = 0;
1879
+ for (let i = 1; i < pending.length; i++) if ((pending[i]?.at ?? 0) < (pending[best]?.at ?? 0)) best = i;
1880
+ return best;
1881
+ }
1882
+ /** What a verdict rests on about how schedules were chosen, when exploration was exhaustive. */
1883
+ function explorationAssumption(options) {
1884
+ if (!options.exhaustive) return [];
1885
+ 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)", ...(typeof options.exhaustive === "object" ? options.exhaustive.reduction ?? true : true) ? ["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)"] : []];
1886
+ }
1887
+ /** Deliver events one at a time, each to completion; time passes until a delayed one is due. */
1888
+ async function deliverInOrder(spec, platform, run) {
1889
+ const pending = [...platform.initialEvents(spec)];
1890
+ while (pending.length > 0) {
1891
+ const [event] = pending.splice(nextEvent(pending), 1);
1892
+ if (event.at !== void 0) await run.advanceTo(event.at);
1893
+ const result = await platform.deliver(event, run, spec);
1894
+ pending.push(...run.takeQueued(), ...result.followUps);
1895
+ }
1896
+ }
1897
+ /**
1898
+ * Deliver events with up to `maxConcurrentInvocations` in flight. Each turn
1899
+ * is a seeded pick: one parked invocation performs its effect and runs to
1900
+ * its next one, or, while a slot is free, the next event starts. When
1901
+ * nothing is parked and no event can start a timer fires, and when nothing
1902
+ * can move the remaining invocations are abandoned.
1903
+ */
1904
+ async function deliverConcurrently(spec, platform, run) {
1905
+ const pending = [...platform.initialEvents(spec)];
1906
+ let active = [];
1907
+ for (;;) {
1908
+ const queuedBefore = pending.length;
1909
+ for (const d of active) {
1910
+ if (!d.outcome) continue;
1911
+ if ("error" in d.outcome) throw d.outcome.error;
1912
+ pending.push(...d.outcome.result.followUps);
1913
+ }
1914
+ active = active.filter((d) => !d.outcome);
1915
+ pending.push(...run.takeQueued());
1916
+ if (pending.length > queuedBefore) run.queuedEvents();
1917
+ if (active.length === 0 && pending.length === 0) return;
1918
+ const next = pending.length > 0 ? nextEvent(pending) : -1;
1919
+ const due = next >= 0 && (pending[next]?.at ?? 0) <= run.now();
1920
+ const canStart = active.length < spec.bounds.maxConcurrentInvocations && due;
1921
+ const turn = run.takeTurn(canStart);
1922
+ if (turn === "start") {
1923
+ const [event] = pending.splice(next, 1);
1924
+ const d = {
1925
+ started: run.startDelivery(() => platform.deliver(event, run, spec)),
1926
+ outcome: null
1927
+ };
1928
+ d.started.promise.then((result) => {
1929
+ d.outcome = { result };
1930
+ run.progressed();
1931
+ }, (error) => {
1932
+ d.outcome = { error };
1933
+ run.progressed();
1934
+ });
1935
+ active.push(d);
1936
+ } else if (turn === "none" && next >= 0 && !due && active.length < spec.bounds.maxConcurrentInvocations && (run.nextTimerDue() ?? Number.POSITIVE_INFINITY) > (pending[next]?.at ?? 0)) await run.advanceTo(pending[next]?.at ?? 0);
1937
+ else if (turn === "none" && !run.fireTimer()) {
1938
+ const stuck = active.flatMap((d) => d.started.invocation() ?? []);
1939
+ if (run.abandon(stuck) === 0) throw new Error(`the ${platform.name} platform's delivery made no progress and cannot be abandoned`);
1940
+ }
1941
+ await run.quiesce();
1942
+ }
1943
+ }
1137
1944
  /** Run the scenario once under the given run's fault decisions and return its log. */
1138
1945
  async function runOnce(spec, platform, run) {
1139
1946
  await platform.reset(spec);
1140
1947
  run.install(spec.externals);
1141
1948
  try {
1142
1949
  try {
1143
- const pending = [...platform.initialEvents(spec)];
1144
- while (pending.length > 0) {
1145
- const event = pending.shift();
1146
- const result = await platform.deliver(event, run, spec);
1147
- pending.push(...result.followUps);
1148
- }
1950
+ if (!run.concurrent) await deliverInOrder(spec, platform, run);
1951
+ else if (platform.concurrent) await deliverConcurrently(spec, platform, run);
1952
+ else throw new Error(`the ${platform.name} platform delivers one event at a time`);
1149
1953
  } finally {
1150
1954
  run.uninstall();
1151
1955
  }
@@ -1174,7 +1978,12 @@ async function explore(spec, platform, options) {
1174
1978
  const now = options.now ?? (() => Date.now());
1175
1979
  const maxRuns = options.maxRuns ?? 100;
1176
1980
  const faultProbability = options.faultProbability ?? .5;
1177
- const assumptions = [...engineAssumptions, ...platform.assumptions];
1981
+ const assumptions = [
1982
+ ...engineAssumptions,
1983
+ concurrencyAssumption(spec.bounds),
1984
+ ...explorationAssumption(options),
1985
+ ...platform.assumptions
1986
+ ];
1178
1987
  const start = now();
1179
1988
  const reached = {
1180
1989
  runs: 0,
@@ -1190,31 +1999,68 @@ async function explore(spec, platform, options) {
1190
1999
  seed: options.seed,
1191
2000
  assumptions
1192
2001
  };
1193
- if (spec.bounds.maxConcurrentInvocations !== 1) return {
2002
+ if (spec.bounds.maxConcurrentInvocations > 1 && !concurrencySupported) return {
1194
2003
  ...base,
1195
2004
  kind: "UNSUPPORTED",
1196
2005
  cause: "unsupported_bounds",
1197
- reason: "maxConcurrentInvocations above 1 is not supported yet",
2006
+ reason: "maxConcurrentInvocations above 1 needs AsyncLocalStorage (Node, or workerd with nodejs_compat or nodejs_als)",
2007
+ reached: done()
2008
+ };
2009
+ if (spec.bounds.maxConcurrentInvocations > 1 && !platform.concurrent) return {
2010
+ ...base,
2011
+ kind: "UNSUPPORTED",
2012
+ cause: "unsupported_bounds",
2013
+ reason: `maxConcurrentInvocations above 1 is not supported on the ${platform.name} platform yet`,
1198
2014
  reached: done()
1199
2015
  };
1200
2016
  const leakCheckRuns = options.leakCheckRuns ?? 2;
1201
2017
  /** The first runs' schedules and digests, replayed in reverse order before BOUNDED. */
1202
2018
  const witnesses = [];
1203
2019
  let master = seedPrng(options.seed);
1204
- while (reached.runs < maxRuns && now() - start < spec.bounds.budgetMs) {
2020
+ let reduction = typeof options.exhaustive === "object" ? options.exhaustive.reduction ?? true : true;
2021
+ let enumerator = options.exhaustive ? new Enumerator({ reduction }) : null;
2022
+ let schedules = 0;
2023
+ let more = true;
2024
+ let restart = false;
2025
+ const exhaustiveReached = () => enumerator ? { exhaustive: {
2026
+ complete: !more,
2027
+ schedules,
2028
+ reduction
2029
+ } } : {};
2030
+ const doneNow = () => ({
2031
+ ...done(),
2032
+ ...exhaustiveReached()
2033
+ });
2034
+ while (more && reached.runs < maxRuns && now() - start < spec.bounds.budgetMs) {
1205
2035
  const [runSeed, next] = nextU32(master);
1206
2036
  master = next;
1207
2037
  const run = new Run({
1208
2038
  mode: "explore",
1209
2039
  schedule: {
1210
- seed: runSeed,
2040
+ seed: enumerator ? 0 : runSeed,
1211
2041
  faults: []
1212
2042
  },
1213
2043
  bounds: spec.bounds,
1214
- faultProbability
2044
+ faultProbability,
2045
+ ...enumerator ? { chooser: enumerator.next() } : {}
1215
2046
  });
1216
2047
  const log = await runOnce(spec, platform, run);
1217
2048
  reached.runs++;
2049
+ if (enumerator) {
2050
+ if (enumerator.mismatch) return {
2051
+ ...base,
2052
+ kind: "UNSUPPORTED",
2053
+ cause: "not_replayable",
2054
+ reason: `exhaustive exploration needs deterministic runs: ${enumerator.mismatch}`,
2055
+ reached: doneNow()
2056
+ };
2057
+ restart = reduction && run.turnsMayNotCommute;
2058
+ if (!restart) {
2059
+ more = enumerator.advance();
2060
+ if (enumerator.blocked) continue;
2061
+ schedules++;
2062
+ }
2063
+ }
1218
2064
  reached.effectPoints += run.effectPoints;
1219
2065
  reached.faultsInjected += run.faultsInjected;
1220
2066
  if (witnesses.length < leakCheckRuns) witnesses.push({
@@ -1226,7 +2072,7 @@ async function explore(spec, platform, options) {
1226
2072
  kind: "UNSUPPORTED",
1227
2073
  cause: "unsupported_api",
1228
2074
  reason: run.unsupportedReasons.join("; "),
1229
- reached: done()
2075
+ reached: doneNow()
1230
2076
  };
1231
2077
  const violation = checkInvariants(log, spec.invariants)[0];
1232
2078
  if (violation) {
@@ -1239,7 +2085,7 @@ async function explore(spec, platform, options) {
1239
2085
  kind: "UNSUPPORTED",
1240
2086
  cause: "not_replayable",
1241
2087
  reason: `the violating run of seed ${schedule.seed} did not reproduce on replay`,
1242
- reached: done()
2088
+ reached: doneNow()
1243
2089
  };
1244
2090
  const shrunk = await shrink(spec, platform, schedule, violation, replayed, {
1245
2091
  maxRuns: options.maxShrinkRuns ?? 200,
@@ -1259,9 +2105,14 @@ async function explore(spec, platform, options) {
1259
2105
  eventsRemoved: shrunk.eventsRemoved,
1260
2106
  runs: shrunk.runs
1261
2107
  },
1262
- reached: done()
2108
+ reached: doneNow()
1263
2109
  };
1264
2110
  }
2111
+ if (restart) {
2112
+ reduction = false;
2113
+ enumerator = new Enumerator({ reduction });
2114
+ schedules = 0;
2115
+ }
1265
2116
  }
1266
2117
  for (const witness of [...witnesses].reverse()) {
1267
2118
  const again = await replayRun(spec, platform, witness.schedule);
@@ -1271,16 +2122,116 @@ async function explore(spec, platform, options) {
1271
2122
  kind: "UNSUPPORTED",
1272
2123
  cause: "module_state_leak",
1273
2124
  reason: `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)`,
1274
- reached: done()
2125
+ reached: doneNow()
1275
2126
  };
1276
2127
  }
1277
2128
  return {
1278
2129
  ...base,
1279
2130
  kind: "BOUNDED",
1280
2131
  bounds: spec.bounds,
1281
- reached: done()
2132
+ reached: doneNow()
2133
+ };
2134
+ }
2135
+ // packages/engine/src/observe.ts
2136
+ /** A JSON summary of a value for the log: exact for JSON, a readable string otherwise. */
2137
+ function summarize(value, depth = 0, seen = /* @__PURE__ */ new Set()) {
2138
+ if (value === null || value === void 0) return null;
2139
+ switch (typeof value) {
2140
+ case "string":
2141
+ case "boolean": return value;
2142
+ case "number": return Number.isFinite(value) && !Object.is(value, -0) ? value : String(Object.is(value, -0) ? "-0" : value);
2143
+ case "bigint": return `${value}n`;
2144
+ case "function": return "[function]";
2145
+ case "symbol": return String(value);
2146
+ }
2147
+ if (depth > 8 || seen.has(value)) return "[…]";
2148
+ seen.add(value);
2149
+ try {
2150
+ if (Array.isArray(value)) return value.map((v) => summarize(v, depth + 1, seen));
2151
+ const proto = Object.getPrototypeOf(value);
2152
+ if (proto !== Object.prototype && proto !== null) return String(value);
2153
+ const out = {};
2154
+ for (const [k, v] of Object.entries(value)) Object.defineProperty(out, k, {
2155
+ value: summarize(v, depth + 1, seen),
2156
+ enumerable: true,
2157
+ writable: true,
2158
+ configurable: true
2159
+ });
2160
+ return out;
2161
+ } finally {
2162
+ seen.delete(value);
2163
+ }
2164
+ }
2165
+ function observeCore(namespace, functions) {
2166
+ const calls = [];
2167
+ const unobservable = Object.create(null);
2168
+ const undo = [];
2169
+ const target = namespace;
2170
+ for (const name of functions) {
2171
+ const original = target[name];
2172
+ if (typeof original !== "function") {
2173
+ unobservable[name] = `the module exports no function ${name}`;
2174
+ continue;
2175
+ }
2176
+ const wrapped = function(...args) {
2177
+ const run = installedRun();
2178
+ if (!run) return Reflect.apply(original, this, args);
2179
+ const record = (threw, payload) => {
2180
+ calls.push({
2181
+ function: name,
2182
+ args: [...args],
2183
+ threw
2184
+ });
2185
+ run.decision(name, {
2186
+ args: summarize(args),
2187
+ ...payload
2188
+ });
2189
+ };
2190
+ let value;
2191
+ try {
2192
+ value = Reflect.apply(original, this, args);
2193
+ } catch (err) {
2194
+ record(true, { error: String(err) });
2195
+ throw err;
2196
+ }
2197
+ if (typeof value?.then === "function") {
2198
+ run.unsupported(`core function ${name} returned a promise; observed core functions must be synchronous and pure`);
2199
+ return value;
2200
+ }
2201
+ record(false, { result: summarize(value) });
2202
+ return value;
2203
+ };
2204
+ const descriptor = Object.getOwnPropertyDescriptor(target, name);
2205
+ try {
2206
+ Object.defineProperty(target, name, {
2207
+ configurable: true,
2208
+ enumerable: descriptor?.enumerable ?? true,
2209
+ get: () => wrapped
2210
+ });
2211
+ } catch (err) {
2212
+ unobservable[name] = `its module's namespace cannot be changed here (${String(err)})`;
2213
+ continue;
2214
+ }
2215
+ if (target[name] !== wrapped) {
2216
+ unobservable[name] = "its module's namespace did not take the observer";
2217
+ continue;
2218
+ }
2219
+ undo.push(() => {
2220
+ if (descriptor) Object.defineProperty(target, name, descriptor);
2221
+ else delete target[name];
2222
+ });
2223
+ }
2224
+ let restored = false;
2225
+ return {
2226
+ calls,
2227
+ unobservable,
2228
+ restore() {
2229
+ if (restored) return;
2230
+ restored = true;
2231
+ for (const u of undo.reverse()) u();
2232
+ }
1282
2233
  };
1283
2234
  }
1284
- export { Run as a, realTick as c, validateScenario as d, checkInvariant as f, CrashSignal as i, settleOn as l, getPath as m, replay as n, installScriptedFetch as o, checkInvariants as p, restrictSpec as r, patchGlobals as s, explore as t, defaultBounds as u };
2235
+ export { getPath as _, CrashSignal as a, installScriptedFetch as c, realTick as d, settleOn as f, checkInvariants as g, checkInvariant as h, restrictSpec as i, withoutNetwork as l, validateScenario as m, explore as n, InjectedEffectError as o, defaultBounds as p, replay as r, Run as s, observeCore as t, patchGlobals as u };
1285
2236
 
1286
- //# sourceMappingURL=src-Brt0dfNL.mjs.map
2237
+ //# sourceMappingURL=src-C19_yfMM.mjs.map