eutaxy 0.15.0 → 0.15.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.
@@ -31,16 +31,19 @@ function canonicalJson(value) {
31
31
  }
32
32
  // packages/core/src/selectors.ts
33
33
  /** Picking effect records out of the log, and reading paths out of their payloads. */
34
+ const partsOf = (path) => path === "" ? [] : path.split(".");
35
+ const indexPattern = /^(0|[1-9]\d*)$/;
34
36
  /** Read a dot path such as "args.params.0" out of JSON data; undefined when absent. */
35
37
  function getPath(value, path) {
38
+ return readParts(value, partsOf(path));
39
+ }
40
+ function readParts(value, parts) {
36
41
  let cur = value;
37
- if (path === "") return cur;
38
- for (const part of path.split(".")) {
42
+ for (const part of parts) {
39
43
  if (cur === null || typeof cur !== "object") return void 0;
40
44
  if (Array.isArray(cur)) {
41
- const i = Number(part);
42
- if (!Number.isInteger(i) || i < 0) return void 0;
43
- cur = cur[i];
45
+ if (!indexPattern.test(part)) return void 0;
46
+ cur = cur[Number(part)];
44
47
  } else cur = cur[part];
45
48
  if (cur === void 0) return void 0;
46
49
  }
@@ -58,61 +61,30 @@ function jsonEqual(a, b) {
58
61
  const bk = Object.keys(bo).sort();
59
62
  return ak.length === bk.length && ak.every((k, i) => k === bk[i] && jsonEqual(ao[k], bo[k]));
60
63
  }
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;
64
+ function compileSelector(sel) {
65
+ const where = Object.entries(sel.where ?? {}).map(([p, want]) => [partsOf(p), want]);
66
+ const atLeast = Object.entries(sel.atLeast ?? {}).map(([p, min]) => [partsOf(p), min]);
67
+ return (record) => {
68
+ if (record.target !== sel.target) return false;
69
+ if (sel.op !== void 0 && record.op !== sel.op) return false;
70
+ if (sel.kind !== void 0 && record.kind !== sel.kind) return false;
71
+ for (const [parts, want] of where) if (!jsonEqual(readParts(record.payload, parts), want)) return false;
72
+ for (const [parts, min] of atLeast) {
73
+ const v = readParts(record.payload, parts);
74
+ if (typeof v !== "number" || v < min) return false;
75
+ }
76
+ return true;
77
+ };
73
78
  }
74
79
  function selectEffects(log, sel) {
75
- return log.entries.filter((e) => matches(e, sel));
80
+ return log.entries.filter(compileSelector(sel));
76
81
  }
77
82
  /** Canonical form of a key, so equal JSON values compare equal whatever their key order. */
78
83
  function keyOf(record, path) {
79
84
  const v = getPath(record.payload, path);
80
85
  return v === void 0 ? void 0 : canonicalJson(v);
81
86
  }
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
- }
87
+ Object.freeze({ entries: Object.freeze([]) });
116
88
  /** One canonical JSON object per line, in sequence order. */
117
89
  function serializeLog(log) {
118
90
  return log.entries.map((e) => canonicalJson({
@@ -124,16 +96,6 @@ function serializeLog(log) {
124
96
  payload: e.payload
125
97
  })).join("\n");
126
98
  }
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
- }
137
99
  // packages/core/src/prng.ts
138
100
  function rotl(x, k) {
139
101
  return (x << k | x >>> 32 - k) >>> 0;
@@ -279,14 +241,27 @@ function decisionTarget(fn) {
279
241
  }
280
242
  function checkRefines(log, inv) {
281
243
  const target = decisionTarget(inv.decision);
244
+ const entries = log.entries;
245
+ const lastBelow = (seq) => {
246
+ if (entries[seq - 1]?.seq === seq - 1) return seq - 1;
247
+ let i = entries.length - 1;
248
+ while (i >= 0 && entries[i].seq >= seq) i--;
249
+ return i;
250
+ };
251
+ const firstAbove = (seq) => {
252
+ if (entries[seq + 1]?.seq === seq + 1) return seq + 1;
253
+ const i = entries.findIndex((e) => e.seq > seq);
254
+ return i === -1 ? entries.length : i;
255
+ };
256
+ /** The last record before `seq` in `invocation` that `pick` accepts. */
282
257
  const before = (seq, invocation, pick) => {
283
- let found;
284
- for (const e of log.entries) {
285
- if (e.seq >= seq) break;
286
- if (e.invocation === invocation && pick(e)) found = e;
258
+ for (let i = lastBelow(seq); i >= 0; i--) {
259
+ const e = entries[i];
260
+ if (e.invocation === invocation && pick(e)) return e;
287
261
  }
288
- return found;
289
262
  };
263
+ const isRead = inv.state ? compileSelector(inv.state.read) : null;
264
+ const isWrite = inv.state ? compileSelector(inv.state.write) : null;
290
265
  for (const effect of selectEffects(log, inv.effect)) {
291
266
  const what = `${effect.target} ${effect.op} (seq ${effect.seq}) in ${effect.invocation}`;
292
267
  const decision = before(effect.seq, effect.invocation, (e) => e.target === target && e.kind === "result" && getPath(e.payload, "error") === void 0);
@@ -310,8 +285,8 @@ function checkRefines(log, inv) {
310
285
  }
311
286
  }
312
287
  const state = inv.state;
313
- if (!state) continue;
314
- const read = before(decision.seq, effect.invocation, (e) => matches(e, state.read));
288
+ if (!state || !isRead || !isWrite) continue;
289
+ const read = before(decision.seq, effect.invocation, isRead);
315
290
  if (!read) return {
316
291
  invariant: inv.name,
317
292
  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`,
@@ -319,7 +294,15 @@ function checkRefines(log, inv) {
319
294
  evidence: [decision.seq, effect.seq]
320
295
  };
321
296
  const key = state.key === void 0 ? void 0 : keyOf(read, state.key);
322
- 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));
297
+ let write;
298
+ for (let i = firstAbove(read.seq); i < entries.length; i++) {
299
+ const e = entries[i];
300
+ if (e.seq >= effect.seq) break;
301
+ if (e.invocation !== effect.invocation && isWrite(e) && (state.key === void 0 || keyOf(e, state.key) === key)) {
302
+ write = e;
303
+ break;
304
+ }
305
+ }
323
306
  if (write) return {
324
307
  invariant: inv.name,
325
308
  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`,
@@ -338,13 +321,17 @@ function checkRefines(log, inv) {
338
321
  /** State invariants: conditions on the rows of the end-of-run snapshots recorded in the log. */
339
322
  /** The tables in the last snapshot recorded for a target, or undefined when none was. */
340
323
  function lastSnapshot(log, target) {
324
+ const e = findSnapshot(log, target);
325
+ if (!e) return void 0;
326
+ const tables = getPath(e.payload, "tables");
327
+ if (tables && typeof tables === "object" && !Array.isArray(tables)) return tables;
328
+ return {};
329
+ }
330
+ /** The last snapshot recorded for a target, found from the end of the log. */
331
+ function findSnapshot(log, target) {
341
332
  for (let i = log.entries.length - 1; i >= 0; i--) {
342
333
  const e = log.entries[i];
343
- if (e.kind === "snapshot" && e.target === target) {
344
- const tables = getPath(e.payload, "tables");
345
- if (tables && typeof tables === "object" && !Array.isArray(tables)) return tables;
346
- return {};
347
- }
334
+ if (e.kind === "snapshot" && e.target === target) return e;
348
335
  }
349
336
  }
350
337
  function rowMatches(row, condition) {
@@ -369,9 +356,8 @@ function queryRows(log, query) {
369
356
  return rows.filter((r) => where.every((c) => rowMatches(r, c)));
370
357
  }
371
358
  function snapshotSeq(log, target) {
372
- let last;
373
- for (const e of log.entries) if (e.kind === "snapshot" && e.target === target) last = e.seq;
374
- return last === void 0 ? [] : [last];
359
+ const last = findSnapshot(log, target);
360
+ return last === void 0 ? [] : [last.seq];
375
361
  }
376
362
  function checkEveryRow(log, inv) {
377
363
  const rows = queryRows(log, inv.query);
@@ -882,7 +868,8 @@ var VirtualClock = class {
882
868
  return this.schedule(callback, delay, args, null);
883
869
  }
884
870
  setInterval(callback, delay = 0, ...args) {
885
- return this.schedule(callback, delay, args, Math.max(1, Math.floor(delay)));
871
+ const every = Number.isFinite(delay) && delay >= 1 ? Math.floor(delay) : 1;
872
+ return this.schedule(callback, delay, args, every);
886
873
  }
887
874
  clear(id) {
888
875
  this.timers = this.timers.filter((t) => t.id !== id);
@@ -1125,15 +1112,22 @@ async function settleOn(promise, ctx) {
1125
1112
  failed = true;
1126
1113
  error = e;
1127
1114
  });
1115
+ let afterTimer = false;
1128
1116
  for (;;) {
1129
- await Promise.race([tracked, realTick()]);
1117
+ await Promise.race([tracked, afterTimer ? eventLoopTurn() : realTick()]);
1118
+ const cheap = afterTimer;
1119
+ afterTimer = false;
1130
1120
  if (done) {
1131
1121
  if (failed) throw error;
1132
1122
  return value;
1133
1123
  }
1134
1124
  if (ctx.crashed()) return new Promise(() => {});
1135
1125
  if (ctx.inFlight() > 0) continue;
1136
- if (ctx.clock.fireNext()) continue;
1126
+ if (ctx.clock.fireNext()) {
1127
+ afterTimer = true;
1128
+ continue;
1129
+ }
1130
+ if (cheap) continue;
1137
1131
  ctx.stuck();
1138
1132
  return new Promise(() => {});
1139
1133
  }
@@ -1702,7 +1696,14 @@ function waitingUnseen(invocation) {
1702
1696
  /** Delivered invocations are `<event>#<attempt>`, so this id is never one of theirs. */
1703
1697
  const bookkeepingId = "platform";
1704
1698
  var Run = class {
1705
- logState = emptyLog;
1699
+ /** The records, appended in place. */
1700
+ entries = [];
1701
+ /**
1702
+ * The log last handed out, a snapshot of the records then: what a run returned never changes
1703
+ * under its reader, however late an abandoned effect's I/O records its result. Rebuilt on the
1704
+ * next read after a record, so a run reads it once at its end and a differential once per event.
1705
+ */
1706
+ logView = null;
1706
1707
  faults = [];
1707
1708
  effectIndex = 0;
1708
1709
  eligibleSeen = 0;
@@ -1732,7 +1733,8 @@ var Run = class {
1732
1733
  this.concurrent = options.bounds.maxConcurrentInvocations > 1;
1733
1734
  }
1734
1735
  get log() {
1735
- return this.logState;
1736
+ this.logView ??= { entries: [...this.entries] };
1737
+ return this.logView;
1736
1738
  }
1737
1739
  /** The schedule as actually executed: the faults taken and, when they do not follow the seed, the turns. */
1738
1740
  get schedule() {
@@ -1807,10 +1809,6 @@ var Run = class {
1807
1809
  now() {
1808
1810
  return this.patched ? this.patched.clock.now() : Date.now();
1809
1811
  }
1810
- /** Timers scheduled and not yet fired or cancelled (0 when the globals are not installed). */
1811
- pendingTimers() {
1812
- return this.patched?.clock.pendingTimers() ?? 0;
1813
- }
1814
1812
  startInvocation(id, options = {}) {
1815
1813
  const inv = this.track(id);
1816
1814
  if (options.bookkeeping) return inv;
@@ -1879,9 +1877,17 @@ var Run = class {
1879
1877
  }))]);
1880
1878
  return i === 0 ? null : point.allowed[i - 1] ?? null;
1881
1879
  }
1880
+ /** Append one record, with the next sequence number: O(1), so a long run's log stays cheap. */
1881
+ append(effect) {
1882
+ this.entries.push({
1883
+ ...effect,
1884
+ seq: this.entries.length
1885
+ });
1886
+ this.logView = null;
1887
+ }
1882
1888
  record(point, kind, payload) {
1883
1889
  if (kind === "result") this.turns.performed(point.target);
1884
- this.logState = appendEffect(this.logState, {
1890
+ this.append({
1885
1891
  kind,
1886
1892
  invocation: point.invocation,
1887
1893
  target: point.target,
@@ -1911,44 +1917,49 @@ var Run = class {
1911
1917
  const nested = enclosing !== void 0;
1912
1918
  if (this.concurrent && !nested) {
1913
1919
  const host = this.hosts.get(point.invocation);
1914
- if (host?.active) {
1915
- this.frames.adjust(host, () => {
1916
- host.children++;
1917
- host.waitingChildren++;
1918
- });
1919
- await new Promise((go) => this.turns.park(inv, point.target, go, host));
1920
- try {
1921
- return await this.performEffect(point, perform, summarize, options, inv, void 0, host);
1922
- } finally {
1923
- this.frames.adjust(host, () => host.children--);
1924
- }
1925
- }
1920
+ if (host?.active) return this.hostedTurn(point, perform, summarize, options, inv, void 0, host, (park) => new Promise((go) => park(() => go(true))));
1926
1921
  await new Promise((go) => this.turns.park(inv, point.target, go));
1927
1922
  if (inv.isCrashed()) return hang();
1928
- } else if (this.concurrent && enclosing?.hosts && enclosing.mayPark()) {
1929
- const host = enclosing;
1923
+ } else if (this.concurrent && enclosing?.hosts && enclosing.mayPark()) return this.hostedTurn(point, perform, summarize, options, inv, enclosing, enclosing, async (park) => {
1930
1924
  let released = false;
1931
- this.frames.adjust(host, () => {
1932
- host.children++;
1933
- host.waitingChildren++;
1934
- });
1935
- this.turns.park(inv, point.target, () => released = true, host);
1925
+ park(() => released = true);
1936
1926
  while (!released && !inv.isCrashed()) await realTick();
1937
- if (!released) {
1938
- this.frames.adjust(host, () => {
1939
- host.children--;
1940
- host.waitingChildren--;
1941
- });
1942
- return hang();
1943
- }
1944
- try {
1945
- return await this.performEffect(point, perform, summarize, options, inv, enclosing, host);
1946
- } finally {
1947
- this.frames.adjust(host, () => host.children--);
1948
- }
1949
- }
1927
+ return released;
1928
+ });
1950
1929
  return this.performEffect(point, perform, summarize, options, inv, enclosing);
1951
1930
  }
1931
+ /**
1932
+ * An effect that is a turn under `host` (the effect hosting the invocation, or the hosted code's
1933
+ * own enclosing effect): the host waits on it until `wait` gives it the turn, and is in flight
1934
+ * again while it performs. `wait` parks the effect through `park` and answers whether the turn
1935
+ * came; when it did not (the invocation crashed meanwhile) the effect hangs.
1936
+ */
1937
+ async hostedTurn(point, perform, summarize, options, inv, enclosing, host, wait) {
1938
+ this.childWaits(host);
1939
+ if (!await wait((go) => this.turns.park(inv, point.target, go, host))) {
1940
+ this.childLeaves(host, true);
1941
+ return hang();
1942
+ }
1943
+ try {
1944
+ return await this.performEffect(point, perform, summarize, options, inv, enclosing, host);
1945
+ } finally {
1946
+ this.childLeaves(host, false);
1947
+ }
1948
+ }
1949
+ /** A child of `host` started and waits for its turn (the scheduler clears the wait when it comes). */
1950
+ childWaits(host) {
1951
+ this.frames.adjust(host, () => {
1952
+ host.children++;
1953
+ host.waitingChildren++;
1954
+ });
1955
+ }
1956
+ /** A child of `host` ended; `stillWaiting` when its turn never came. */
1957
+ childLeaves(host, stillWaiting) {
1958
+ this.frames.adjust(host, () => {
1959
+ host.children--;
1960
+ if (stillWaiting) host.waitingChildren--;
1961
+ });
1962
+ }
1952
1963
  /** The effect once it has its turn: the fault, the perform under its deadline, the record. */
1953
1964
  async performEffect(point, perform, summarize, options, inv, enclosing, host) {
1954
1965
  const dead = () => {
@@ -1956,21 +1967,9 @@ var Run = class {
1956
1967
  return hang();
1957
1968
  };
1958
1969
  const fault = this.open(point, inv);
1959
- if (fault === "crash_before" || fault === "cut_off") {
1960
- this.record(point, "fault", {
1961
- args: point.args,
1962
- fault
1963
- });
1964
- inv.crash();
1965
- return dead();
1966
- }
1967
- if (fault === "error") {
1968
- this.record(point, "fault", {
1969
- args: point.args,
1970
- fault
1971
- });
1972
- throw new InjectedEffectError(point, fault);
1973
- }
1970
+ const before = this.faultBefore(point, inv, fault);
1971
+ if (before === "crashed") return dead();
1972
+ if (before) throw before;
1974
1973
  let settled;
1975
1974
  const deadline = realDeadline(this.options.bounds.budgetMs);
1976
1975
  const frame = new Frame(point.invocation, point.hostsEffects === true, options);
@@ -2022,42 +2021,50 @@ var Run = class {
2022
2021
  result: summarize(value)
2023
2022
  });
2024
2023
  if (inv.isCrashed()) return hang();
2024
+ const after = this.faultAfter(point, inv, fault);
2025
+ if (after === "crashed") return dead();
2026
+ if (after) throw after;
2027
+ return value;
2028
+ }
2029
+ /** A fault decided before the effect performs: the crash it is, the error to throw, or nothing. */
2030
+ faultBefore(point, inv, fault) {
2031
+ if (fault === "crash_before" || fault === "cut_off") {
2032
+ this.recordFault(point, fault);
2033
+ inv.crash();
2034
+ return "crashed";
2035
+ }
2036
+ if (fault === "error") {
2037
+ this.recordFault(point, fault);
2038
+ return new InjectedEffectError(point, fault);
2039
+ }
2040
+ return null;
2041
+ }
2042
+ /** A fault decided after the effect committed: the crash it is, the error to throw, or nothing. */
2043
+ faultAfter(point, inv, fault) {
2025
2044
  if (fault === "crash_after") {
2026
- this.record(point, "fault", {
2027
- args: point.args,
2028
- fault
2029
- });
2045
+ this.recordFault(point, fault);
2030
2046
  inv.crash();
2031
- return dead();
2047
+ return "crashed";
2032
2048
  }
2033
2049
  if (fault === "ambiguous") {
2034
- this.record(point, "fault", {
2035
- args: point.args,
2036
- fault
2037
- });
2038
- throw new InjectedEffectError(point, fault);
2050
+ this.recordFault(point, fault);
2051
+ return new InjectedEffectError(point, fault);
2039
2052
  }
2040
- return value;
2053
+ return null;
2054
+ }
2055
+ recordFault(point, fault) {
2056
+ this.record(point, "fault", {
2057
+ args: point.args,
2058
+ fault
2059
+ });
2041
2060
  }
2042
2061
  effectSync(point, perform, summarize) {
2043
2062
  const inv = this.invocation(point.invocation);
2044
2063
  if (inv.isCrashed()) throw new CrashSignal(inv.id);
2045
2064
  const fault = this.open(point, inv);
2046
- if (fault === "crash_before" || fault === "cut_off") {
2047
- this.record(point, "fault", {
2048
- args: point.args,
2049
- fault
2050
- });
2051
- inv.crash();
2052
- throw new CrashSignal(inv.id);
2053
- }
2054
- if (fault === "error") {
2055
- this.record(point, "fault", {
2056
- args: point.args,
2057
- fault
2058
- });
2059
- throw new InjectedEffectError(point, fault);
2060
- }
2065
+ const before = this.faultBefore(point, inv, fault);
2066
+ if (before === "crashed") throw new CrashSignal(inv.id);
2067
+ if (before) throw before;
2061
2068
  let value;
2062
2069
  try {
2063
2070
  value = perform();
@@ -2073,21 +2080,9 @@ var Run = class {
2073
2080
  args: point.args,
2074
2081
  result: summarize(value)
2075
2082
  });
2076
- if (fault === "crash_after") {
2077
- this.record(point, "fault", {
2078
- args: point.args,
2079
- fault
2080
- });
2081
- inv.crash();
2082
- throw new CrashSignal(inv.id);
2083
- }
2084
- if (fault === "ambiguous") {
2085
- this.record(point, "fault", {
2086
- args: point.args,
2087
- fault
2088
- });
2089
- throw new InjectedEffectError(point, fault);
2090
- }
2083
+ const after = this.faultAfter(point, inv, fault);
2084
+ if (after === "crashed") throw new CrashSignal(inv.id);
2085
+ if (after) throw after;
2091
2086
  return value;
2092
2087
  }
2093
2088
  unsupported(reason) {
@@ -2097,10 +2092,7 @@ var Run = class {
2097
2092
  const inv = this.invocation(invocation);
2098
2093
  if (this.concurrent) return Promise.race([promise, inv.crashed.then(() => hang())]);
2099
2094
  const patched = this.patched;
2100
- if (!this.hosts.has(invocation)) {
2101
- if (patched) patched.clock.owner = invocation;
2102
- this.current = invocation;
2103
- }
2095
+ if (!this.hosts.has(invocation)) this.runAs(invocation);
2104
2096
  if (!patched) return Promise.race([promise, inv.crashed.then(() => hang())]);
2105
2097
  return settleOn(promise, {
2106
2098
  clock: patched.clock,
@@ -2130,17 +2122,11 @@ var Run = class {
2130
2122
  const inv = this.track(id);
2131
2123
  if (this.concurrent) this.turns.started(id);
2132
2124
  this.hosts.set(id, frame);
2133
- this.frames.adjust(frame, () => {
2134
- frame.children++;
2135
- frame.waitingChildren++;
2136
- });
2125
+ this.childWaits(frame);
2137
2126
  try {
2138
2127
  return await work(inv);
2139
2128
  } finally {
2140
- this.frames.adjust(frame, () => {
2141
- frame.children--;
2142
- frame.waitingChildren--;
2143
- });
2129
+ this.childLeaves(frame, true);
2144
2130
  this.hosts.delete(id);
2145
2131
  }
2146
2132
  };
@@ -2246,7 +2232,7 @@ var Run = class {
2246
2232
  }
2247
2233
  /** A call of a pure core function, recorded as a decision of the invocation running now (see `observeCore`). */
2248
2234
  decision(fn, payload) {
2249
- this.logState = appendEffect(this.logState, {
2235
+ this.append({
2250
2236
  kind: "result",
2251
2237
  invocation: this.running(),
2252
2238
  target: decisionTarget(fn),
@@ -2255,7 +2241,7 @@ var Run = class {
2255
2241
  });
2256
2242
  }
2257
2243
  snapshot(invocation, target, payload) {
2258
- this.logState = appendEffect(this.logState, {
2244
+ this.append({
2259
2245
  kind: "snapshot",
2260
2246
  invocation,
2261
2247
  target,
@@ -2549,10 +2535,28 @@ function nextEvent(pending) {
2549
2535
  for (let i = 1; i < pending.length; i++) if ((pending[i]?.at ?? 0) < (pending[best]?.at ?? 0)) best = i;
2550
2536
  return best;
2551
2537
  }
2538
+ /** The first record a replay recorded differently from the run, or how their lengths differ; null when the logs match. */
2539
+ function whatDiffered(run, replay) {
2540
+ const show = (e) => {
2541
+ const payload = canonicalJson(e.payload);
2542
+ const shown = payload.length > 120 ? `${payload.slice(0, 117)}...` : payload;
2543
+ return `${e.kind} ${e.target} ${e.op} in ${e.invocation} ${shown}`;
2544
+ };
2545
+ const a = serializeLog(run).split("\n");
2546
+ const b = serializeLog(replay).split("\n");
2547
+ const n = Math.min(run.entries.length, replay.entries.length);
2548
+ for (let i = 0; i < n; i++) if (a[i] !== b[i]) return `at seq ${i} the run recorded ${show(run.entries[i])} and the replay ${show(replay.entries[i])}`;
2549
+ if (run.entries.length === replay.entries.length) return null;
2550
+ return `the run recorded ${run.entries.length} entries and the replay ${replay.entries.length}`;
2551
+ }
2552
+ /** Whether exhaustive exploration reduces by partial order (it does unless told not to). */
2553
+ function reductionOf(options) {
2554
+ return typeof options.exhaustive === "object" ? options.exhaustive.reduction ?? true : true;
2555
+ }
2552
2556
  /** What a verdict rests on about how schedules were chosen, when exploration was exhaustive. */
2553
2557
  function explorationAssumption(options) {
2554
2558
  if (!options.exhaustive) return [];
2555
- 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)"] : []];
2559
+ return ["exhaustive: every placement of faults within maxFaultsPerRun and every order of turns, each run once, until complete or the budget ends (reached.exhaustive says which)", ...reductionOf(options) ? ["partial-order reduction: turns of different invocations whose effects have different targets commute, so one order of them is run; this assumes code between an invocation's effects shares no state with other invocations except through effects and the virtual globals, and once a turn other than an event's start performs an effect on another target than its own, queues an event, or reads virtual time or randomness, or schedules a timer, the reduction is off and every order is run (reached.exhaustive.reduction says whether it stayed on)"] : []];
2556
2560
  }
2557
2561
  /** Deliver events one at a time, each to completion; time passes until a delayed one is due. */
2558
2562
  async function deliverInOrder(spec, platform, run) {
@@ -2682,20 +2686,20 @@ async function explore(scenario, platform, options) {
2682
2686
  seed: options.seed,
2683
2687
  assumptions
2684
2688
  };
2685
- if (spec.bounds.maxConcurrentInvocations > 1 && !concurrencySupported) return {
2686
- ...base,
2687
- kind: "UNSUPPORTED",
2688
- cause: "unsupported_bounds",
2689
- reason: "maxConcurrentInvocations above 1 needs AsyncLocalStorage (Node, or workerd with nodejs_compat or nodejs_als)",
2690
- reached: done()
2691
- };
2692
- if (spec.bounds.maxConcurrentInvocations > 1 && !platform.concurrent) return {
2689
+ const exhaustive = options.exhaustive ? new ExhaustiveDriver(reductionOf(options), spec.bounds.maxFaultsPerRun) : null;
2690
+ const doneNow = () => ({
2691
+ ...done(),
2692
+ ...exhaustive ? { exhaustive: exhaustive.reached } : {}
2693
+ });
2694
+ const unsupported = (cause, reason) => ({
2693
2695
  ...base,
2694
2696
  kind: "UNSUPPORTED",
2695
- cause: "unsupported_bounds",
2696
- reason: `maxConcurrentInvocations above 1 is not supported on the ${platform.name} platform yet`,
2697
- reached: done()
2698
- };
2697
+ cause,
2698
+ reason,
2699
+ reached: doneNow()
2700
+ });
2701
+ if (spec.bounds.maxConcurrentInvocations > 1 && !concurrencySupported) return unsupported("unsupported_bounds", "maxConcurrentInvocations above 1 needs AsyncLocalStorage (Node, or workerd with nodejs_compat or nodejs_als)");
2702
+ if (spec.bounds.maxConcurrentInvocations > 1 && !platform.concurrent) return unsupported("unsupported_bounds", `maxConcurrentInvocations above 1 is not supported on the ${platform.name} platform yet`);
2699
2703
  const leakCheckRuns = options.leakCheckRuns ?? 2;
2700
2704
  /** The first runs' schedules and digests, replayed in reverse order before BOUNDED. */
2701
2705
  const witnesses = [];
@@ -2703,11 +2707,6 @@ async function explore(scenario, platform, options) {
2703
2707
  /** Eligible points of a run without faults, and the most any run has had: seeded fault positions. */
2704
2708
  let baseline = 0;
2705
2709
  let longest = 0;
2706
- const exhaustive = options.exhaustive ? new ExhaustiveDriver(typeof options.exhaustive === "object" ? options.exhaustive.reduction ?? true : true, spec.bounds.maxFaultsPerRun) : null;
2707
- const doneNow = () => ({
2708
- ...done(),
2709
- ...exhaustive ? { exhaustive: exhaustive.reached } : {}
2710
- });
2711
2710
  while ((exhaustive?.hasMore ?? true) && reached.runs < maxRuns && now() - start < spec.bounds.budgetMs) {
2712
2711
  const [runSeed, next] = nextU32(master);
2713
2712
  master = next;
@@ -2726,41 +2725,25 @@ async function explore(scenario, platform, options) {
2726
2725
  if (run.faultsInjected === 0) baseline = Math.max(baseline, run.eligiblePoints);
2727
2726
  longest = Math.max(longest, run.eligiblePoints);
2728
2727
  if (exhaustive) {
2729
- if (exhaustive.mismatch) return {
2730
- ...base,
2731
- kind: "UNSUPPORTED",
2732
- cause: "not_replayable",
2733
- reason: `exhaustive exploration needs deterministic runs: ${exhaustive.mismatch}`,
2734
- reached: doneNow()
2735
- };
2728
+ if (exhaustive.mismatch) return unsupported("not_replayable", `exhaustive exploration needs deterministic runs: ${exhaustive.mismatch}`);
2736
2729
  if (!exhaustive.ran(() => run.turnsMayNotCommute)) continue;
2737
2730
  }
2738
2731
  reached.effectPoints += run.effectPoints;
2739
2732
  reached.faultsInjected += run.faultsInjected;
2740
2733
  if (witnesses.length < leakCheckRuns) witnesses.push({
2741
2734
  schedule: run.schedule,
2742
- digest: digestLog(log)
2735
+ log
2743
2736
  });
2744
- if (run.unsupportedReasons.length > 0) return {
2745
- ...base,
2746
- kind: "UNSUPPORTED",
2747
- cause: "unsupported_api",
2748
- reason: run.unsupportedReasons.join("; "),
2749
- reached: doneNow()
2750
- };
2737
+ if (run.unsupportedReasons.length > 0) return unsupported("unsupported_api", run.unsupportedReasons.join("; "));
2751
2738
  const violation = checkInvariants(log, spec.invariants)[0];
2752
2739
  if (violation) {
2753
2740
  const schedule = run.schedule;
2754
2741
  const replayedRun = await replayRun(spec, platform, schedule);
2755
2742
  const replayed = replayedRun.log;
2756
2743
  reached.runs++;
2757
- if (replayedRun.unsupportedReasons.length > 0 || digestLog(replayed) !== digestLog(log)) return {
2758
- ...base,
2759
- kind: "UNSUPPORTED",
2760
- cause: "not_replayable",
2761
- reason: `the violating run of seed ${schedule.seed} did not reproduce on replay`,
2762
- reached: doneNow()
2763
- };
2744
+ if (replayedRun.unsupportedReasons.length > 0) return unsupported("unsupported_api", replayedRun.unsupportedReasons.join("; "));
2745
+ const differed = whatDiffered(log, replayed);
2746
+ if (differed) return unsupported("not_replayable", `the violating run of seed ${schedule.seed} did not reproduce on replay: ${differed}`);
2764
2747
  const shrunk = await shrink(spec, platform, schedule, violation, replayed, {
2765
2748
  maxRuns: options.maxShrinkRuns ?? 200,
2766
2749
  deadline: now() + spec.bounds.budgetMs,
@@ -2787,13 +2770,9 @@ async function explore(scenario, platform, options) {
2787
2770
  for (const witness of [...witnesses].reverse()) {
2788
2771
  const again = await replayRun(spec, platform, witness.schedule);
2789
2772
  reached.runs++;
2790
- if (again.unsupportedReasons.length > 0 || digestLog(again.log) !== witness.digest) return {
2791
- ...base,
2792
- kind: "UNSUPPORTED",
2793
- cause: "module_state_leak",
2794
- 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)`,
2795
- reached: doneNow()
2796
- };
2773
+ if (again.unsupportedReasons.length > 0) return unsupported("unsupported_api", again.unsupportedReasons.join("; "));
2774
+ const differed = whatDiffered(witness.log, again.log);
2775
+ if (differed) return unsupported("module_state_leak", `run seed ${witness.schedule.seed} produced a different log when replayed after other runs: state is leaking between runs (module-level variables, or a binding Eutaxy does not reset); ${differed}`);
2797
2776
  }
2798
2777
  return {
2799
2778
  ...base,
@@ -2952,4 +2931,4 @@ function observeCore(namespace, functions) {
2952
2931
  }
2953
2932
  export { readFaults as A, patchProperty as C, checkInvariant as D, validateScenario as E, seedPrng as F, getPath as I, canonicalJson as L, nextFloat as M, nextInt as N, checkInvariants as O, nextU32 as P, virtualEpoch as S, defaultBounds as T, toResponse as _, explore as a, realTick as b, hostInvocation as c, InjectedEffectError as d, findResponse as f, replyOf as g, parseBody as h, proxiedSide as i, writeFaults as j, decisionFaults as k, runInvocation as l, isRedirect as m, DifferentialStuck as n, replay as o, installScriptedFetch as p, compareSides as r, restrictSpec as s, observeCore as t, CrashSignal as u, withoutNetwork as v, toJson as w, settleOn as x, patchGlobals as y };
2954
2933
 
2955
- //# sourceMappingURL=src-ud5wEfnx.mjs.map
2934
+ //# sourceMappingURL=src-CPuihHZh.mjs.map