eutaxy 0.5.0 → 0.5.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 (44) hide show
  1. package/README.md +1 -1
  2. package/dist/aws.d.mts +7 -5
  3. package/dist/aws.d.mts.map +1 -1
  4. package/dist/aws.mjs +41 -135
  5. package/dist/aws.mjs.map +1 -1
  6. package/dist/bin.mjs +2 -2
  7. package/dist/checked-CGpA2-F0.d.mts +285 -0
  8. package/dist/checked-CGpA2-F0.d.mts.map +1 -0
  9. package/dist/cli-IJrKkeYS.mjs +2 -0
  10. package/dist/cli.d.mts.map +1 -1
  11. package/dist/cli.mjs +2 -2
  12. package/dist/cloudflare.d.mts +158 -54
  13. package/dist/cloudflare.d.mts.map +1 -1
  14. package/dist/cloudflare.mjs +3 -1815
  15. package/dist/delivery-invariants-BraYqcYN.d.mts +5 -0
  16. package/dist/delivery-invariants-BraYqcYN.d.mts.map +1 -0
  17. package/dist/delivery-invariants-Cuxdna28.mjs +39 -0
  18. package/dist/delivery-invariants-Cuxdna28.mjs.map +1 -0
  19. package/dist/index.d.mts +22 -189
  20. package/dist/index.d.mts.map +1 -1
  21. package/dist/index.mjs +17 -197
  22. package/dist/index.mjs.map +1 -1
  23. package/dist/{platform-eVgCMbX0.d.mts → platform-DfMwknw1.d.mts} +94 -73
  24. package/dist/platform-DfMwknw1.d.mts.map +1 -0
  25. package/dist/{src-C19_yfMM.mjs → src-Bqc9Eyb1.mjs} +961 -543
  26. package/dist/src-Bqc9Eyb1.mjs.map +1 -0
  27. package/dist/src-DKb-fkdb.mjs +3399 -0
  28. package/dist/src-DKb-fkdb.mjs.map +1 -0
  29. package/dist/{src-CgfGiH25.mjs → src-Dxl9ZlKn.mjs} +223 -17
  30. package/dist/src-Dxl9ZlKn.mjs.map +1 -0
  31. package/package.json +1 -1
  32. package/dist/cli-NqY61bpo.mjs +0 -2
  33. package/dist/cloudflare.mjs.map +0 -1
  34. package/dist/explore-BHYvAZKN.d.mts +0 -84
  35. package/dist/explore-BHYvAZKN.d.mts.map +0 -1
  36. package/dist/platform-eVgCMbX0.d.mts.map +0 -1
  37. package/dist/src-BD3jkjgG.mjs +0 -477
  38. package/dist/src-BD3jkjgG.mjs.map +0 -1
  39. package/dist/src-C19_yfMM.mjs.map +0 -1
  40. package/dist/src-CgfGiH25.mjs.map +0 -1
  41. package/dist/src-s6uYyC0B.mjs +0 -89
  42. package/dist/src-s6uYyC0B.mjs.map +0 -1
  43. package/dist/verdict-evEM5Gxx.mjs +0 -12
  44. package/dist/verdict-evEM5Gxx.mjs.map +0 -1
@@ -1,4 +1,139 @@
1
- import { i as canonicalJson, n as digestLog, r as emptyLog, t as appendEffect } from "./src-s6uYyC0B.mjs";
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
+ }
31
+ }
32
+ // packages/core/src/selectors.ts
33
+ /** Picking effect records out of the log, and reading paths out of their payloads. */
34
+ /** Read a dot path such as "args.params.0" out of JSON data; undefined when absent. */
35
+ function getPath(value, path) {
36
+ let cur = value;
37
+ if (path === "") return cur;
38
+ for (const part of path.split(".")) {
39
+ if (cur === null || typeof cur !== "object") return void 0;
40
+ if (Array.isArray(cur)) {
41
+ const i = Number(part);
42
+ if (!Number.isInteger(i) || i < 0) return void 0;
43
+ cur = cur[i];
44
+ } else cur = cur[part];
45
+ if (cur === void 0) return void 0;
46
+ }
47
+ return cur;
48
+ }
49
+ function jsonEqual(a, b) {
50
+ if (a === void 0) return false;
51
+ if (a === b) return true;
52
+ if (a === null || b === null || typeof a !== "object" || typeof b !== "object") return false;
53
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
54
+ if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((x, i) => jsonEqual(x, b[i]));
55
+ const ao = a;
56
+ const bo = b;
57
+ const ak = Object.keys(ao).sort();
58
+ const bk = Object.keys(bo).sort();
59
+ return ak.length === bk.length && ak.every((k, i) => k === bk[i] && jsonEqual(ao[k], bo[k]));
60
+ }
61
+ function matches(record, sel) {
62
+ if (record.target !== sel.target) return false;
63
+ if (sel.op !== void 0 && record.op !== sel.op) return false;
64
+ if (sel.kind !== void 0 && record.kind !== sel.kind) return false;
65
+ if (sel.where) {
66
+ for (const [path, want] of Object.entries(sel.where)) if (!jsonEqual(getPath(record.payload, path), want)) return false;
67
+ }
68
+ if (sel.atLeast) for (const [path, min] of Object.entries(sel.atLeast)) {
69
+ const v = getPath(record.payload, path);
70
+ if (typeof v !== "number" || v < min) return false;
71
+ }
72
+ return true;
73
+ }
74
+ function selectEffects(log, sel) {
75
+ return log.entries.filter((e) => matches(e, sel));
76
+ }
77
+ /** Canonical form of a key, so equal JSON values compare equal whatever their key order. */
78
+ function keyOf(record, path) {
79
+ const v = getPath(record.payload, path);
80
+ return v === void 0 ? void 0 : canonicalJson(v);
81
+ }
82
+ // packages/core/src/utf8.ts
83
+ /**
84
+ * UTF-8 encode a string, with no runtime dependency on TextEncoder. An unpaired
85
+ * surrogate becomes U+FFFD, exactly as TextEncoder does, so the output is
86
+ * always valid UTF-8.
87
+ */
88
+ function utf8Encode(s) {
89
+ const out = [];
90
+ for (const ch of s) {
91
+ let cp = ch.codePointAt(0) ?? 0;
92
+ if (cp >= 55296 && cp <= 57343) cp = 65533;
93
+ if (cp < 128) out.push(cp);
94
+ else if (cp < 2048) out.push(192 | cp >> 6, 128 | cp & 63);
95
+ else if (cp < 65536) out.push(224 | cp >> 12, 128 | cp >> 6 & 63, 128 | cp & 63);
96
+ else out.push(240 | cp >> 18, 128 | cp >> 12 & 63, 128 | cp >> 6 & 63, 128 | cp & 63);
97
+ }
98
+ return Uint8Array.from(out);
99
+ }
100
+ // packages/core/src/effect-log.ts
101
+ /**
102
+ * The effect log: the complete, ordered record of what a simulated run did at
103
+ * its effect boundaries. It is plain data, appended immutably, and has one
104
+ * canonical serialisation, so two runs are identical exactly when their
105
+ * serialised logs are byte-identical.
106
+ */
107
+ const emptyLog = Object.freeze({ entries: Object.freeze([]) });
108
+ /** Append one effect, assigning its sequence number. The input log is unchanged. */
109
+ function appendEffect(log, effect) {
110
+ const record = {
111
+ ...effect,
112
+ seq: log.entries.length
113
+ };
114
+ return { entries: [...log.entries, record] };
115
+ }
116
+ /** One canonical JSON object per line, in sequence order. */
117
+ function serializeLog(log) {
118
+ return log.entries.map((e) => canonicalJson({
119
+ seq: e.seq,
120
+ kind: e.kind,
121
+ invocation: e.invocation,
122
+ target: e.target,
123
+ op: e.op,
124
+ payload: e.payload
125
+ })).join("\n");
126
+ }
127
+ /** A 64-bit FNV-1a digest of the serialised log, as 16 hex digits. Not cryptographic. */
128
+ function digestLog(log) {
129
+ const bytes = utf8Encode(serializeLog(log));
130
+ let h = 14695981039346656037n;
131
+ for (const b of bytes) {
132
+ h ^= BigInt(b);
133
+ h = h * 1099511628211n & 18446744073709551615n;
134
+ }
135
+ return h.toString(16).padStart(16, "0");
136
+ }
2
137
  // packages/core/src/prng.ts
3
138
  function rotl(x, k) {
4
139
  return (x << k | x >>> 32 - k) >>> 0;
@@ -91,32 +226,96 @@ function decideFault(state, allowed, faultsSoFar, policy) {
91
226
  const [i, s2] = nextInt(s1, allowed.length);
92
227
  return [allowed[i] ?? null, s2];
93
228
  }
94
- // packages/core/src/invariants.ts
95
229
  /**
96
- * Invariants are plain data describing a property of the effect log; checkers
97
- * are pure functions from (log, invariant) to a violation or null. The
98
- * library starts with what the first planted bug needs and grows from there.
230
+ * Where one seeded run injects its faults: with probability `probability`,
231
+ * one up to `maxFaults` distinct positions, in increasing order; otherwise
232
+ * none. Positions count the run's eligible points (those that may take a
233
+ * fault) from 0. The first is uniform over the `baseline` points a run
234
+ * without faults has, which every run reaches before its first fault; the
235
+ * others come after it, uniform up to `longest`, the most any run has had
236
+ * (earlier faults, a redelivery say, can make a run longer). Pure.
99
237
  */
100
- /** Re-derive `expected` for per-message invariants from the bodies that remain. */
101
- function recomputePerMessageExpected(invariants, bodies) {
102
- return invariants.map((inv) => {
103
- if (inv.kind !== "atLeastOnce" || !inv.perMessage) return inv;
104
- const bodyKey = inv.perMessage.bodyKey;
105
- const expected = [];
106
- for (const b of bodies) {
107
- const v = getPath(b, bodyKey);
108
- if (v !== void 0) expected.push(v);
109
- }
110
- return {
111
- ...inv,
112
- expected
113
- };
114
- });
238
+ function planFaults(state, baseline, longest, maxFaults, probability) {
239
+ if (baseline <= 0 || maxFaults <= 0) return [[], state];
240
+ const [p, s1] = nextFloat(state);
241
+ if (p >= probability) return [[], s1];
242
+ let [k, s] = nextInt(s1, maxFaults);
243
+ const more = k;
244
+ let first;
245
+ [first, s] = nextInt(s, baseline);
246
+ const room = Math.max(longest, baseline) - first - 1;
247
+ const chosen = /* @__PURE__ */ new Set([first]);
248
+ while (chosen.size < 1 + Math.min(more, room)) {
249
+ [k, s] = nextInt(s, room);
250
+ chosen.add(first + 1 + k);
251
+ }
252
+ return [[...chosen].sort((a, b) => a - b), s];
115
253
  }
254
+ // packages/core/src/refines.ts
255
+ /** `refines`: the shell carries out the decisions its pure core made, and not on a stale read. */
116
256
  /** The log target decisions of a core function are recorded under. */
117
257
  function decisionTarget(fn) {
118
258
  return `Core:${fn}`;
119
259
  }
260
+ function checkRefines(log, inv) {
261
+ const target = decisionTarget(inv.decision);
262
+ const before = (seq, invocation, pick) => {
263
+ let found;
264
+ for (const e of log.entries) {
265
+ if (e.seq >= seq) break;
266
+ if (e.invocation === invocation && pick(e)) found = e;
267
+ }
268
+ return found;
269
+ };
270
+ for (const effect of selectEffects(log, inv.effect)) {
271
+ const what = `${effect.target} ${effect.op} (seq ${effect.seq}) in ${effect.invocation}`;
272
+ const decision = before(effect.seq, effect.invocation, (e) => e.target === target && e.kind === "result" && getPath(e.payload, "error") === void 0);
273
+ if (!decision) return {
274
+ invariant: inv.name,
275
+ message: `${what} carries out no decision: ${inv.decision} was not called before it in that invocation`,
276
+ keys: ["no_decision"],
277
+ evidence: [effect.seq]
278
+ };
279
+ for (const pair of inv.follows ?? []) {
280
+ const got = getPath(effect.payload, pair.effect);
281
+ const want = getPath(decision.payload, pair.decision);
282
+ if (want === void 0 ? got !== void 0 : !jsonEqual(got, want)) {
283
+ const show = (v) => v === void 0 ? "nothing" : canonicalJson(v);
284
+ return {
285
+ invariant: inv.name,
286
+ 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)}`,
287
+ keys: ["not_followed", pair.effect],
288
+ evidence: [decision.seq, effect.seq]
289
+ };
290
+ }
291
+ }
292
+ const state = inv.state;
293
+ if (!state) continue;
294
+ const read = before(decision.seq, effect.invocation, (e) => matches(e, state.read));
295
+ if (!read) return {
296
+ invariant: inv.name,
297
+ 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`,
298
+ keys: ["no_read"],
299
+ evidence: [decision.seq, effect.seq]
300
+ };
301
+ const key = state.key === void 0 ? void 0 : keyOf(read, state.key);
302
+ 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));
303
+ if (write) return {
304
+ invariant: inv.name,
305
+ 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`,
306
+ keys: ["stale_read", ...key === void 0 ? [] : [key]],
307
+ evidence: [
308
+ read.seq,
309
+ decision.seq,
310
+ write.seq,
311
+ effect.seq
312
+ ]
313
+ };
314
+ }
315
+ return null;
316
+ }
317
+ // packages/core/src/state.ts
318
+ /** State invariants: conditions on the rows of the end-of-run snapshots recorded in the log. */
120
319
  /** The tables in the last snapshot recorded for a target, or undefined when none was. */
121
320
  function lastSnapshot(log, target) {
122
321
  for (let i = log.entries.length - 1; i >= 0; i--) {
@@ -154,98 +353,6 @@ function snapshotSeq(log, target) {
154
353
  for (const e of log.entries) if (e.kind === "snapshot" && e.target === target) last = e.seq;
155
354
  return last === void 0 ? [] : [last];
156
355
  }
157
- /** True when two violations are of the same invariant for the same keys, whatever the traces. */
158
- function sameViolation(a, b) {
159
- return a.invariant === b.invariant && a.keys.length === b.keys.length && a.keys.every((k, i) => k === b.keys[i]);
160
- }
161
- /** Read a dot path such as "args.params.0" out of JSON data; undefined when absent. */
162
- function getPath(value, path) {
163
- let cur = value;
164
- if (path === "") return cur;
165
- for (const part of path.split(".")) {
166
- if (cur === null || typeof cur !== "object") return void 0;
167
- if (Array.isArray(cur)) {
168
- const i = Number(part);
169
- if (!Number.isInteger(i) || i < 0) return void 0;
170
- cur = cur[i];
171
- } else cur = cur[part];
172
- if (cur === void 0) return void 0;
173
- }
174
- return cur;
175
- }
176
- function jsonEqual(a, b) {
177
- if (a === void 0) return false;
178
- if (a === b) return true;
179
- if (a === null || b === null || typeof a !== "object" || typeof b !== "object") return false;
180
- if (Array.isArray(a) !== Array.isArray(b)) return false;
181
- if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((x, i) => jsonEqual(x, b[i]));
182
- const ao = a;
183
- const bo = b;
184
- const ak = Object.keys(ao).sort();
185
- const bk = Object.keys(bo).sort();
186
- return ak.length === bk.length && ak.every((k, i) => k === bk[i] && jsonEqual(ao[k], bo[k]));
187
- }
188
- function matches(record, sel) {
189
- if (record.target !== sel.target) return false;
190
- if (sel.op !== void 0 && record.op !== sel.op) return false;
191
- if (sel.kind !== void 0 && record.kind !== sel.kind) return false;
192
- if (sel.where) {
193
- for (const [path, want] of Object.entries(sel.where)) if (!jsonEqual(getPath(record.payload, path), want)) return false;
194
- }
195
- if (sel.atLeast) for (const [path, min] of Object.entries(sel.atLeast)) {
196
- const v = getPath(record.payload, path);
197
- if (typeof v !== "number" || v < min) return false;
198
- }
199
- return true;
200
- }
201
- function selectEffects(log, sel) {
202
- return log.entries.filter((e) => matches(e, sel));
203
- }
204
- /** Canonical form of a key, so equal JSON values compare equal whatever their key order. */
205
- function keyOf(record, path) {
206
- const v = getPath(record.payload, path);
207
- return v === void 0 ? void 0 : canonicalJson(v);
208
- }
209
- function checkInvariant(log, inv) {
210
- switch (inv.kind) {
211
- case "refines": return checkRefines(log, inv);
212
- case "everyRow": return checkEveryRow(log, inv);
213
- case "implies": return checkImplies(log, inv);
214
- case "unique": return checkUnique(log, inv);
215
- case "atMostOncePerKey": {
216
- const seen = /* @__PURE__ */ new Map();
217
- for (const e of selectEffects(log, inv.effect)) {
218
- const k = keyOf(e, inv.key);
219
- if (k === void 0) continue;
220
- const first = seen.get(k);
221
- if (first !== void 0) return {
222
- invariant: inv.name,
223
- message: `${inv.effect.target} ${inv.effect.op ?? "*"} happened twice for key ${k} (seq ${first} and ${e.seq})`,
224
- keys: [k],
225
- evidence: [first, e.seq]
226
- };
227
- seen.set(k, e.seq);
228
- }
229
- return null;
230
- }
231
- case "atLeastOnce": {
232
- const present = /* @__PURE__ */ new Set();
233
- const selected = selectEffects(log, inv.effect);
234
- for (const e of selected) {
235
- const k = keyOf(e, inv.key);
236
- if (k !== void 0) present.add(k);
237
- }
238
- const missing = inv.expected.map((v) => canonicalJson(v)).filter((k) => !present.has(k));
239
- if (missing.length === 0) return null;
240
- return {
241
- invariant: inv.name,
242
- message: `${inv.effect.target} ${inv.effect.op ?? "*"} never happened for key(s) ${missing.join(", ")}`,
243
- keys: missing,
244
- evidence: selected.map((e) => e.seq)
245
- };
246
- }
247
- }
248
- }
249
356
  function checkEveryRow(log, inv) {
250
357
  const rows = queryRows(log, inv.query);
251
358
  if (rows === void 0) return {
@@ -319,62 +426,102 @@ function checkImplies(log, inv) {
319
426
  evidence
320
427
  };
321
428
  }
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;
429
+ function checkReferences(log, inv) {
430
+ const rows = queryRows(log, inv.query);
431
+ const targets = queryRows(log, inv.in);
432
+ for (const [q, r] of [[inv.query, rows], [inv.in, targets]]) if (r === void 0) return {
433
+ invariant: inv.name,
434
+ message: `no snapshot of ${q.target} was recorded`,
435
+ keys: [],
436
+ evidence: []
331
437
  };
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]
438
+ const pointedAt = /* @__PURE__ */ new Set();
439
+ for (const t of targets ?? []) {
440
+ const v = t[inv.column];
441
+ if (v !== void 0 && v !== null) pointedAt.add(canonicalJson(v));
442
+ }
443
+ const orphans = /* @__PURE__ */ new Set();
444
+ for (const r of rows ?? []) {
445
+ const v = getPath(r, inv.path);
446
+ if (v === void 0 || v === null) continue;
447
+ const k = canonicalJson(v);
448
+ if (!pointedAt.has(k)) orphans.add(k);
449
+ }
450
+ if (orphans.size === 0) return null;
451
+ const missing = [...orphans];
452
+ return {
453
+ invariant: inv.name,
454
+ message: `${missing.length} row(s) of ${inv.query.table} in ${inv.query.target} have no row of ${inv.in.table} in ${inv.in.target} whose ${inv.column} names them: ${missing.slice(0, 3).join(", ")}${missing.length > 3 ? ", …" : ""}`,
455
+ keys: missing,
456
+ evidence: [...snapshotSeq(log, inv.query.target), ...snapshotSeq(log, inv.in.target)]
457
+ };
458
+ }
459
+ // packages/core/src/invariants.ts
460
+ /**
461
+ * Invariants are plain data describing a property of the effect log; checkers
462
+ * are pure functions from (log, invariant) to a violation or null. The
463
+ * library starts with what the first planted bug needs and grows from there.
464
+ */
465
+ /** Re-derive `expected` for per-message invariants from the bodies that remain. */
466
+ function recomputePerMessageExpected(invariants, bodies) {
467
+ return invariants.map((inv) => {
468
+ if (inv.kind !== "atLeastOnce" || !inv.perMessage) return inv;
469
+ const bodyKey = inv.perMessage.bodyKey;
470
+ const expected = [];
471
+ for (const b of bodies) {
472
+ const v = getPath(b, bodyKey);
473
+ if (v !== void 0) expected.push(v);
474
+ }
475
+ return {
476
+ ...inv,
477
+ expected
340
478
  };
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 {
479
+ });
480
+ }
481
+ /** True when two violations are of the same invariant for the same keys, whatever the traces. */
482
+ function sameViolation(a, b) {
483
+ return a.invariant === b.invariant && a.keys.length === b.keys.length && a.keys.every((k, i) => k === b.keys[i]);
484
+ }
485
+ function checkInvariant(log, inv) {
486
+ switch (inv.kind) {
487
+ case "refines": return checkRefines(log, inv);
488
+ case "everyRow": return checkEveryRow(log, inv);
489
+ case "implies": return checkImplies(log, inv);
490
+ case "unique": return checkUnique(log, inv);
491
+ case "references": return checkReferences(log, inv);
492
+ case "atMostOncePerKey": {
493
+ const seen = /* @__PURE__ */ new Map();
494
+ for (const e of selectEffects(log, inv.effect)) {
495
+ const k = keyOf(e, inv.key);
496
+ if (k === void 0) continue;
497
+ const first = seen.get(k);
498
+ if (first !== void 0) return {
347
499
  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]
500
+ message: `${inv.effect.target} ${inv.effect.op ?? "*"} happened twice for key ${k} (seq ${first} and ${e.seq})`,
501
+ keys: [k],
502
+ evidence: [first, e.seq]
351
503
  };
504
+ seen.set(k, e.seq);
352
505
  }
506
+ return null;
507
+ }
508
+ case "atLeastOnce": {
509
+ const present = /* @__PURE__ */ new Set();
510
+ const selected = selectEffects(log, inv.effect);
511
+ for (const e of selected) {
512
+ const k = keyOf(e, inv.key);
513
+ if (k !== void 0) present.add(k);
514
+ }
515
+ const missing = inv.expected.map((v) => canonicalJson(v)).filter((k) => !present.has(k));
516
+ if (missing.length === 0) return null;
517
+ return {
518
+ invariant: inv.name,
519
+ message: `${inv.effect.target} ${inv.effect.op ?? "*"} never happened for key(s) ${missing.join(", ")}`,
520
+ keys: missing,
521
+ evidence: selected.map((e) => e.seq)
522
+ };
353
523
  }
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
524
  }
377
- return null;
378
525
  }
379
526
  function checkInvariants(log, invariants) {
380
527
  const out = [];
@@ -430,15 +577,11 @@ function validateScenario(spec) {
430
577
  if (!(Number.isInteger(r.status) && r.status >= 100 && r.status <= 599)) errors.push(`external ${JSON.stringify(e.name)} responses[${i}].status must be an HTTP status`);
431
578
  });
432
579
  }
433
- for (const k of [
434
- "maxFaultsPerRun",
435
- "maxRedeliveries",
436
- "maxConcurrentInvocations",
437
- "budgetMs"
438
- ]) if (k === "maxFaultsPerRun" || k === "maxRedeliveries") {
580
+ for (const k of ["maxFaultsPerRun", "maxRedeliveries"]) {
439
581
  const v = spec.bounds[k];
440
582
  if (!(Number.isInteger(v) && v >= 0)) errors.push(`bounds.${k} must be a non-negative integer`);
441
- } else if (!isPositiveInt(spec.bounds[k])) errors.push(`bounds.${k} must be a positive integer`);
583
+ }
584
+ for (const k of ["maxConcurrentInvocations", "budgetMs"]) if (!isPositiveInt(spec.bounds[k])) errors.push(`bounds.${k} must be a positive integer`);
442
585
  return errors;
443
586
  }
444
587
  // packages/core/src/shrink.ts
@@ -465,12 +608,101 @@ function shrinkCandidates(state) {
465
608
  });
466
609
  return out;
467
610
  }
611
+ // packages/core/src/to-json.ts
612
+ const maxDepth = 10;
613
+ /**
614
+ * Exact for JSON data. Otherwise: -0, NaN and the infinities as strings,
615
+ * bigints as their digits, symbols as `Symbol(s)`, functions as `<function>`, Dates
616
+ * as ISO strings, Sets as arrays, Maps as `[key, value]` pairs, Errors as
617
+ * `Name: message`, byte buffers as `<bytes n>`, other objects by their own
618
+ * enumerable keys; a cycle or nesting deeper than ten as `<nested>`, a
619
+ * property that throws when read as `<unreadable>`. `extra` is tried first
620
+ * on every object.
621
+ */
622
+ function toJson(value, extra) {
623
+ return walk(value, extra, 0, /* @__PURE__ */ new Set());
624
+ }
625
+ function walk(value, extra, depth, seen) {
626
+ if (value === null || value === void 0) return null;
627
+ switch (typeof value) {
628
+ case "string":
629
+ case "boolean": return value;
630
+ case "number":
631
+ if (Object.is(value, -0)) return "-0";
632
+ return Number.isFinite(value) ? value : String(value);
633
+ case "bigint": return value.toString();
634
+ case "symbol": return String(value);
635
+ case "function": return "<function>";
636
+ }
637
+ const object = value;
638
+ if (depth > maxDepth || seen.has(object)) return "<nested>";
639
+ const own = extra?.(object);
640
+ if (own !== void 0) return own;
641
+ if (object instanceof Date) return Number.isNaN(object.getTime()) ? "Invalid Date" : object.toISOString();
642
+ if (object instanceof Error) return `${object.name}: ${object.message}`;
643
+ if (object instanceof ArrayBuffer || ArrayBuffer.isView(object)) return `<bytes ${object.byteLength}>`;
644
+ const next = (v) => walk(v, extra, depth + 1, seen);
645
+ seen.add(object);
646
+ try {
647
+ if (Array.isArray(object)) return Array.from(object, next);
648
+ if (object instanceof Set) return [...object].map(next);
649
+ if (object instanceof Map) return [...object].map(([k, v]) => [next(k), next(v)]);
650
+ const out = {};
651
+ for (const key of Object.keys(object)) {
652
+ let v;
653
+ try {
654
+ v = next(object[key]);
655
+ } catch {
656
+ v = "<unreadable>";
657
+ }
658
+ Object.defineProperty(out, key, {
659
+ value: v,
660
+ enumerable: true,
661
+ writable: true,
662
+ configurable: true
663
+ });
664
+ }
665
+ return out;
666
+ } finally {
667
+ seen.delete(object);
668
+ }
669
+ }
468
670
  // packages/engine/src/context.ts
469
671
  /** A new async context slot, or null where the host has no AsyncLocalStorage. */
470
672
  function asyncScope() {
471
673
  const mod = typeof process !== "undefined" ? process?.getBuiltinModule?.("node:async_hooks") : void 0;
472
674
  return mod?.AsyncLocalStorage ? new mod.AsyncLocalStorage() : null;
473
675
  }
676
+ // packages/engine/src/patch.ts
677
+ /** The one way the engine and its platforms replace a property for a while. */
678
+ /**
679
+ * Replace `target[key]` with a value or a getter until the returned
680
+ * function is called, which puts the property back exactly as it was (its
681
+ * descriptor, or no property at all). The replacement is configurable and
682
+ * keeps the original's enumerability. Calling the restore twice is
683
+ * harmless. Throws where the property cannot be redefined.
684
+ */
685
+ function patchProperty(target, key, patch) {
686
+ const saved = Object.getOwnPropertyDescriptor(target, key);
687
+ const enumerable = saved?.enumerable ?? false;
688
+ Object.defineProperty(target, key, "get" in patch ? {
689
+ get: patch.get,
690
+ configurable: true,
691
+ enumerable
692
+ } : {
693
+ value: patch.value,
694
+ writable: true,
695
+ configurable: true,
696
+ enumerable
697
+ });
698
+ let restored = false;
699
+ return () => {
700
+ if (restored) return;
701
+ restored = true;
702
+ if (saved) Object.defineProperty(target, key, saved);
703
+ else Reflect.deleteProperty(target, key);
704
+ };
705
+ }
474
706
  // packages/engine/src/clock.ts
475
707
  /**
476
708
  * The virtual clock and the globals patch. Within a run, Date, Math.random,
@@ -630,19 +862,9 @@ function patchGlobals(seed, options = {}) {
630
862
  reads.count++;
631
863
  };
632
864
  const g = globalThis;
633
- const saved = [];
865
+ const undo = [];
634
866
  const define = (target, key, value) => {
635
- saved.push({
636
- target,
637
- key,
638
- descriptor: Object.getOwnPropertyDescriptor(target, key)
639
- });
640
- Object.defineProperty(target, key, {
641
- value,
642
- configurable: true,
643
- writable: true,
644
- enumerable: false
645
- });
867
+ undo.push(patchProperty(target, key, { value }));
646
868
  };
647
869
  const RealDate = Date;
648
870
  const VirtualDate = function(...args) {
@@ -723,17 +945,18 @@ function patchGlobals(seed, options = {}) {
723
945
  restore() {
724
946
  if (restored) return;
725
947
  restored = true;
726
- for (const { target, key, descriptor } of saved.reverse()) if (descriptor) Object.defineProperty(target, key, descriptor);
727
- else delete target[key];
948
+ for (const u of undo.reverse()) u();
728
949
  }
729
950
  };
730
951
  }
952
+ /** The longest timeout hosts accept: 2^31 - 1 ms. */
953
+ const maxTimeoutMs = 2 ** 31 - 1;
731
954
  /** A real-time deadline: `expired` resolves after `ms` unless cancelled first. */
732
955
  function realDeadline(ms) {
733
956
  let handle;
734
957
  return {
735
958
  expired: new Promise((resolve) => {
736
- handle = realSetTimeout(() => resolve("expired"), ms);
959
+ handle = realSetTimeout(() => resolve("expired"), Math.min(ms, maxTimeoutMs));
737
960
  }),
738
961
  cancel: () => realClearTimeout(handle)
739
962
  };
@@ -862,6 +1085,64 @@ var Enumerator = class {
862
1085
  return false;
863
1086
  }
864
1087
  };
1088
+ /**
1089
+ * The exhaustive half of `explore`: the chooser for each run, what a run
1090
+ * counts for, and starting the enumeration again with the reduction off
1091
+ * once a run shows its turns may not commute.
1092
+ */
1093
+ var ExhaustiveDriver = class {
1094
+ reduction;
1095
+ enumerator;
1096
+ schedules = 0;
1097
+ more = true;
1098
+ restart = false;
1099
+ constructor(reduction) {
1100
+ this.reduction = reduction;
1101
+ this.enumerator = new Enumerator({ reduction });
1102
+ }
1103
+ /** Whether schedules are left to run. */
1104
+ get hasMore() {
1105
+ return this.more;
1106
+ }
1107
+ /** See `Enumerator.mismatch`. */
1108
+ get mismatch() {
1109
+ return this.enumerator.mismatch;
1110
+ }
1111
+ /** The chooser for the next run. */
1112
+ next() {
1113
+ return this.enumerator.next();
1114
+ }
1115
+ /**
1116
+ * Account for the run just made. False when it only repeated an order the
1117
+ * reduction had covered: it is not a new schedule and its checks repeat
1118
+ * others'. A run that shows its turns may not commute counts and is
1119
+ * checked, and `checked` then starts again over every order.
1120
+ */
1121
+ ran(turnsMayNotCommute) {
1122
+ this.restart = this.reduction && turnsMayNotCommute();
1123
+ if (!this.restart) {
1124
+ this.more = this.enumerator.advance();
1125
+ if (this.enumerator.blocked) return false;
1126
+ }
1127
+ this.schedules++;
1128
+ return true;
1129
+ }
1130
+ /** The run's checks passed: if it turned the reduction off, every order from the start. */
1131
+ checked() {
1132
+ if (!this.restart) return;
1133
+ this.reduction = false;
1134
+ this.enumerator = new Enumerator({ reduction: false });
1135
+ this.schedules = 0;
1136
+ }
1137
+ /** What the verdict reports (see `BoundsReached.exhaustive`). */
1138
+ get reached() {
1139
+ return {
1140
+ complete: !this.more,
1141
+ schedules: this.schedules,
1142
+ reduction: this.reduction
1143
+ };
1144
+ }
1145
+ };
865
1146
  // packages/engine/src/fetch.ts
866
1147
  const FAULTS = [
867
1148
  "crash_before",
@@ -986,69 +1267,321 @@ function createScriptedFetch(externals, hooks, unsupported, afterRequest = () =>
986
1267
  afterRequest();
987
1268
  return toResponse(reply);
988
1269
  }
989
- const { reply } = await hooks.hooks.effect({
990
- invocation: hooks.invocation(),
991
- target: `Fetch:${external.name}`,
992
- op: method,
993
- args,
994
- allowed: FAULTS
995
- }, perform, (r) => ({
996
- status: r.reply.status,
997
- effective: r.effective,
998
- dedupeKey
999
- }));
1000
- return toResponse(reply);
1001
- });
1002
- return {
1003
- fetch: scripted,
1004
- dedupe
1005
- };
1006
- }
1007
- /** Replace the global `fetch` for a run; returns the function that restores it. */
1008
- function installScriptedFetch(externals, hooks, unsupported, afterRequest) {
1009
- const g = globalThis;
1010
- const saved = Object.getOwnPropertyDescriptor(globalThis, "fetch");
1011
- const { fetch: scripted } = createScriptedFetch(externals, hooks, unsupported, afterRequest);
1012
- Object.defineProperty(globalThis, "fetch", {
1013
- value: scripted,
1014
- configurable: true,
1015
- writable: true
1016
- });
1017
- let restored = false;
1018
- return () => {
1019
- if (restored) return;
1020
- restored = true;
1021
- if (saved) Object.defineProperty(globalThis, "fetch", saved);
1022
- else delete g.fetch;
1023
- };
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;
1270
+ const { reply } = await hooks.hooks.effect({
1271
+ invocation: hooks.invocation(),
1272
+ target: `Fetch:${external.name}`,
1273
+ op: method,
1274
+ args,
1275
+ allowed: FAULTS
1276
+ }, perform, (r) => ({
1277
+ status: r.reply.status,
1278
+ effective: r.effective,
1279
+ dedupeKey
1280
+ }));
1281
+ return toResponse(reply);
1282
+ });
1283
+ return {
1284
+ fetch: scripted,
1285
+ dedupe
1286
+ };
1287
+ }
1288
+ /** Replace the global `fetch` for a run; returns the function that restores it. */
1289
+ function installScriptedFetch(externals, hooks, unsupported, afterRequest) {
1290
+ const { fetch: scripted } = createScriptedFetch(externals, hooks, unsupported, afterRequest);
1291
+ return patchProperty(globalThis, "fetch", { value: scripted });
1292
+ }
1293
+ /**
1294
+ * Run platform work (a reset, a snapshot) with no network: `fetch` rejects
1295
+ * while it runs. Reports whether anything tried, so code that runs outside
1296
+ * the simulation (an object's constructor during a reset) cannot reach the
1297
+ * network unseen.
1298
+ */
1299
+ async function withoutNetwork(work) {
1300
+ let requested = false;
1301
+ const restore = patchProperty(globalThis, "fetch", { value: async () => {
1302
+ requested = true;
1303
+ throw new TypeError("network access is blocked while Eutaxy resets or snapshots state");
1304
+ } });
1305
+ try {
1306
+ return {
1307
+ value: await work(),
1308
+ requested
1309
+ };
1310
+ } finally {
1311
+ restore();
1312
+ }
1313
+ }
1314
+ // packages/engine/src/frames.ts
1315
+ /**
1316
+ * An effect being performed. An effect made inside it is nested in it; when
1317
+ * a crash is injected there, the nested effect hangs like any crashed
1318
+ * effect and tells this frame, so the enclosing effect ends too. User code
1319
+ * never sees the crash as an error it could catch.
1320
+ */
1321
+ var Frame = class {
1322
+ /** The invocation whose effect this is. */
1323
+ invocation;
1324
+ /** Whether the effect hosts user code that makes effects of its own (`hostsEffects`). */
1325
+ hosts;
1326
+ /** False once the effect's perform has ended. */
1327
+ active = true;
1328
+ /** The effect's `onAbandon`, called where the crash happens (inside the hosted code's context). */
1329
+ onAbandon;
1330
+ /** The effect's `mayPark`: whether an effect its hosted code makes may wait for a turn now. */
1331
+ mayPark;
1332
+ /** The hosting effect this one was made inside of and waited for a turn under, if any. */
1333
+ parent;
1334
+ /** Effects the hosted code made that are parked or running now. */
1335
+ children = 0;
1336
+ /** Of those, the ones parked, or running but only waiting on parked effects of their own. */
1337
+ waitingChildren = 0;
1338
+ abandoned = false;
1339
+ wake = () => {};
1340
+ crashed = new Promise((resolve) => {
1341
+ this.wake = () => resolve("nested_crash");
1342
+ });
1343
+ constructor(invocation, hosts, options) {
1344
+ this.invocation = invocation;
1345
+ this.hosts = hosts;
1346
+ this.onAbandon = options.onAbandon;
1347
+ this.mayPark = options.mayPark ?? (() => true);
1348
+ }
1349
+ /** Its hosted code is only waiting on effects of its own that are parked (however deep). */
1350
+ isWaiting() {
1351
+ return this.children > 0 && this.waitingChildren === this.children;
1352
+ }
1353
+ crash() {
1354
+ this.abandon();
1355
+ this.wake();
1356
+ }
1357
+ abandon() {
1358
+ if (this.abandoned) return;
1359
+ this.abandoned = true;
1360
+ this.onAbandon?.();
1361
+ }
1362
+ };
1363
+ /** The frame of the effect whose `perform` the current code runs inside. */
1364
+ const effectScope = asyncScope();
1365
+ /** One run's frames and in-flight count. */
1366
+ var Frames = class {
1367
+ /** Real I/O pending: effects being performed and tracked work, less hosting effects only waiting. */
1368
+ inFlight = 0;
1369
+ /** Effects being performed, innermost last (the nesting test where there is no async context). */
1370
+ stack = [];
1371
+ /** Per invocation, its effects with `hostsEffects` being performed, innermost last. */
1372
+ hosting = /* @__PURE__ */ new Map();
1373
+ /** Effects with `hostsEffects` being performed now, across invocations. */
1374
+ hostingCount = 0;
1375
+ /** How many effects with `hostsEffects` are being performed now: above 0, hosted code may be running. */
1376
+ get hostingNow() {
1377
+ return this.hostingCount;
1378
+ }
1379
+ /**
1380
+ * The effect an invocation's new effect is made inside of, if any. Async
1381
+ * context tells exactly which code is inside; an invocation merely woken
1382
+ * meanwhile is not. A hosting effect's own effects are attributed to its
1383
+ * invocation: only those count as nested. Async context can be stale (code
1384
+ * resumed in the context of an effect that has ended, as an object's code
1385
+ * may run in the context it was built in): trust only a live frame of the
1386
+ * same invocation (the innermost), else the invocation's own hosting effect.
1387
+ */
1388
+ enclosing(invocation) {
1389
+ const store = effectScope?.getStore();
1390
+ const live = store?.active && store.invocation === invocation ? store : void 0;
1391
+ return effectScope ? live ?? this.hosting.get(invocation)?.at(-1) : this.stack.at(-1);
1392
+ }
1393
+ /** An effect starts being performed: it is in flight. */
1394
+ enter(frame) {
1395
+ this.inFlight++;
1396
+ this.stack.push(frame);
1397
+ if (frame.hosts) {
1398
+ this.hostingFrames(frame.invocation).push(frame);
1399
+ this.hostingCount++;
1400
+ }
1401
+ }
1402
+ /** An effect's perform has ended. */
1403
+ leave(frame) {
1404
+ if (frame.hosts) {
1405
+ const hosted = this.hostingFrames(frame.invocation);
1406
+ hosted.splice(hosted.lastIndexOf(frame), 1);
1407
+ this.hostingCount--;
1408
+ }
1409
+ this.stack.splice(this.stack.lastIndexOf(frame), 1);
1410
+ if (!frame.isWaiting()) this.inFlight--;
1411
+ else if (frame.parent) {
1412
+ const parent = frame.parent;
1413
+ this.adjust(parent, () => parent.waitingChildren--);
1414
+ }
1415
+ frame.active = false;
1416
+ frame.parent = void 0;
1417
+ }
1418
+ /**
1419
+ * Change a hosting frame's children and keep `inFlight` in step: a frame
1420
+ * counts in flight unless it is only waiting on parked effects of its own,
1421
+ * and a frame that starts or stops waiting does so for its parent too.
1422
+ */
1423
+ adjust(frame, change) {
1424
+ const before = frame.isWaiting();
1425
+ change();
1426
+ const after = frame.isWaiting();
1427
+ if (before === after) return;
1428
+ if (frame.active) this.inFlight += after ? -1 : 1;
1429
+ const parent = frame.parent;
1430
+ if (frame.active && parent) this.adjust(parent, () => parent.waitingChildren += after ? 1 : -1);
1431
+ }
1432
+ hostingFrames(invocation) {
1433
+ let frames = this.hosting.get(invocation);
1434
+ if (!frames) {
1435
+ frames = [];
1436
+ this.hosting.set(invocation, frames);
1437
+ }
1438
+ return frames;
1439
+ }
1440
+ };
1441
+ // packages/engine/src/turns.ts
1442
+ /**
1443
+ * The concurrent scheduler. Each asynchronous effect of a concurrent run is
1444
+ * a turn: the invocation parks there, and once every invocation has parked,
1445
+ * finished or gone idle the run picks which parked one goes next (or whether
1446
+ * a new event starts): from the recorded turns when replaying them, from the
1447
+ * chooser when exploring exhaustively, else from a stream seeded by the
1448
+ * schedule's seed. It also tracks whether turns told apart by their parked
1449
+ * effects' targets may not commute, which partial-order reduction needs.
1450
+ */
1451
+ var Turns = class {
1452
+ options;
1453
+ frames;
1454
+ /** Makes an invocation the running one. */
1455
+ runAs;
1456
+ /** The virtual globals' read counter, when they are installed. */
1457
+ reads;
1458
+ /** Invocations waiting at an effect for their turn. */
1459
+ parked = [];
1460
+ parkSeq = 0;
1461
+ /** The turns picked at decisions with more than one option, in order (see Schedule.turns). */
1462
+ picked = [];
1463
+ /** Turns taken from `schedule.turns` so far, when replaying recorded turns. */
1464
+ replayed = 0;
1465
+ /** Events started so far, to name the next start the same in every run. */
1466
+ starts = 0;
1467
+ /** The target of the turn running since the last decision; null for an event's start or none. */
1468
+ turnTarget = null;
1469
+ commuteNot = false;
1470
+ /** Woken whenever an invocation parks, a delivery ends or I/O completes. */
1471
+ progressWaiters = [];
1472
+ /** The order invocations started in, which orders the parked ones. */
1473
+ startOrder = /* @__PURE__ */ new Map();
1474
+ /** The picks among parked invocations, drawn apart from fault decisions. */
1475
+ prng;
1476
+ constructor(options, frames, runAs, reads) {
1477
+ this.options = options;
1478
+ this.frames = frames;
1479
+ this.runAs = runAs;
1480
+ this.reads = reads;
1481
+ this.prng = seedPrng(`turns:${options.schedule.seed}`);
1482
+ }
1483
+ /** The turns picked so far, as a copy. */
1484
+ get picks() {
1485
+ return [...this.picked];
1486
+ }
1487
+ /** An invocation started; its start orders its parked turns against others'. */
1488
+ started(id) {
1489
+ this.startOrder.set(id, this.startOrder.size);
1490
+ }
1491
+ /** Park an invocation at an effect until `takeTurn` releases it with `go`. */
1492
+ park(inv, target, go, host) {
1493
+ const option = {
1494
+ label: `${inv.id}@${inv.parks++}`,
1495
+ invocation: inv.id,
1496
+ target
1497
+ };
1498
+ this.parked.push({
1499
+ inv,
1500
+ seq: this.parkSeq++,
1501
+ go,
1502
+ option,
1503
+ ...host ? { host } : {}
1504
+ });
1505
+ this.progressed();
1506
+ }
1507
+ /** See `Run.turnsMayNotCommute`. */
1508
+ get mayNotCommute() {
1509
+ this.endSegment();
1510
+ return this.commuteNot;
1511
+ }
1512
+ /** See `Run.queuedEvents`. */
1513
+ queuedEvents() {
1514
+ if (this.turnTarget !== null) this.commuteNot = true;
1515
+ }
1516
+ /** An effect was performed: within a turn, one on another target is shared with other turns. */
1517
+ performed(target) {
1518
+ if (this.turnTarget !== null && target !== this.turnTarget) this.commuteNot = true;
1519
+ }
1520
+ /** Close the code run since the last decision, noting whether a turn read the shared virtual state. */
1521
+ endSegment() {
1522
+ const reads = this.reads();
1523
+ if (!reads) return;
1524
+ if (this.turnTarget !== null && reads.count > 0) this.commuteNot = true;
1525
+ reads.count = 0;
1526
+ }
1527
+ /** See `Run.progressed`. */
1528
+ progressed() {
1529
+ if (this.frames.hostingNow > 0) return;
1530
+ const waiters = this.progressWaiters;
1531
+ this.progressWaiters = [];
1532
+ for (const wake of waiters) wake();
1533
+ }
1534
+ /** See `Run.quiesce`. */
1535
+ async quiesce() {
1536
+ for (;;) {
1537
+ await Promise.race([new Promise((wake) => this.progressWaiters.push(wake)), realTick()]);
1538
+ await drainMicrotasks();
1539
+ if (this.frames.inFlight === 0) return;
1540
+ }
1541
+ }
1542
+ /** See `Run.takeTurn`. */
1543
+ takeTurn(canStart) {
1544
+ const order = (inv) => this.startOrder.get(inv.id) ?? 0;
1545
+ this.parked = this.parked.filter((p) => !p.inv.isCrashed()).sort((a, b) => order(a.inv) - order(b.inv) || a.seq - b.seq);
1546
+ const options = this.parked.length + (canStart ? 1 : 0);
1547
+ this.endSegment();
1548
+ this.turnTarget = null;
1549
+ if (options === 0) return "none";
1550
+ let pick = 0;
1551
+ if (options > 1) {
1552
+ pick = this.pickTurn(options, canStart);
1553
+ this.picked.push(pick);
1554
+ } else if (this.options.chooser && this.options.mode === "explore") this.options.chooser.choose("turn", this.turnOptions(canStart));
1555
+ const [chosen] = pick < this.parked.length ? this.parked.splice(pick, 1) : [];
1556
+ if (!chosen) {
1557
+ this.starts++;
1558
+ return "start";
1559
+ }
1560
+ this.turnTarget = chosen.option.target ?? null;
1561
+ this.runAs(chosen.inv.id);
1562
+ const host = chosen.host;
1563
+ if (host) this.frames.adjust(host, () => host.waitingChildren--);
1564
+ chosen.go();
1565
+ return "turn";
1566
+ }
1567
+ /** The turns on offer, as choices: the parked invocations in order, then starting the next event. */
1568
+ turnOptions(canStart) {
1569
+ return [...this.parked.map((p) => p.option), ...canStart ? [{ label: `start:${this.starts}` }] : []];
1570
+ }
1571
+ /** The turn at a decision with more than one option: recorded, chosen, or drawn from the seed. */
1572
+ pickTurn(options, canStart) {
1573
+ const recorded = this.options.schedule.turns;
1574
+ if (this.options.mode === "replay" && recorded) {
1575
+ const i = recorded[this.replayed++] ?? 0;
1576
+ return i < options ? i : 0;
1577
+ }
1578
+ const chooser = this.options.chooser;
1579
+ if (chooser && this.options.mode === "explore") return chooser.choose("turn", this.turnOptions(canStart));
1580
+ const [i, next] = nextInt(this.prng, options);
1581
+ this.prng = next;
1582
+ return i;
1050
1583
  }
1051
- }
1584
+ };
1052
1585
  // packages/engine/src/run.ts
1053
1586
  /**
1054
1587
  * One run of a scenario: the effect log being built, the fault decisions
@@ -1057,14 +1590,11 @@ async function withoutNetwork(work) {
1057
1590
  * around every real effect; everything else is engine-internal.
1058
1591
  *
1059
1592
  * 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.
1593
+ * invocations are in flight and each asynchronous effect is a turn, which
1594
+ * `turns.ts` schedules; `frames.ts` tracks effects nested in others and what
1595
+ * is in flight. Each delivery runs in its own async context, so an effect is
1596
+ * attributed to the invocation whose code made it even when a promise shared
1597
+ * between invocations resumes one during another's turn.
1068
1598
  */
1069
1599
  /** Thrown into user code by a synchronous effect that crashes the invocation. */
1070
1600
  var CrashSignal = class extends Error {
@@ -1114,56 +1644,6 @@ var InvocationState = class {
1114
1644
  }
1115
1645
  };
1116
1646
  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
1647
  /** The run whose globals are installed, if any: where code observed from outside records into. */
1168
1648
  let installed = null;
1169
1649
  function installedRun() {
@@ -1175,43 +1655,28 @@ const concurrencySupported = deliveryScope !== null;
1175
1655
  function hang() {
1176
1656
  return new Promise(() => {});
1177
1657
  }
1658
+ /** Why an invocation that nothing can move is abandoned. */
1659
+ function waitingUnseen(invocation) {
1660
+ return `invocation ${invocation} is waiting on something Eutaxy cannot see (no effect in flight, no timer due)`;
1661
+ }
1662
+ /** Delivered invocations are `<event>#<attempt>`, so this id is never one of theirs. */
1663
+ const bookkeepingId = "platform";
1178
1664
  var Run = class {
1179
1665
  logState = emptyLog;
1180
1666
  faults = [];
1181
1667
  effectIndex = 0;
1668
+ eligibleSeen = 0;
1182
1669
  prng;
1183
1670
  invocations = /* @__PURE__ */ new Map();
1184
1671
  reasons = [];
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;
1672
+ frames = new Frames();
1192
1673
  patched = null;
1193
1674
  restoreFetch = null;
1194
1675
  /** The invocation whose code is running (one at a time); outbound fetches are attributed to it. */
1195
1676
  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
1677
  /** Events a platform queued during a delivery, for the run loop to pick up. */
1209
1678
  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. */
1679
+ /** Concurrent runs only: the scheduler of turns. */
1215
1680
  turns;
1216
1681
  /** Whether several invocations may be in flight (`maxConcurrentInvocations` above 1). */
1217
1682
  concurrent;
@@ -1219,7 +1684,7 @@ var Run = class {
1219
1684
  constructor(options) {
1220
1685
  this.options = options;
1221
1686
  this.prng = seedPrng(options.schedule.seed);
1222
- this.turns = seedPrng(`turns:${options.schedule.seed}`);
1687
+ this.turns = new Turns(options, this.frames, (id) => this.runAs(id), () => this.patched?.reads);
1223
1688
  this.concurrent = options.bounds.maxConcurrentInvocations > 1;
1224
1689
  }
1225
1690
  get log() {
@@ -1231,7 +1696,7 @@ var Run = class {
1231
1696
  return {
1232
1697
  seed: this.options.schedule.seed,
1233
1698
  faults: [...this.faults],
1234
- ...recorded ? { turns: [...this.turnPicks] } : {}
1699
+ ...recorded ? { turns: [...this.turns.picks] } : {}
1235
1700
  };
1236
1701
  }
1237
1702
  get effectPoints() {
@@ -1249,8 +1714,7 @@ var Run = class {
1249
1714
  * does does not count.
1250
1715
  */
1251
1716
  get turnsMayNotCommute() {
1252
- this.endSegment();
1253
- return this.turnsCommuteNot;
1717
+ return this.turns.mayNotCommute;
1254
1718
  }
1255
1719
  /**
1256
1720
  * Concurrent runs: events were queued since the last decision (follow-ups
@@ -1258,14 +1722,7 @@ var Run = class {
1258
1722
  * within a turn this is another dependence.
1259
1723
  */
1260
1724
  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;
1725
+ this.turns.queuedEvents();
1269
1726
  }
1270
1727
  get unsupportedReasons() {
1271
1728
  return this.reasons;
@@ -1275,9 +1732,9 @@ var Run = class {
1275
1732
  installed = this;
1276
1733
  if (!this.patched) {
1277
1734
  this.patched = patchGlobals(this.options.schedule.seed, { trackIo: (work) => {
1278
- this.inFlight++;
1735
+ this.frames.inFlight++;
1279
1736
  return work.finally(() => {
1280
- this.inFlight--;
1737
+ this.frames.inFlight--;
1281
1738
  if (this.concurrent) this.progressed();
1282
1739
  });
1283
1740
  } });
@@ -1313,12 +1770,10 @@ var Run = class {
1313
1770
  return this.patched?.clock.pendingTimers() ?? 0;
1314
1771
  }
1315
1772
  startInvocation(id, options = {}) {
1316
- if (this.invocations.has(id)) throw new Error(`invocation ${id} already started`);
1317
- const inv = new InvocationState(id, () => this.patched?.clock.cancelOwner(id));
1318
- this.invocations.set(id, inv);
1773
+ const inv = this.track(id);
1319
1774
  if (options.bookkeeping) return inv;
1320
1775
  if (this.concurrent) {
1321
- this.startOrder.set(id, this.startOrder.size);
1776
+ this.turns.started(id);
1322
1777
  const cell = deliveryScope?.getStore();
1323
1778
  if (cell && cell.id === null) {
1324
1779
  cell.id = id;
@@ -1339,14 +1794,6 @@ var Run = class {
1339
1794
  this.queued = [];
1340
1795
  return queued;
1341
1796
  }
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
1797
  running() {
1351
1798
  if (!this.concurrent) return this.current;
1352
1799
  return deliveryScope?.getStore()?.id ?? this.current;
@@ -1355,12 +1802,35 @@ var Run = class {
1355
1802
  if (this.patched) this.patched.clock.owner = id;
1356
1803
  if (id !== null) this.current = id;
1357
1804
  }
1805
+ bookkeeping() {
1806
+ if (!this.invocations.has(bookkeepingId)) this.track(bookkeepingId);
1807
+ return bookkeepingId;
1808
+ }
1809
+ track(id) {
1810
+ if (this.invocations.has(id)) throw new Error(`invocation ${id} already started`);
1811
+ const inv = new InvocationState(id, () => this.patched?.clock.cancelOwner(id));
1812
+ this.invocations.set(id, inv);
1813
+ return inv;
1814
+ }
1358
1815
  invocation(id) {
1359
1816
  const inv = this.invocations.get(id);
1360
1817
  if (!inv) throw new Error(`effect from unknown invocation ${id}`);
1361
1818
  return inv;
1362
1819
  }
1820
+ /** Effect points so far that could take a fault (see `RunOptions.faultPlan`). */
1821
+ get eligiblePoints() {
1822
+ return this.eligibleSeen;
1823
+ }
1363
1824
  decide(point, ordinal) {
1825
+ const position = point.allowed.length > 0 ? this.eligibleSeen++ : -1;
1826
+ const plan = this.options.faultPlan;
1827
+ if (plan && this.options.mode === "explore" && !this.options.chooser) {
1828
+ if (position < 0 || this.faults.length >= this.options.bounds.maxFaultsPerRun) return null;
1829
+ if (!plan.includes(position)) return null;
1830
+ const [i, next] = nextInt(this.prng, point.allowed.length);
1831
+ this.prng = next;
1832
+ return point.allowed[i] ?? null;
1833
+ }
1364
1834
  const chooser = this.options.chooser;
1365
1835
  if (chooser && this.options.mode === "explore") {
1366
1836
  if (point.allowed.length === 0 || this.faults.length >= this.options.bounds.maxFaultsPerRun) return null;
@@ -1379,7 +1849,7 @@ var Run = class {
1379
1849
  return fault;
1380
1850
  }
1381
1851
  record(point, kind, payload) {
1382
- if (kind === "result" && this.turnTarget !== null && point.target !== this.turnTarget) this.turnsCommuteNot = true;
1852
+ if (kind === "result") this.turns.performed(point.target);
1383
1853
  this.logState = appendEffect(this.logState, {
1384
1854
  kind,
1385
1855
  invocation: point.invocation,
@@ -1406,39 +1876,22 @@ var Run = class {
1406
1876
  async effect(point, perform, summarize, options = {}) {
1407
1877
  const inv = this.invocation(point.invocation);
1408
1878
  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);
1879
+ const enclosing = this.frames.enclosing(point.invocation);
1412
1880
  const nested = enclosing !== void 0;
1413
1881
  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
- });
1882
+ await new Promise((go) => this.turns.park(inv, point.target, go));
1423
1883
  if (inv.isCrashed()) return hang();
1424
1884
  } else if (this.concurrent && enclosing?.hosts && enclosing.mayPark()) {
1425
1885
  const host = enclosing;
1426
1886
  let released = false;
1427
- this.adjust(host, () => {
1887
+ this.frames.adjust(host, () => {
1428
1888
  host.children++;
1429
1889
  host.waitingChildren++;
1430
1890
  });
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();
1891
+ this.turns.park(inv, point.target, () => released = true, host);
1439
1892
  while (!released && !inv.isCrashed()) await realTick();
1440
1893
  if (!released) {
1441
- this.adjust(host, () => {
1894
+ this.frames.adjust(host, () => {
1442
1895
  host.children--;
1443
1896
  host.waitingChildren--;
1444
1897
  });
@@ -1447,25 +1900,11 @@ var Run = class {
1447
1900
  try {
1448
1901
  return await this.performEffect(point, perform, summarize, options, inv, enclosing, host);
1449
1902
  } finally {
1450
- this.adjust(host, () => host.children--);
1903
+ this.frames.adjust(host, () => host.children--);
1451
1904
  }
1452
1905
  }
1453
1906
  return this.performEffect(point, perform, summarize, options, inv, enclosing);
1454
1907
  }
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
1908
  /** The effect once it has its turn: the fault, the perform under its deadline, the record. */
1470
1909
  async performEffect(point, perform, summarize, options, inv, enclosing, host) {
1471
1910
  const dead = () => {
@@ -1492,11 +1931,7 @@ var Run = class {
1492
1931
  const deadline = realDeadline(this.options.bounds.budgetMs);
1493
1932
  const frame = new Frame(point.invocation, point.hostsEffects === true, options);
1494
1933
  frame.parent = host;
1495
- const hosted = point.hostsEffects ? this.hostingFrames(point.invocation) : void 0;
1496
- this.inFlight++;
1497
- this.frames.push(frame);
1498
- hosted?.push(frame);
1499
- if (hosted) this.hostingNow++;
1934
+ this.frames.enter(frame);
1500
1935
  try {
1501
1936
  const inside = () => effectScope ? effectScope.run(frame, perform) : perform();
1502
1937
  const io = this.patched ? this.patched.libraryIo(inside) : inside();
@@ -1518,18 +1953,7 @@ var Run = class {
1518
1953
  };
1519
1954
  } finally {
1520
1955
  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;
1956
+ this.frames.leave(frame);
1533
1957
  this.patched?.clock.advance(1);
1534
1958
  if (this.concurrent) this.progressed();
1535
1959
  }
@@ -1631,13 +2055,13 @@ var Run = class {
1631
2055
  const patched = this.patched;
1632
2056
  if (patched) patched.clock.owner = invocation;
1633
2057
  this.current = invocation;
1634
- if (!patched) return Promise.race([promise, inv.crashed.then(() => new Promise(() => {}))]);
2058
+ if (!patched) return Promise.race([promise, inv.crashed.then(() => hang())]);
1635
2059
  return settleOn(promise, {
1636
2060
  clock: patched.clock,
1637
- inFlight: () => this.inFlight,
2061
+ inFlight: () => this.frames.inFlight,
1638
2062
  crashed: () => inv.isCrashed(),
1639
2063
  stuck: () => {
1640
- this.unsupported(`invocation ${invocation} is waiting on something Eutaxy cannot see (no effect in flight, no timer due)`);
2064
+ this.unsupported(waitingUnseen(invocation));
1641
2065
  inv.crash();
1642
2066
  }
1643
2067
  });
@@ -1654,10 +2078,7 @@ var Run = class {
1654
2078
  }
1655
2079
  /** Concurrent runs: something moved (an invocation parked, a delivery ended, I/O completed). */
1656
2080
  progressed() {
1657
- if (this.hostingNow > 0) return;
1658
- const waiters = this.progressWaiters;
1659
- this.progressWaiters = [];
1660
- for (const wake of waiters) wake();
2081
+ this.turns.progressed();
1661
2082
  }
1662
2083
  /**
1663
2084
  * Concurrent runs: wait until the running invocation has parked, finished
@@ -1666,12 +2087,8 @@ var Run = class {
1666
2087
  * off have run too. Code waiting on anything else gets one zero timer, the
1667
2088
  * same allowance the sequential path gives, before it counts as idle.
1668
2089
  */
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
- }
2090
+ quiesce() {
2091
+ return this.turns.quiesce();
1675
2092
  }
1676
2093
  /**
1677
2094
  * Concurrent runs: pick the next turn among the parked invocations and,
@@ -1680,53 +2097,7 @@ var Run = class {
1680
2097
  * real-time arrival. Returns what was picked; "turn" has already released it.
1681
2098
  */
1682
2099
  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;
2100
+ return this.turns.takeTurn(canStart);
1730
2101
  }
1731
2102
  /**
1732
2103
  * Let virtual time pass until `at`: timers due by then fire first, in due
@@ -1741,7 +2112,7 @@ var Run = class {
1741
2112
  clock.fireNext();
1742
2113
  do
1743
2114
  await drainMicrotasks();
1744
- while (this.inFlight > 0);
2115
+ while (this.frames.inFlight > 0);
1745
2116
  }
1746
2117
  clock.advance(at - clock.now());
1747
2118
  }
@@ -1767,7 +2138,7 @@ var Run = class {
1767
2138
  for (const id of ids) {
1768
2139
  const inv = this.invocations.get(id);
1769
2140
  if (!inv || inv.isCrashed()) continue;
1770
- this.unsupported(`invocation ${id} is waiting on something Eutaxy cannot see (no effect in flight, no timer due)`);
2141
+ this.unsupported(waitingUnseen(id));
1771
2142
  inv.crash();
1772
2143
  abandoned++;
1773
2144
  }
@@ -1863,7 +2234,7 @@ const engineAssumptions = [
1863
2234
  "faults: crash_before, crash_after, ambiguous, error at any effect point; redelivery per the platform's queue model",
1864
2235
  "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",
1865
2236
  "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",
2237
+ "an effect whose real I/O takes longer than the time budget (the scenario's budgetMs, or the budgetMs option replacing it) is treated as hung: the run is UNSUPPORTED and names the effect",
1867
2238
  "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",
1868
2239
  "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)",
1869
2240
  "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"
@@ -1974,10 +2345,19 @@ async function replayRun(spec, platform, schedule) {
1974
2345
  async function replay(spec, platform, schedule) {
1975
2346
  return (await replayRun(spec, platform, schedule)).log;
1976
2347
  }
1977
- async function explore(spec, platform, options) {
2348
+ async function explore(scenario, platform, options) {
2349
+ const budgetMs = options.budgetMs;
2350
+ if (budgetMs !== void 0 && !(Number.isFinite(budgetMs) && budgetMs > 0)) throw new Error(`budgetMs must be a positive finite number, got ${budgetMs}`);
2351
+ const spec = budgetMs === void 0 ? scenario : {
2352
+ ...scenario,
2353
+ bounds: {
2354
+ ...scenario.bounds,
2355
+ budgetMs
2356
+ }
2357
+ };
1978
2358
  const now = options.now ?? (() => Date.now());
1979
2359
  const maxRuns = options.maxRuns ?? 100;
1980
- const faultProbability = options.faultProbability ?? .5;
2360
+ const faultProbability = options.faultProbability ?? .9;
1981
2361
  const assumptions = [
1982
2362
  ...engineAssumptions,
1983
2363
  concurrencyAssumption(spec.bounds),
@@ -2017,49 +2397,42 @@ async function explore(spec, platform, options) {
2017
2397
  /** The first runs' schedules and digests, replayed in reverse order before BOUNDED. */
2018
2398
  const witnesses = [];
2019
2399
  let master = seedPrng(options.seed);
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
- } } : {};
2400
+ /** Eligible points of a run without faults, and the most any run has had: seeded fault positions. */
2401
+ let baseline = 0;
2402
+ let longest = 0;
2403
+ const exhaustive = options.exhaustive ? new ExhaustiveDriver(typeof options.exhaustive === "object" ? options.exhaustive.reduction ?? true : true) : null;
2030
2404
  const doneNow = () => ({
2031
2405
  ...done(),
2032
- ...exhaustiveReached()
2406
+ ...exhaustive ? { exhaustive: exhaustive.reached } : {}
2033
2407
  });
2034
- while (more && reached.runs < maxRuns && now() - start < spec.bounds.budgetMs) {
2408
+ while ((exhaustive?.hasMore ?? true) && reached.runs < maxRuns && now() - start < spec.bounds.budgetMs) {
2035
2409
  const [runSeed, next] = nextU32(master);
2036
2410
  master = next;
2411
+ let faultPlan = [];
2412
+ if (!exhaustive) [faultPlan, master] = planFaults(master, baseline, longest, spec.bounds.maxFaultsPerRun, faultProbability);
2037
2413
  const run = new Run({
2038
2414
  mode: "explore",
2039
2415
  schedule: {
2040
- seed: enumerator ? 0 : runSeed,
2416
+ seed: exhaustive ? 0 : runSeed,
2041
2417
  faults: []
2042
2418
  },
2043
2419
  bounds: spec.bounds,
2044
2420
  faultProbability,
2045
- ...enumerator ? { chooser: enumerator.next() } : {}
2421
+ ...exhaustive ? { chooser: exhaustive.next() } : { faultPlan }
2046
2422
  });
2047
2423
  const log = await runOnce(spec, platform, run);
2048
2424
  reached.runs++;
2049
- if (enumerator) {
2050
- if (enumerator.mismatch) return {
2425
+ if (run.faultsInjected === 0) baseline = Math.max(baseline, run.eligiblePoints);
2426
+ longest = Math.max(longest, run.eligiblePoints);
2427
+ if (exhaustive) {
2428
+ if (exhaustive.mismatch) return {
2051
2429
  ...base,
2052
2430
  kind: "UNSUPPORTED",
2053
2431
  cause: "not_replayable",
2054
- reason: `exhaustive exploration needs deterministic runs: ${enumerator.mismatch}`,
2432
+ reason: `exhaustive exploration needs deterministic runs: ${exhaustive.mismatch}`,
2055
2433
  reached: doneNow()
2056
2434
  };
2057
- restart = reduction && run.turnsMayNotCommute;
2058
- if (!restart) {
2059
- more = enumerator.advance();
2060
- if (enumerator.blocked) continue;
2061
- schedules++;
2062
- }
2435
+ if (!exhaustive.ran(() => run.turnsMayNotCommute)) continue;
2063
2436
  }
2064
2437
  reached.effectPoints += run.effectPoints;
2065
2438
  reached.faultsInjected += run.faultsInjected;
@@ -2108,11 +2481,7 @@ async function explore(spec, platform, options) {
2108
2481
  reached: doneNow()
2109
2482
  };
2110
2483
  }
2111
- if (restart) {
2112
- reduction = false;
2113
- enumerator = new Enumerator({ reduction });
2114
- schedules = 0;
2115
- }
2484
+ exhaustive?.checked();
2116
2485
  }
2117
2486
  for (const witness of [...witnesses].reverse()) {
2118
2487
  const again = await replayRun(spec, platform, witness.schedule);
@@ -2132,36 +2501,91 @@ async function explore(spec, platform, options) {
2132
2501
  reached: doneNow()
2133
2502
  };
2134
2503
  }
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);
2504
+ // packages/engine/src/differential.ts
2505
+ /**
2506
+ * The platform-neutral half of a differential check: the same fault-free
2507
+ * scenario once through Eutaxy (this module) and once against the raw
2508
+ * bindings (each platform's own, sharing no proxy code), then a comparison
2509
+ * of what each attempt decided and of the final state. Any difference is a
2510
+ * bug in the proxies or the platform model, not in the handler.
2511
+ */
2512
+ /** The raw side cannot abandon an invocation the way the engine does; a stuck handler ends the comparison. */
2513
+ var DifferentialStuck = class extends Error {
2514
+ name = "DifferentialStuck";
2515
+ constructor(message = "raw side: the handler is waiting on something outside the run (no effect in flight, no timer due)") {
2516
+ super(message);
2163
2517
  }
2518
+ };
2519
+ /**
2520
+ * The Eutaxy side: one run with no faults, one event at a time whatever the
2521
+ * scenario's bound (the raw side cannot interleave), with `attempt` given
2522
+ * each delivery's event, result and log entries.
2523
+ */
2524
+ async function proxiedSide(spec, platform, attempt) {
2525
+ const run = new Run({
2526
+ mode: "replay",
2527
+ schedule: {
2528
+ seed: 0,
2529
+ faults: []
2530
+ },
2531
+ bounds: {
2532
+ ...spec.bounds,
2533
+ maxConcurrentInvocations: 1
2534
+ },
2535
+ faultProbability: 0
2536
+ });
2537
+ const attempts = [];
2538
+ const { finish, cleanup } = platform;
2539
+ await runOnce(spec, {
2540
+ name: platform.name,
2541
+ assumptions: platform.assumptions,
2542
+ ...platform.concurrent === void 0 ? {} : { concurrent: platform.concurrent },
2543
+ reset: (s) => platform.reset(s),
2544
+ initialEvents: (s) => platform.initialEvents(s),
2545
+ restrictEvents: (s, keep) => platform.restrictEvents(s, keep),
2546
+ async deliver(event, hooks, s) {
2547
+ const before = run.log.entries.length;
2548
+ const result = await platform.deliver(event, hooks, s);
2549
+ attempts.push(attempt(event, result, run.log.entries.slice(before)));
2550
+ return result;
2551
+ },
2552
+ ...finish ? { finish: (s, hooks) => finish.call(platform, s, hooks) } : {},
2553
+ ...cleanup ? { cleanup: (s) => cleanup.call(platform, s) } : {}
2554
+ }, run);
2555
+ return {
2556
+ attempts,
2557
+ unsupported: run.unsupportedReasons
2558
+ };
2559
+ }
2560
+ /** Every difference between the two sides, one readable entry each; none means they agree. */
2561
+ function compareSides(eutaxy, raw, unsupported) {
2562
+ const differences = [];
2563
+ if (unsupported.length > 0) differences.push(`the proxied run touched unsupported APIs: ${unsupported.join("; ")}`);
2564
+ const a = canonicalJson(eutaxy.attempts);
2565
+ const b = canonicalJson(raw.attempts);
2566
+ if (a !== b) differences.push(`attempts differ:\n eutaxy ${a}\n raw ${b}`);
2567
+ const names = /* @__PURE__ */ new Set([...Object.keys(eutaxy.state), ...Object.keys(raw.state)]);
2568
+ for (const name of [...names].sort()) {
2569
+ const x = canonicalJson(eutaxy.state[name] ?? []);
2570
+ const y = canonicalJson(raw.state[name] ?? []);
2571
+ if (x !== y) differences.push(`${name} differs:\n eutaxy ${x}\n raw ${y}`);
2572
+ }
2573
+ return differences;
2164
2574
  }
2575
+ // packages/engine/src/observe.ts
2576
+ /**
2577
+ * Observe a module's pure core functions while runs are installed: each call
2578
+ * from outside the module is recorded with its arguments, for spec checks
2579
+ * on the inputs the simulator passed, and logged as a decision of the
2580
+ * invocation that made it (`Core:<function>`, payload `{ args, result }` or
2581
+ * `{ args, error }`), for `refines`. Calls the module makes to itself do not
2582
+ * go through its exports and are not seen.
2583
+ *
2584
+ * Observing replaces the export on the module's namespace object, which
2585
+ * works where a bundler or test runner gives modules a namespace with
2586
+ * configurable properties (Vite, so Vitest and the Cloudflare plugin); a
2587
+ * native ESM namespace is frozen, and the function is reported unobservable.
2588
+ */
2165
2589
  function observeCore(namespace, functions) {
2166
2590
  const calls = [];
2167
2591
  const unobservable = Object.create(null);
@@ -2183,7 +2607,7 @@ function observeCore(namespace, functions) {
2183
2607
  threw
2184
2608
  });
2185
2609
  run.decision(name, {
2186
- args: summarize(args),
2610
+ args: toJson(args),
2187
2611
  ...payload
2188
2612
  });
2189
2613
  };
@@ -2198,28 +2622,22 @@ function observeCore(namespace, functions) {
2198
2622
  run.unsupported(`core function ${name} returned a promise; observed core functions must be synchronous and pure`);
2199
2623
  return value;
2200
2624
  }
2201
- record(false, { result: summarize(value) });
2625
+ record(false, { result: toJson(value) });
2202
2626
  return value;
2203
2627
  };
2204
- const descriptor = Object.getOwnPropertyDescriptor(target, name);
2628
+ let restore;
2205
2629
  try {
2206
- Object.defineProperty(target, name, {
2207
- configurable: true,
2208
- enumerable: descriptor?.enumerable ?? true,
2209
- get: () => wrapped
2210
- });
2630
+ restore = patchProperty(target, name, { get: () => wrapped });
2211
2631
  } catch (err) {
2212
2632
  unobservable[name] = `its module's namespace cannot be changed here (${String(err)})`;
2213
2633
  continue;
2214
2634
  }
2215
2635
  if (target[name] !== wrapped) {
2636
+ restore();
2216
2637
  unobservable[name] = "its module's namespace did not take the observer";
2217
2638
  continue;
2218
2639
  }
2219
- undo.push(() => {
2220
- if (descriptor) Object.defineProperty(target, name, descriptor);
2221
- else delete target[name];
2222
- });
2640
+ undo.push(restore);
2223
2641
  }
2224
2642
  let restored = false;
2225
2643
  return {
@@ -2232,6 +2650,6 @@ function observeCore(namespace, functions) {
2232
2650
  }
2233
2651
  };
2234
2652
  }
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 };
2653
+ export { canonicalJson as S, defaultBounds as _, explore as a, checkInvariants as b, CrashSignal as c, withoutNetwork as d, patchGlobals as f, toJson as g, patchProperty as h, proxiedSide as i, InjectedEffectError as l, settleOn as m, DifferentialStuck as n, replay as o, realTick as p, compareSides as r, restrictSpec as s, observeCore as t, installScriptedFetch as u, validateScenario as v, getPath as x, checkInvariant as y };
2236
2654
 
2237
- //# sourceMappingURL=src-C19_yfMM.mjs.map
2655
+ //# sourceMappingURL=src-Bqc9Eyb1.mjs.map