eutaxy 0.4.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.
- package/README.md +2 -2
- package/dist/aws.d.mts +7 -5
- package/dist/aws.d.mts.map +1 -1
- package/dist/aws.mjs +41 -135
- package/dist/aws.mjs.map +1 -1
- package/dist/bin.mjs +2 -2
- package/dist/checked-CGpA2-F0.d.mts +285 -0
- package/dist/checked-CGpA2-F0.d.mts.map +1 -0
- package/dist/cli-IJrKkeYS.mjs +2 -0
- package/dist/cli.d.mts.map +1 -1
- package/dist/cli.mjs +2 -2
- package/dist/cloudflare.d.mts +232 -51
- package/dist/cloudflare.d.mts.map +1 -1
- package/dist/cloudflare.mjs +3 -1083
- package/dist/delivery-invariants-BraYqcYN.d.mts +5 -0
- package/dist/delivery-invariants-BraYqcYN.d.mts.map +1 -0
- package/dist/delivery-invariants-Cuxdna28.mjs +39 -0
- package/dist/delivery-invariants-Cuxdna28.mjs.map +1 -0
- package/dist/index.d.mts +66 -5
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +81 -5
- package/dist/index.mjs.map +1 -0
- package/dist/{platform-TwATAkL3.d.mts → platform-DfMwknw1.d.mts} +179 -42
- package/dist/platform-DfMwknw1.d.mts.map +1 -0
- package/dist/src-Bqc9Eyb1.mjs +2655 -0
- package/dist/src-Bqc9Eyb1.mjs.map +1 -0
- package/dist/src-DKb-fkdb.mjs +3399 -0
- package/dist/src-DKb-fkdb.mjs.map +1 -0
- package/dist/src-Dxl9ZlKn.mjs +1752 -0
- package/dist/src-Dxl9ZlKn.mjs.map +1 -0
- package/package.json +1 -1
- package/dist/cli-Dr-Ziogu.mjs +0 -2
- package/dist/cloudflare.mjs.map +0 -1
- package/dist/explore-YVHTRjjS.d.mts +0 -63
- package/dist/explore-YVHTRjjS.d.mts.map +0 -1
- package/dist/platform-TwATAkL3.d.mts.map +0 -1
- package/dist/src-BBXd0WEp.mjs +0 -117
- package/dist/src-BBXd0WEp.mjs.map +0 -1
- package/dist/src-BGdIBGkN.mjs +0 -311
- package/dist/src-BGdIBGkN.mjs.map +0 -1
- package/dist/src-Brt0dfNL.mjs +0 -1286
- package/dist/src-Brt0dfNL.mjs.map +0 -1
- package/dist/src-s6uYyC0B.mjs +0 -89
- package/dist/src-s6uYyC0B.mjs.map +0 -1
- package/dist/verdict-evEM5Gxx.mjs +0 -12
- package/dist/verdict-evEM5Gxx.mjs.map +0 -1
|
@@ -0,0 +1,2655 @@
|
|
|
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
|
+
}
|
|
137
|
+
// packages/core/src/prng.ts
|
|
138
|
+
function rotl(x, k) {
|
|
139
|
+
return (x << k | x >>> 32 - k) >>> 0;
|
|
140
|
+
}
|
|
141
|
+
/** splitmix32: expands a 32-bit seed into well-mixed words for seeding. */
|
|
142
|
+
function splitmix32(seed) {
|
|
143
|
+
let a = seed >>> 0;
|
|
144
|
+
return () => {
|
|
145
|
+
a = a + 2654435769 >>> 0;
|
|
146
|
+
let t = a;
|
|
147
|
+
t = Math.imul(t ^ t >>> 16, 569420461);
|
|
148
|
+
t = Math.imul(t ^ t >>> 15, 1935289751);
|
|
149
|
+
return (t ^ t >>> 15) >>> 0;
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
/** FNV-1a over UTF-16 code units, so string seeds are stable across runtimes. */
|
|
153
|
+
function hashString(s) {
|
|
154
|
+
let h = 2166136261;
|
|
155
|
+
for (let i = 0; i < s.length; i++) {
|
|
156
|
+
h ^= s.charCodeAt(i);
|
|
157
|
+
h = Math.imul(h, 16777619);
|
|
158
|
+
}
|
|
159
|
+
return h >>> 0;
|
|
160
|
+
}
|
|
161
|
+
/** Derive an initial state from a number (taken modulo 2^32) or a string. */
|
|
162
|
+
function seedPrng(seed) {
|
|
163
|
+
const next = splitmix32(typeof seed === "string" ? hashString(seed) : seed >>> 0);
|
|
164
|
+
const s = [
|
|
165
|
+
next(),
|
|
166
|
+
next(),
|
|
167
|
+
next(),
|
|
168
|
+
next()
|
|
169
|
+
];
|
|
170
|
+
if (s[0] === 0 && s[1] === 0 && s[2] === 0 && s[3] === 0) s[0] = 1;
|
|
171
|
+
return s;
|
|
172
|
+
}
|
|
173
|
+
/** Next 32-bit unsigned integer and the state that follows it. */
|
|
174
|
+
function nextU32(state) {
|
|
175
|
+
const [s0, s1, s2, s3] = state;
|
|
176
|
+
const result = Math.imul(rotl(Math.imul(s1, 5) >>> 0, 7), 9) >>> 0;
|
|
177
|
+
const t = s1 << 9 >>> 0;
|
|
178
|
+
let n2 = (s2 ^ s0) >>> 0;
|
|
179
|
+
let n3 = (s3 ^ s1) >>> 0;
|
|
180
|
+
const n1 = (s1 ^ n2) >>> 0;
|
|
181
|
+
const n0 = (s0 ^ n3) >>> 0;
|
|
182
|
+
n2 = (n2 ^ t) >>> 0;
|
|
183
|
+
n3 = rotl(n3, 11);
|
|
184
|
+
return [result, [
|
|
185
|
+
n0,
|
|
186
|
+
n1,
|
|
187
|
+
n2,
|
|
188
|
+
n3
|
|
189
|
+
]];
|
|
190
|
+
}
|
|
191
|
+
/** Next float in [0, 1) with 24 bits of precision. */
|
|
192
|
+
function nextFloat(state) {
|
|
193
|
+
const [u, next] = nextU32(state);
|
|
194
|
+
return [(u >>> 8) * 2 ** -24, next];
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Next integer in [0, bound). Uses rejection sampling, so every value is
|
|
198
|
+
* equally likely; a bound of 1 always yields 0 without consuming state.
|
|
199
|
+
*/
|
|
200
|
+
function nextInt(state, bound) {
|
|
201
|
+
if (!Number.isInteger(bound) || bound < 1 || bound > 4294967296) throw new RangeError(`nextInt bound must be an integer in [1, 2^32], got ${bound}`);
|
|
202
|
+
if (bound === 1) return [0, state];
|
|
203
|
+
const limit = 4294967296 - 4294967296 % bound;
|
|
204
|
+
let s = state;
|
|
205
|
+
for (;;) {
|
|
206
|
+
const [u, next] = nextU32(s);
|
|
207
|
+
s = next;
|
|
208
|
+
if (u < limit) return [u % bound, s];
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
// packages/core/src/faults.ts
|
|
212
|
+
/**
|
|
213
|
+
* The fault model and the schedule. A schedule is the complete, replayable
|
|
214
|
+
* record of which fault was injected at which effect point in one run.
|
|
215
|
+
*/
|
|
216
|
+
/**
|
|
217
|
+
* Decide whether to inject a fault at an effect point during exploration.
|
|
218
|
+
* Pure: the same state and inputs always give the same decision. The PRNG is
|
|
219
|
+
* only consumed when a fault is possible, so adding an ineligible point does
|
|
220
|
+
* not perturb later decisions.
|
|
221
|
+
*/
|
|
222
|
+
function decideFault(state, allowed, faultsSoFar, policy) {
|
|
223
|
+
if (allowed.length === 0 || faultsSoFar >= policy.maxFaultsPerRun) return [null, state];
|
|
224
|
+
const [p, s1] = nextFloat(state);
|
|
225
|
+
if (p >= policy.faultProbability) return [null, s1];
|
|
226
|
+
const [i, s2] = nextInt(s1, allowed.length);
|
|
227
|
+
return [allowed[i] ?? null, s2];
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
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.
|
|
237
|
+
*/
|
|
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];
|
|
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. */
|
|
256
|
+
/** The log target decisions of a core function are recorded under. */
|
|
257
|
+
function decisionTarget(fn) {
|
|
258
|
+
return `Core:${fn}`;
|
|
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. */
|
|
319
|
+
/** The tables in the last snapshot recorded for a target, or undefined when none was. */
|
|
320
|
+
function lastSnapshot(log, target) {
|
|
321
|
+
for (let i = log.entries.length - 1; i >= 0; i--) {
|
|
322
|
+
const e = log.entries[i];
|
|
323
|
+
if (e.kind === "snapshot" && e.target === target) {
|
|
324
|
+
const tables = getPath(e.payload, "tables");
|
|
325
|
+
if (tables && typeof tables === "object" && !Array.isArray(tables)) return tables;
|
|
326
|
+
return {};
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
function rowMatches(row, condition) {
|
|
331
|
+
const v = row[condition.column];
|
|
332
|
+
switch (condition.op) {
|
|
333
|
+
case "eq": return v !== void 0 && jsonEqual(v, condition.value);
|
|
334
|
+
case "neq": return v === void 0 || !jsonEqual(v, condition.value);
|
|
335
|
+
case "gt": return typeof v === "number" && v > condition.value;
|
|
336
|
+
case "gte": return typeof v === "number" && v >= condition.value;
|
|
337
|
+
case "lt": return typeof v === "number" && v < condition.value;
|
|
338
|
+
case "lte": return typeof v === "number" && v <= condition.value;
|
|
339
|
+
case "in": return v !== void 0 && condition.value.some((c) => jsonEqual(v, c));
|
|
340
|
+
case "notNull": return v !== void 0 && v !== null;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
/** Rows a state query selects from the log's last snapshot; undefined when there is no snapshot. */
|
|
344
|
+
function queryRows(log, query) {
|
|
345
|
+
const tables = lastSnapshot(log, query.target);
|
|
346
|
+
if (!tables) return void 0;
|
|
347
|
+
const rows = tables[query.table] ?? [];
|
|
348
|
+
const where = query.where ?? [];
|
|
349
|
+
return rows.filter((r) => where.every((c) => rowMatches(r, c)));
|
|
350
|
+
}
|
|
351
|
+
function snapshotSeq(log, target) {
|
|
352
|
+
let last;
|
|
353
|
+
for (const e of log.entries) if (e.kind === "snapshot" && e.target === target) last = e.seq;
|
|
354
|
+
return last === void 0 ? [] : [last];
|
|
355
|
+
}
|
|
356
|
+
function checkEveryRow(log, inv) {
|
|
357
|
+
const rows = queryRows(log, inv.query);
|
|
358
|
+
if (rows === void 0) return {
|
|
359
|
+
invariant: inv.name,
|
|
360
|
+
message: `no snapshot of ${inv.query.target} was recorded`,
|
|
361
|
+
keys: [],
|
|
362
|
+
evidence: []
|
|
363
|
+
};
|
|
364
|
+
const failing = rows.filter((r) => !inv.holds.every((c) => rowMatches(r, c)));
|
|
365
|
+
if (failing.length === 0) return null;
|
|
366
|
+
const keys = failing.map((r) => canonicalJson(r));
|
|
367
|
+
const shown = keys.slice(0, 3).join(", ") + (failing.length > 3 ? ", …" : "");
|
|
368
|
+
return {
|
|
369
|
+
invariant: inv.name,
|
|
370
|
+
message: `${failing.length} row(s) of ${inv.query.table} in ${inv.query.target} violate the condition: ${shown}`,
|
|
371
|
+
keys,
|
|
372
|
+
evidence: snapshotSeq(log, inv.query.target)
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
function checkUnique(log, inv) {
|
|
376
|
+
const rows = queryRows(log, inv.query);
|
|
377
|
+
if (rows === void 0) return {
|
|
378
|
+
invariant: inv.name,
|
|
379
|
+
message: `no snapshot of ${inv.query.target} was recorded`,
|
|
380
|
+
keys: [],
|
|
381
|
+
evidence: []
|
|
382
|
+
};
|
|
383
|
+
const counts = /* @__PURE__ */ new Map();
|
|
384
|
+
for (const r of rows) {
|
|
385
|
+
const v = getPath(r, inv.path);
|
|
386
|
+
if (v === void 0 || v === null) continue;
|
|
387
|
+
const k = canonicalJson(v);
|
|
388
|
+
counts.set(k, (counts.get(k) ?? 0) + 1);
|
|
389
|
+
}
|
|
390
|
+
const shared = [...counts].filter(([, n]) => n > 1);
|
|
391
|
+
if (shared.length === 0) return null;
|
|
392
|
+
const shown = shared.map(([k, n]) => `${n} rows of ${inv.query.table} in ${inv.query.target} share ${inv.path} = ${k}`);
|
|
393
|
+
return {
|
|
394
|
+
invariant: inv.name,
|
|
395
|
+
message: shown.join("; "),
|
|
396
|
+
keys: shared.map(([k]) => k),
|
|
397
|
+
evidence: snapshotSeq(log, inv.query.target)
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
function checkImplies(log, inv) {
|
|
401
|
+
const rows = queryRows(log, inv.state);
|
|
402
|
+
if (rows === void 0) return {
|
|
403
|
+
invariant: inv.name,
|
|
404
|
+
message: `no snapshot of ${inv.state.target} was recorded`,
|
|
405
|
+
keys: [],
|
|
406
|
+
evidence: []
|
|
407
|
+
};
|
|
408
|
+
const present = /* @__PURE__ */ new Set();
|
|
409
|
+
for (const r of rows) {
|
|
410
|
+
const v = r[inv.column];
|
|
411
|
+
if (v !== void 0) present.add(canonicalJson(v));
|
|
412
|
+
}
|
|
413
|
+
const missing = [];
|
|
414
|
+
const evidence = [];
|
|
415
|
+
for (const e of selectEffects(log, inv.when)) {
|
|
416
|
+
const k = keyOf(e, inv.key);
|
|
417
|
+
if (k === void 0 || present.has(k)) continue;
|
|
418
|
+
if (!missing.includes(k)) missing.push(k);
|
|
419
|
+
evidence.push(e.seq);
|
|
420
|
+
}
|
|
421
|
+
if (missing.length === 0) return null;
|
|
422
|
+
return {
|
|
423
|
+
invariant: inv.name,
|
|
424
|
+
message: `${inv.when.target} ${inv.when.op ?? "*"} happened for key(s) ${missing.join(", ")} but ${inv.state.table}.${inv.column} in ${inv.state.target} has no such row`,
|
|
425
|
+
keys: missing,
|
|
426
|
+
evidence
|
|
427
|
+
};
|
|
428
|
+
}
|
|
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: []
|
|
437
|
+
};
|
|
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
|
|
478
|
+
};
|
|
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 {
|
|
499
|
+
invariant: inv.name,
|
|
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]
|
|
503
|
+
};
|
|
504
|
+
seen.set(k, e.seq);
|
|
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
|
+
};
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
function checkInvariants(log, invariants) {
|
|
527
|
+
const out = [];
|
|
528
|
+
for (const inv of invariants) {
|
|
529
|
+
const v = checkInvariant(log, inv);
|
|
530
|
+
if (v) out.push(v);
|
|
531
|
+
}
|
|
532
|
+
return out;
|
|
533
|
+
}
|
|
534
|
+
// packages/core/src/scenario.ts
|
|
535
|
+
const defaultBounds = {
|
|
536
|
+
maxFaultsPerRun: 1,
|
|
537
|
+
maxRedeliveries: 2,
|
|
538
|
+
maxConcurrentInvocations: 1,
|
|
539
|
+
budgetMs: 2e3
|
|
540
|
+
};
|
|
541
|
+
function isPositiveInt(n) {
|
|
542
|
+
return typeof n === "number" && Number.isInteger(n) && n > 0;
|
|
543
|
+
}
|
|
544
|
+
/** Every reason a spec is not usable; empty when it is. */
|
|
545
|
+
function validateScenario(spec) {
|
|
546
|
+
const errors = [];
|
|
547
|
+
if (spec.version !== 1) errors.push(`version must be 1, got ${String(spec.version)}`);
|
|
548
|
+
if (!spec.name.trim()) errors.push("name must not be empty");
|
|
549
|
+
if (spec.platform !== void 0 && !spec.platform) errors.push("platform must not be empty when given");
|
|
550
|
+
if (!/^[a-z0-9][a-z0-9-]*$/.test(spec.name)) errors.push(`name must be lowercase letters, digits and dashes: ${JSON.stringify(spec.name)}`);
|
|
551
|
+
if (!spec.worker.entry) errors.push("worker.entry must not be empty");
|
|
552
|
+
if (!spec.worker.config) errors.push("worker.config must not be empty");
|
|
553
|
+
if (!spec.drive.kind) errors.push("drive.kind must not be empty");
|
|
554
|
+
spec.setup.forEach((s, i) => {
|
|
555
|
+
if (!s.kind) errors.push(`setup[${i}].kind must not be empty`);
|
|
556
|
+
});
|
|
557
|
+
if (spec.invariants.length === 0) errors.push("at least one invariant is required");
|
|
558
|
+
const names = /* @__PURE__ */ new Set();
|
|
559
|
+
for (const inv of spec.invariants) {
|
|
560
|
+
if (!inv.name) errors.push("every invariant needs a name");
|
|
561
|
+
else if (names.has(inv.name)) errors.push(`duplicate invariant name ${JSON.stringify(inv.name)}`);
|
|
562
|
+
names.add(inv.name);
|
|
563
|
+
}
|
|
564
|
+
const specs = /* @__PURE__ */ new Set();
|
|
565
|
+
for (const m of spec.specs ?? []) {
|
|
566
|
+
if (!m) errors.push("every specs entry needs a module path");
|
|
567
|
+
else if (specs.has(m)) errors.push(`duplicate specs module ${JSON.stringify(m)}`);
|
|
568
|
+
specs.add(m);
|
|
569
|
+
}
|
|
570
|
+
const ext = /* @__PURE__ */ new Set();
|
|
571
|
+
for (const e of spec.externals) {
|
|
572
|
+
if (!e.name) errors.push("every external needs a name");
|
|
573
|
+
if (ext.has(e.name)) errors.push(`duplicate external ${JSON.stringify(e.name)}`);
|
|
574
|
+
ext.add(e.name);
|
|
575
|
+
if (!e.host) errors.push(`external ${JSON.stringify(e.name)} needs a host`);
|
|
576
|
+
(e.responses ?? []).forEach((r, i) => {
|
|
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`);
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
for (const k of ["maxFaultsPerRun", "maxRedeliveries"]) {
|
|
581
|
+
const v = spec.bounds[k];
|
|
582
|
+
if (!(Number.isInteger(v) && v >= 0)) errors.push(`bounds.${k} must be a non-negative integer`);
|
|
583
|
+
}
|
|
584
|
+
for (const k of ["maxConcurrentInvocations", "budgetMs"]) if (!isPositiveInt(spec.bounds[k])) errors.push(`bounds.${k} must be a positive integer`);
|
|
585
|
+
return errors;
|
|
586
|
+
}
|
|
587
|
+
// packages/core/src/shrink.ts
|
|
588
|
+
/** One-step candidates: each single fault removed, then each single event removed. */
|
|
589
|
+
function shrinkCandidates(state) {
|
|
590
|
+
const out = [];
|
|
591
|
+
state.schedule.faults.forEach((_, i) => {
|
|
592
|
+
out.push({
|
|
593
|
+
schedule: {
|
|
594
|
+
...state.schedule,
|
|
595
|
+
faults: state.schedule.faults.filter((_, j) => j !== i)
|
|
596
|
+
},
|
|
597
|
+
keepIds: state.keepIds
|
|
598
|
+
});
|
|
599
|
+
});
|
|
600
|
+
if (state.keepIds.length > 1) state.keepIds.forEach((id) => {
|
|
601
|
+
out.push({
|
|
602
|
+
schedule: {
|
|
603
|
+
...state.schedule,
|
|
604
|
+
faults: state.schedule.faults.filter((f) => !f.invocation.startsWith(`${id}#`))
|
|
605
|
+
},
|
|
606
|
+
keepIds: state.keepIds.filter((k) => k !== id)
|
|
607
|
+
});
|
|
608
|
+
});
|
|
609
|
+
return out;
|
|
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
|
+
}
|
|
670
|
+
// packages/engine/src/context.ts
|
|
671
|
+
/** A new async context slot, or null where the host has no AsyncLocalStorage. */
|
|
672
|
+
function asyncScope() {
|
|
673
|
+
const mod = typeof process !== "undefined" ? process?.getBuiltinModule?.("node:async_hooks") : void 0;
|
|
674
|
+
return mod?.AsyncLocalStorage ? new mod.AsyncLocalStorage() : null;
|
|
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
|
+
}
|
|
706
|
+
// packages/engine/src/clock.ts
|
|
707
|
+
/**
|
|
708
|
+
* The virtual clock and the globals patch. Within a run, Date, Math.random,
|
|
709
|
+
* crypto.randomUUID, crypto.getRandomValues, performance.now and the timer
|
|
710
|
+
* functions are replaced by deterministic versions driven by the run's seed
|
|
711
|
+
* and by a clock that starts at a fixed epoch and advances only when the
|
|
712
|
+
* engine says so: one millisecond per effect, and to each timer's due time
|
|
713
|
+
* when the timer fires. Timers fire only while the invocation is idle (no
|
|
714
|
+
* effect in flight), in due order, so they never race real I/O.
|
|
715
|
+
*/
|
|
716
|
+
/** 2026-01-01T00:00:00.000Z. Every run starts here. */
|
|
717
|
+
const virtualEpoch = Date.UTC(2026, 0, 1);
|
|
718
|
+
const realSetTimeout = globalThis.setTimeout.bind(globalThis);
|
|
719
|
+
const realSetInterval = globalThis.setInterval.bind(globalThis);
|
|
720
|
+
const realClearTimeout = globalThis.clearTimeout.bind(globalThis);
|
|
721
|
+
const realClearInterval = globalThis.clearInterval.bind(globalThis);
|
|
722
|
+
/**
|
|
723
|
+
* Tells library code apart from handler code while an effect's real I/O runs.
|
|
724
|
+
* SDKs back off and time out with timers, which must be real; a handler timer
|
|
725
|
+
* scheduled meanwhile must stay virtual. Node's AsyncLocalStorage follows the
|
|
726
|
+
* library's promise chains and I/O callbacks but not the handler's own
|
|
727
|
+
* continuations. Where it is unavailable (workerd without Node compatibility)
|
|
728
|
+
* every timer stays virtual; the Cloudflare bindings do not use timers.
|
|
729
|
+
*/
|
|
730
|
+
const libraryScope = asyncScope();
|
|
731
|
+
var VirtualClock = class {
|
|
732
|
+
time = virtualEpoch;
|
|
733
|
+
timers = [];
|
|
734
|
+
nextId = 1;
|
|
735
|
+
/** The invocation whose code is running; timers scheduled now belong to it. */
|
|
736
|
+
owner = null;
|
|
737
|
+
/** Set by a concurrent run: who is running, asked when a timer is scheduled (overrides `owner`). */
|
|
738
|
+
ownerNow = null;
|
|
739
|
+
/** Set by a concurrent run: binds a callback to the async context it was scheduled in. */
|
|
740
|
+
bind = null;
|
|
741
|
+
now() {
|
|
742
|
+
return this.time;
|
|
743
|
+
}
|
|
744
|
+
advance(ms) {
|
|
745
|
+
if (ms > 0) this.time += ms;
|
|
746
|
+
}
|
|
747
|
+
schedule(callback, delay, args, interval) {
|
|
748
|
+
const ms = Number.isFinite(delay) && delay > 0 ? Math.floor(delay) : 0;
|
|
749
|
+
const timer = {
|
|
750
|
+
id: this.nextId++,
|
|
751
|
+
due: this.time + ms,
|
|
752
|
+
callback: this.bind ? this.bind(callback) : callback,
|
|
753
|
+
args,
|
|
754
|
+
interval,
|
|
755
|
+
owner: this.ownerNow ? this.ownerNow() : this.owner
|
|
756
|
+
};
|
|
757
|
+
this.timers.push(timer);
|
|
758
|
+
return timer.id;
|
|
759
|
+
}
|
|
760
|
+
setTimeout(callback, delay = 0, ...args) {
|
|
761
|
+
return this.schedule(callback, delay, args, null);
|
|
762
|
+
}
|
|
763
|
+
setInterval(callback, delay = 0, ...args) {
|
|
764
|
+
return this.schedule(callback, delay, args, Math.max(1, Math.floor(delay)));
|
|
765
|
+
}
|
|
766
|
+
clear(id) {
|
|
767
|
+
this.timers = this.timers.filter((t) => t.id !== id);
|
|
768
|
+
}
|
|
769
|
+
/** Whether this clock issued the handle (and the timer is still pending). */
|
|
770
|
+
owns(id) {
|
|
771
|
+
return typeof id === "number" && this.timers.some((t) => t.id === id);
|
|
772
|
+
}
|
|
773
|
+
pendingTimers() {
|
|
774
|
+
return this.timers.length;
|
|
775
|
+
}
|
|
776
|
+
/** Drop every timer an invocation scheduled: a crashed invocation's code must never run again. */
|
|
777
|
+
cancelOwner(owner) {
|
|
778
|
+
this.timers = this.timers.filter((t) => t.owner !== owner);
|
|
779
|
+
}
|
|
780
|
+
earliest() {
|
|
781
|
+
let earliest = this.timers[0];
|
|
782
|
+
for (const t of this.timers) if (earliest && (t.due < earliest.due || t.due === earliest.due && t.id < earliest.id)) earliest = t;
|
|
783
|
+
return earliest;
|
|
784
|
+
}
|
|
785
|
+
/** When the next timer is due, or undefined when none is pending. */
|
|
786
|
+
nextDue() {
|
|
787
|
+
return this.earliest()?.due;
|
|
788
|
+
}
|
|
789
|
+
/** Who set the timer `fireNext` would run: an invocation, null for none, undefined when no timer is pending. */
|
|
790
|
+
nextOwner() {
|
|
791
|
+
return this.earliest()?.owner;
|
|
792
|
+
}
|
|
793
|
+
/** Advance to the earliest due timer and run it. False when none is pending. */
|
|
794
|
+
fireNext() {
|
|
795
|
+
const earliest = this.earliest();
|
|
796
|
+
if (!earliest) return false;
|
|
797
|
+
if (earliest.due > this.time) this.time = earliest.due;
|
|
798
|
+
if (earliest.interval === null) this.timers = this.timers.filter((t) => t !== earliest);
|
|
799
|
+
else earliest.due = this.time + earliest.interval;
|
|
800
|
+
try {
|
|
801
|
+
earliest.callback(...earliest.args);
|
|
802
|
+
} catch {}
|
|
803
|
+
return true;
|
|
804
|
+
}
|
|
805
|
+
};
|
|
806
|
+
/** Deterministic randomness for a run: Math.random, UUIDs and random bytes from one seeded stream. */
|
|
807
|
+
var VirtualRandom = class {
|
|
808
|
+
state;
|
|
809
|
+
constructor(seed) {
|
|
810
|
+
this.state = seedPrng(`random:${seed}`);
|
|
811
|
+
}
|
|
812
|
+
float() {
|
|
813
|
+
const [f, next] = nextFloat(this.state);
|
|
814
|
+
this.state = next;
|
|
815
|
+
return f;
|
|
816
|
+
}
|
|
817
|
+
u32() {
|
|
818
|
+
const [u, next] = nextU32(this.state);
|
|
819
|
+
this.state = next;
|
|
820
|
+
return u;
|
|
821
|
+
}
|
|
822
|
+
fill(view) {
|
|
823
|
+
const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
|
|
824
|
+
for (let i = 0; i < bytes.length; i += 4) {
|
|
825
|
+
const u = this.u32();
|
|
826
|
+
for (let j = 0; j < 4 && i + j < bytes.length; j++) bytes[i + j] = u >>> 8 * j & 255;
|
|
827
|
+
}
|
|
828
|
+
return view;
|
|
829
|
+
}
|
|
830
|
+
/** A version-4 UUID from the stream. */
|
|
831
|
+
uuid() {
|
|
832
|
+
const b = this.fill(/* @__PURE__ */ new Uint8Array(16));
|
|
833
|
+
b[6] = b[6] & 15 | 64;
|
|
834
|
+
b[8] = b[8] & 63 | 128;
|
|
835
|
+
const hex = [...b].map((x) => x.toString(16).padStart(2, "0")).join("");
|
|
836
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
837
|
+
}
|
|
838
|
+
};
|
|
839
|
+
/** Web Crypto's asynchronous methods: real work that always finishes on its own. */
|
|
840
|
+
const subtleMethods = [
|
|
841
|
+
"encrypt",
|
|
842
|
+
"decrypt",
|
|
843
|
+
"sign",
|
|
844
|
+
"verify",
|
|
845
|
+
"digest",
|
|
846
|
+
"generateKey",
|
|
847
|
+
"deriveKey",
|
|
848
|
+
"deriveBits",
|
|
849
|
+
"importKey",
|
|
850
|
+
"exportKey",
|
|
851
|
+
"wrapKey",
|
|
852
|
+
"unwrapKey"
|
|
853
|
+
];
|
|
854
|
+
/** Replace the nondeterministic globals for one run. Returns the handle that restores them. */
|
|
855
|
+
function patchGlobals(seed, options = {}) {
|
|
856
|
+
const clock = new VirtualClock();
|
|
857
|
+
const random = new VirtualRandom(seed);
|
|
858
|
+
const reads = { count: 0 };
|
|
859
|
+
const inLibrary = () => libraryScope?.getStore() === true;
|
|
860
|
+
/** Counts a read of the shared virtual state, an effect's own I/O included: its result may depend on it. */
|
|
861
|
+
const read = () => {
|
|
862
|
+
reads.count++;
|
|
863
|
+
};
|
|
864
|
+
const g = globalThis;
|
|
865
|
+
const undo = [];
|
|
866
|
+
const define = (target, key, value) => {
|
|
867
|
+
undo.push(patchProperty(target, key, { value }));
|
|
868
|
+
};
|
|
869
|
+
const RealDate = Date;
|
|
870
|
+
const VirtualDate = function(...args) {
|
|
871
|
+
if (new.target === void 0 || args.length === 0) read();
|
|
872
|
+
if (new.target === void 0) return new RealDate(clock.now()).toString();
|
|
873
|
+
return Reflect.construct(RealDate, args.length === 0 ? [clock.now()] : args, new.target);
|
|
874
|
+
};
|
|
875
|
+
Object.setPrototypeOf(VirtualDate, RealDate);
|
|
876
|
+
Object.defineProperty(VirtualDate, "prototype", {
|
|
877
|
+
value: RealDate.prototype,
|
|
878
|
+
writable: false
|
|
879
|
+
});
|
|
880
|
+
Object.defineProperty(VirtualDate, "now", {
|
|
881
|
+
value: () => {
|
|
882
|
+
read();
|
|
883
|
+
return clock.now();
|
|
884
|
+
},
|
|
885
|
+
configurable: true,
|
|
886
|
+
writable: true
|
|
887
|
+
});
|
|
888
|
+
Object.defineProperty(VirtualDate, "name", { value: "Date" });
|
|
889
|
+
define(g, "Date", VirtualDate);
|
|
890
|
+
define(Math, "random", () => {
|
|
891
|
+
read();
|
|
892
|
+
return random.float();
|
|
893
|
+
});
|
|
894
|
+
define(g, "setTimeout", (cb, ms, ...args) => {
|
|
895
|
+
if (inLibrary()) return realSetTimeout(cb, ms, ...args);
|
|
896
|
+
read();
|
|
897
|
+
return clock.setTimeout(cb, ms, ...args);
|
|
898
|
+
});
|
|
899
|
+
define(g, "setInterval", (cb, ms, ...args) => {
|
|
900
|
+
if (inLibrary()) return realSetInterval(cb, ms, ...args);
|
|
901
|
+
read();
|
|
902
|
+
return clock.setInterval(cb, ms, ...args);
|
|
903
|
+
});
|
|
904
|
+
define(g, "clearTimeout", (id) => {
|
|
905
|
+
if (clock.owns(id)) clock.clear(id);
|
|
906
|
+
else realClearTimeout(id);
|
|
907
|
+
});
|
|
908
|
+
define(g, "clearInterval", (id) => {
|
|
909
|
+
if (clock.owns(id)) clock.clear(id);
|
|
910
|
+
else realClearInterval(id);
|
|
911
|
+
});
|
|
912
|
+
const perf = g["performance"];
|
|
913
|
+
if (perf && typeof perf === "object") define(perf, "now", () => {
|
|
914
|
+
read();
|
|
915
|
+
return clock.now() - virtualEpoch;
|
|
916
|
+
});
|
|
917
|
+
const cryptoObj = g["crypto"];
|
|
918
|
+
if (cryptoObj && typeof cryptoObj === "object") {
|
|
919
|
+
define(cryptoObj, "randomUUID", () => {
|
|
920
|
+
read();
|
|
921
|
+
return random.uuid();
|
|
922
|
+
});
|
|
923
|
+
define(cryptoObj, "getRandomValues", (view) => {
|
|
924
|
+
read();
|
|
925
|
+
return random.fill(view);
|
|
926
|
+
});
|
|
927
|
+
const subtle = cryptoObj.subtle;
|
|
928
|
+
const trackIo = options.trackIo;
|
|
929
|
+
if (trackIo && subtle && typeof subtle === "object") for (const name of subtleMethods) {
|
|
930
|
+
const real = subtle[name];
|
|
931
|
+
if (typeof real !== "function") continue;
|
|
932
|
+
define(subtle, name, function(...args) {
|
|
933
|
+
return trackIo(Promise.resolve(real.apply(this, args)));
|
|
934
|
+
});
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
let restored = false;
|
|
938
|
+
return {
|
|
939
|
+
clock,
|
|
940
|
+
random,
|
|
941
|
+
reads,
|
|
942
|
+
libraryIo(perform) {
|
|
943
|
+
return libraryScope ? libraryScope.run(true, perform) : perform();
|
|
944
|
+
},
|
|
945
|
+
restore() {
|
|
946
|
+
if (restored) return;
|
|
947
|
+
restored = true;
|
|
948
|
+
for (const u of undo.reverse()) u();
|
|
949
|
+
}
|
|
950
|
+
};
|
|
951
|
+
}
|
|
952
|
+
/** The longest timeout hosts accept: 2^31 - 1 ms. */
|
|
953
|
+
const maxTimeoutMs = 2 ** 31 - 1;
|
|
954
|
+
/** A real-time deadline: `expired` resolves after `ms` unless cancelled first. */
|
|
955
|
+
function realDeadline(ms) {
|
|
956
|
+
let handle;
|
|
957
|
+
return {
|
|
958
|
+
expired: new Promise((resolve) => {
|
|
959
|
+
handle = realSetTimeout(() => resolve("expired"), Math.min(ms, maxTimeoutMs));
|
|
960
|
+
}),
|
|
961
|
+
cancel: () => realClearTimeout(handle)
|
|
962
|
+
};
|
|
963
|
+
}
|
|
964
|
+
/** Yield to the real event loop so microtasks and pending I/O can make progress. */
|
|
965
|
+
function realTick() {
|
|
966
|
+
return new Promise((resolve) => realSetTimeout(() => resolve(), 0));
|
|
967
|
+
}
|
|
968
|
+
const realSetImmediate = globalThis.setImmediate?.bind(globalThis);
|
|
969
|
+
/**
|
|
970
|
+
* Let every pending microtask run, and I/O callbacks that are already due:
|
|
971
|
+
* one turn of the real event loop without a timer's delay where the host has
|
|
972
|
+
* `setImmediate`, else a zero timer.
|
|
973
|
+
*/
|
|
974
|
+
function drainMicrotasks() {
|
|
975
|
+
return realSetImmediate ? new Promise((resolve) => realSetImmediate(() => resolve())) : realTick();
|
|
976
|
+
}
|
|
977
|
+
/**
|
|
978
|
+
* Wait for a promise under the virtual clock: while it is pending, let real
|
|
979
|
+
* I/O complete, and when the invocation is idle fire the next due timer.
|
|
980
|
+
*/
|
|
981
|
+
async function settleOn(promise, ctx) {
|
|
982
|
+
let done = false;
|
|
983
|
+
let failed = false;
|
|
984
|
+
let value;
|
|
985
|
+
let error;
|
|
986
|
+
const tracked = promise.then((v) => {
|
|
987
|
+
done = true;
|
|
988
|
+
value = v;
|
|
989
|
+
}, (e) => {
|
|
990
|
+
done = true;
|
|
991
|
+
failed = true;
|
|
992
|
+
error = e;
|
|
993
|
+
});
|
|
994
|
+
for (;;) {
|
|
995
|
+
await Promise.race([tracked, realTick()]);
|
|
996
|
+
if (done) {
|
|
997
|
+
if (failed) throw error;
|
|
998
|
+
return value;
|
|
999
|
+
}
|
|
1000
|
+
if (ctx.crashed()) return new Promise(() => {});
|
|
1001
|
+
if (ctx.inFlight() > 0) continue;
|
|
1002
|
+
if (ctx.clock.fireNext()) continue;
|
|
1003
|
+
ctx.stuck();
|
|
1004
|
+
return new Promise(() => {});
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
// packages/engine/src/exhaustive.ts
|
|
1008
|
+
/** Whether two turns commute: different invocations, effects on different targets. */
|
|
1009
|
+
function independent(a, b) {
|
|
1010
|
+
return a.invocation !== void 0 && b.invocation !== void 0 && a.invocation !== b.invocation && a.target !== void 0 && b.target !== void 0 && a.target !== b.target;
|
|
1011
|
+
}
|
|
1012
|
+
const asleep = /* @__PURE__ */ new Map();
|
|
1013
|
+
var Enumerator = class {
|
|
1014
|
+
stack = [];
|
|
1015
|
+
depth = 0;
|
|
1016
|
+
/** The depth of the first node in the run just made whose every option was asleep, or null. */
|
|
1017
|
+
blockedAt = null;
|
|
1018
|
+
mismatchReason = null;
|
|
1019
|
+
reduction;
|
|
1020
|
+
constructor(options) {
|
|
1021
|
+
this.reduction = options.reduction;
|
|
1022
|
+
}
|
|
1023
|
+
/** Whether the run just made repeats an explored order (every option at some point was asleep). */
|
|
1024
|
+
get blocked() {
|
|
1025
|
+
return this.blockedAt !== null;
|
|
1026
|
+
}
|
|
1027
|
+
/** Set when a run made different choices than the same prefix did before: not deterministic. */
|
|
1028
|
+
get mismatch() {
|
|
1029
|
+
return this.mismatchReason;
|
|
1030
|
+
}
|
|
1031
|
+
/** The chooser for the next run: the explored prefix, then the first option not asleep. */
|
|
1032
|
+
next() {
|
|
1033
|
+
this.depth = 0;
|
|
1034
|
+
this.blockedAt = null;
|
|
1035
|
+
return { choose: (kind, options) => this.choose(kind, options) };
|
|
1036
|
+
}
|
|
1037
|
+
choose(kind, options) {
|
|
1038
|
+
const i = this.depth++;
|
|
1039
|
+
const known = this.stack[i];
|
|
1040
|
+
if (known) {
|
|
1041
|
+
if (!(known.kind === kind && known.options.length === options.length && known.options.every((o, j) => o.label === options[j]?.label)) && this.mismatchReason === null) this.mismatchReason = `choice ${i} differed between runs with the same earlier choices (${known.options.map((o) => o.label).join(", ")} then ${options.map((o) => o.label).join(", ")})`;
|
|
1042
|
+
return known.picked < options.length ? known.picked : 0;
|
|
1043
|
+
}
|
|
1044
|
+
if (this.blockedAt !== null) return 0;
|
|
1045
|
+
const sleep = this.sleepAt(i);
|
|
1046
|
+
let picked = kind === "turn" ? options.findIndex((o) => !sleep.has(o.label)) : 0;
|
|
1047
|
+
if (picked < 0) {
|
|
1048
|
+
this.blockedAt = i;
|
|
1049
|
+
picked = 0;
|
|
1050
|
+
}
|
|
1051
|
+
this.stack.push({
|
|
1052
|
+
kind,
|
|
1053
|
+
options,
|
|
1054
|
+
picked,
|
|
1055
|
+
done: [],
|
|
1056
|
+
sleep
|
|
1057
|
+
});
|
|
1058
|
+
return picked;
|
|
1059
|
+
}
|
|
1060
|
+
/** The sleep set of a new node at depth i, from its parent's. */
|
|
1061
|
+
sleepAt(i) {
|
|
1062
|
+
const parent = this.stack[i - 1];
|
|
1063
|
+
if (!this.reduction || !parent) return asleep;
|
|
1064
|
+
if (parent.kind === "fault") return parent.sleep;
|
|
1065
|
+
const taken = parent.options[parent.picked];
|
|
1066
|
+
if (!taken) return asleep;
|
|
1067
|
+
const sleep = /* @__PURE__ */ new Map();
|
|
1068
|
+
const candidates = [...parent.sleep.values(), ...parent.done.map((j) => parent.options[j])];
|
|
1069
|
+
for (const c of candidates) if (c && independent(c, taken)) sleep.set(c.label, c);
|
|
1070
|
+
return sleep;
|
|
1071
|
+
}
|
|
1072
|
+
/** Move to the next schedule after a run. False once every schedule has been explored. */
|
|
1073
|
+
advance() {
|
|
1074
|
+
this.stack.length = Math.min(this.stack.length, this.depth, (this.blockedAt ?? Infinity) + 1);
|
|
1075
|
+
while (this.stack.length > 0) {
|
|
1076
|
+
const node = this.stack[this.stack.length - 1];
|
|
1077
|
+
if (!node.done.includes(node.picked)) node.done.push(node.picked);
|
|
1078
|
+
const next = node.options.findIndex((o, j) => !node.done.includes(j) && (node.kind === "fault" || !node.sleep.has(o.label)));
|
|
1079
|
+
if (next >= 0) {
|
|
1080
|
+
node.picked = next;
|
|
1081
|
+
return true;
|
|
1082
|
+
}
|
|
1083
|
+
this.stack.pop();
|
|
1084
|
+
}
|
|
1085
|
+
return false;
|
|
1086
|
+
}
|
|
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
|
+
};
|
|
1146
|
+
// packages/engine/src/fetch.ts
|
|
1147
|
+
const FAULTS = [
|
|
1148
|
+
"crash_before",
|
|
1149
|
+
"crash_after",
|
|
1150
|
+
"ambiguous",
|
|
1151
|
+
"error"
|
|
1152
|
+
];
|
|
1153
|
+
/** Match a host against an exact host or a "*.suffix" pattern. */
|
|
1154
|
+
function hostMatches(pattern, host) {
|
|
1155
|
+
if (pattern.startsWith("*.")) {
|
|
1156
|
+
const suffix = pattern.slice(1);
|
|
1157
|
+
return host.endsWith(suffix) && host.length > suffix.length;
|
|
1158
|
+
}
|
|
1159
|
+
return pattern === host;
|
|
1160
|
+
}
|
|
1161
|
+
function findExternal(externals, host) {
|
|
1162
|
+
return externals.find((e) => hostMatches(e.host, host));
|
|
1163
|
+
}
|
|
1164
|
+
function findResponse(external, method, path) {
|
|
1165
|
+
if (!external.responses) return null;
|
|
1166
|
+
return external.responses.find((r) => {
|
|
1167
|
+
if (r.method && r.method.toUpperCase() !== method) return false;
|
|
1168
|
+
if (r.path === void 0) return true;
|
|
1169
|
+
return r.path.endsWith("*") ? path.startsWith(r.path.slice(0, -1)) : r.path === path;
|
|
1170
|
+
});
|
|
1171
|
+
}
|
|
1172
|
+
const REDIRECTS = /* @__PURE__ */ new Set([
|
|
1173
|
+
301,
|
|
1174
|
+
302,
|
|
1175
|
+
303,
|
|
1176
|
+
307,
|
|
1177
|
+
308
|
|
1178
|
+
]);
|
|
1179
|
+
function replyOf(r) {
|
|
1180
|
+
if (r === null) return {
|
|
1181
|
+
status: 200,
|
|
1182
|
+
headers: {},
|
|
1183
|
+
body: ""
|
|
1184
|
+
};
|
|
1185
|
+
const json = r.body !== void 0 && typeof r.body !== "string";
|
|
1186
|
+
const headers = {};
|
|
1187
|
+
for (const [name, value] of Object.entries(r.headers ?? {})) headers[name.toLowerCase()] = value;
|
|
1188
|
+
if (json && !("content-type" in headers)) headers["content-type"] = "application/json";
|
|
1189
|
+
const body = r.body === void 0 ? "" : json ? JSON.stringify(r.body) : r.body;
|
|
1190
|
+
return {
|
|
1191
|
+
status: r.status,
|
|
1192
|
+
headers,
|
|
1193
|
+
body
|
|
1194
|
+
};
|
|
1195
|
+
}
|
|
1196
|
+
function toResponse(reply) {
|
|
1197
|
+
return new Response(reply.body === "" ? null : reply.body, {
|
|
1198
|
+
status: reply.status,
|
|
1199
|
+
headers: reply.headers
|
|
1200
|
+
});
|
|
1201
|
+
}
|
|
1202
|
+
function parseBody(text) {
|
|
1203
|
+
if (text === "") return null;
|
|
1204
|
+
try {
|
|
1205
|
+
return JSON.parse(text);
|
|
1206
|
+
} catch {
|
|
1207
|
+
return text;
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
/**
|
|
1211
|
+
* Build the replacement `fetch`. With `hooks`, every request is an effect
|
|
1212
|
+
* point recorded as `Fetch:<external>` with the method as op; the result
|
|
1213
|
+
* summary carries `status`, `effective` and the dedupe key.
|
|
1214
|
+
*/
|
|
1215
|
+
function createScriptedFetch(externals, hooks, unsupported, afterRequest = () => {}) {
|
|
1216
|
+
const dedupe = /* @__PURE__ */ new Map();
|
|
1217
|
+
const scripted = (async (input, init) => {
|
|
1218
|
+
const request = new Request(input, init);
|
|
1219
|
+
const url = new URL(request.url);
|
|
1220
|
+
const method = request.method.toUpperCase();
|
|
1221
|
+
const external = findExternal(externals, url.host);
|
|
1222
|
+
if (!external) {
|
|
1223
|
+
unsupported(`fetch to undeclared host ${url.host}; declare it as an external in the scenario`);
|
|
1224
|
+
throw new TypeError(`fetch failed: ${url.host} is not a declared external`);
|
|
1225
|
+
}
|
|
1226
|
+
const headers = {};
|
|
1227
|
+
request.headers.forEach((value, name) => {
|
|
1228
|
+
headers[name.toLowerCase()] = value;
|
|
1229
|
+
});
|
|
1230
|
+
const dedupeHeader = external.guarantees.dedupeBy?.toLowerCase();
|
|
1231
|
+
const dedupeKey = dedupeHeader ? headers[dedupeHeader] ?? null : null;
|
|
1232
|
+
const body = parseBody(await request.text());
|
|
1233
|
+
const args = {
|
|
1234
|
+
url: request.url,
|
|
1235
|
+
method,
|
|
1236
|
+
headers,
|
|
1237
|
+
body,
|
|
1238
|
+
dedupeKey
|
|
1239
|
+
};
|
|
1240
|
+
const perform = async () => {
|
|
1241
|
+
const memo = dedupeKey === null ? null : `${external.name}\u0000${dedupeKey}`;
|
|
1242
|
+
if (memo !== null) {
|
|
1243
|
+
const earlier = dedupe.get(memo);
|
|
1244
|
+
if (earlier) return {
|
|
1245
|
+
reply: earlier,
|
|
1246
|
+
effective: false
|
|
1247
|
+
};
|
|
1248
|
+
}
|
|
1249
|
+
const script = findResponse(external, method, url.pathname);
|
|
1250
|
+
if (script === void 0) {
|
|
1251
|
+
unsupported(`no scripted response in external ${external.name} for ${method} ${url.pathname}`);
|
|
1252
|
+
throw new TypeError(`fetch failed: no scripted response for ${method} ${url.pathname}`);
|
|
1253
|
+
}
|
|
1254
|
+
const reply = replyOf(script);
|
|
1255
|
+
if (REDIRECTS.has(reply.status) && request.redirect !== "manual") {
|
|
1256
|
+
unsupported(`external ${external.name} answers ${method} ${url.pathname} with a ${reply.status} redirect; script the final reply or fetch with redirect: "manual"`);
|
|
1257
|
+
throw new TypeError(`fetch failed: redirects are not modelled (${reply.status} from ${url.host})`);
|
|
1258
|
+
}
|
|
1259
|
+
if (memo !== null) dedupe.set(memo, reply);
|
|
1260
|
+
return {
|
|
1261
|
+
reply,
|
|
1262
|
+
effective: true
|
|
1263
|
+
};
|
|
1264
|
+
};
|
|
1265
|
+
if (!hooks) {
|
|
1266
|
+
const { reply } = await perform();
|
|
1267
|
+
afterRequest();
|
|
1268
|
+
return toResponse(reply);
|
|
1269
|
+
}
|
|
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;
|
|
1583
|
+
}
|
|
1584
|
+
};
|
|
1585
|
+
// packages/engine/src/run.ts
|
|
1586
|
+
/**
|
|
1587
|
+
* One run of a scenario: the effect log being built, the fault decisions
|
|
1588
|
+
* (drawn during exploration, looked up during replay), and the invocations
|
|
1589
|
+
* in flight. Proxies in the platform package call `effect`/`effectSync`
|
|
1590
|
+
* around every real effect; everything else is engine-internal.
|
|
1591
|
+
*
|
|
1592
|
+
* With `maxConcurrentInvocations` above 1 the run is concurrent: several
|
|
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.
|
|
1598
|
+
*/
|
|
1599
|
+
/** Thrown into user code by a synchronous effect that crashes the invocation. */
|
|
1600
|
+
var CrashSignal = class extends Error {
|
|
1601
|
+
name = "CrashSignal";
|
|
1602
|
+
invocation;
|
|
1603
|
+
constructor(invocation) {
|
|
1604
|
+
super(`invocation ${invocation} crashed by an injected fault`);
|
|
1605
|
+
this.invocation = invocation;
|
|
1606
|
+
}
|
|
1607
|
+
};
|
|
1608
|
+
/** The error user code sees for an injected `error` or `ambiguous` fault. */
|
|
1609
|
+
var InjectedEffectError = class extends Error {
|
|
1610
|
+
name = "InjectedEffectError";
|
|
1611
|
+
point;
|
|
1612
|
+
fault;
|
|
1613
|
+
constructor(point, fault) {
|
|
1614
|
+
super(`${point.target} ${point.op} failed (injected ${fault})`);
|
|
1615
|
+
this.point = point;
|
|
1616
|
+
this.fault = fault;
|
|
1617
|
+
}
|
|
1618
|
+
};
|
|
1619
|
+
var InvocationState = class {
|
|
1620
|
+
crashed;
|
|
1621
|
+
onCrash;
|
|
1622
|
+
/** Effect points seen so far in this invocation; the next effect's ordinal. */
|
|
1623
|
+
ordinal = 0;
|
|
1624
|
+
/** Times this invocation has parked for a turn; names its next turn the same in every run. */
|
|
1625
|
+
parks = 0;
|
|
1626
|
+
crashedFlag = false;
|
|
1627
|
+
resolveCrashed = () => {};
|
|
1628
|
+
id;
|
|
1629
|
+
constructor(id, onCrash) {
|
|
1630
|
+
this.id = id;
|
|
1631
|
+
this.onCrash = onCrash;
|
|
1632
|
+
this.crashed = new Promise((resolve) => {
|
|
1633
|
+
this.resolveCrashed = resolve;
|
|
1634
|
+
});
|
|
1635
|
+
}
|
|
1636
|
+
isCrashed() {
|
|
1637
|
+
return this.crashedFlag;
|
|
1638
|
+
}
|
|
1639
|
+
crash() {
|
|
1640
|
+
if (this.crashedFlag) return;
|
|
1641
|
+
this.crashedFlag = true;
|
|
1642
|
+
this.onCrash();
|
|
1643
|
+
this.resolveCrashed();
|
|
1644
|
+
}
|
|
1645
|
+
};
|
|
1646
|
+
const deliveryScope = asyncScope();
|
|
1647
|
+
/** The run whose globals are installed, if any: where code observed from outside records into. */
|
|
1648
|
+
let installed = null;
|
|
1649
|
+
function installedRun() {
|
|
1650
|
+
return installed;
|
|
1651
|
+
}
|
|
1652
|
+
/** Whether this host can run concurrent invocations: attribution needs async context. */
|
|
1653
|
+
const concurrencySupported = deliveryScope !== null;
|
|
1654
|
+
/** A promise that never settles: how an abandoned invocation experiences a crash. */
|
|
1655
|
+
function hang() {
|
|
1656
|
+
return new Promise(() => {});
|
|
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";
|
|
1664
|
+
var Run = class {
|
|
1665
|
+
logState = emptyLog;
|
|
1666
|
+
faults = [];
|
|
1667
|
+
effectIndex = 0;
|
|
1668
|
+
eligibleSeen = 0;
|
|
1669
|
+
prng;
|
|
1670
|
+
invocations = /* @__PURE__ */ new Map();
|
|
1671
|
+
reasons = [];
|
|
1672
|
+
frames = new Frames();
|
|
1673
|
+
patched = null;
|
|
1674
|
+
restoreFetch = null;
|
|
1675
|
+
/** The invocation whose code is running (one at a time); outbound fetches are attributed to it. */
|
|
1676
|
+
current = "";
|
|
1677
|
+
/** Events a platform queued during a delivery, for the run loop to pick up. */
|
|
1678
|
+
queued = [];
|
|
1679
|
+
/** Concurrent runs only: the scheduler of turns. */
|
|
1680
|
+
turns;
|
|
1681
|
+
/** Whether several invocations may be in flight (`maxConcurrentInvocations` above 1). */
|
|
1682
|
+
concurrent;
|
|
1683
|
+
options;
|
|
1684
|
+
constructor(options) {
|
|
1685
|
+
this.options = options;
|
|
1686
|
+
this.prng = seedPrng(options.schedule.seed);
|
|
1687
|
+
this.turns = new Turns(options, this.frames, (id) => this.runAs(id), () => this.patched?.reads);
|
|
1688
|
+
this.concurrent = options.bounds.maxConcurrentInvocations > 1;
|
|
1689
|
+
}
|
|
1690
|
+
get log() {
|
|
1691
|
+
return this.logState;
|
|
1692
|
+
}
|
|
1693
|
+
/** The schedule as actually executed: input decisions during replay, drawn ones during exploration. */
|
|
1694
|
+
get schedule() {
|
|
1695
|
+
const recorded = this.options.chooser !== void 0 || this.options.schedule.turns !== void 0;
|
|
1696
|
+
return {
|
|
1697
|
+
seed: this.options.schedule.seed,
|
|
1698
|
+
faults: [...this.faults],
|
|
1699
|
+
...recorded ? { turns: [...this.turns.picks] } : {}
|
|
1700
|
+
};
|
|
1701
|
+
}
|
|
1702
|
+
get effectPoints() {
|
|
1703
|
+
return this.effectIndex;
|
|
1704
|
+
}
|
|
1705
|
+
get faultsInjected() {
|
|
1706
|
+
return this.faults.length;
|
|
1707
|
+
}
|
|
1708
|
+
/**
|
|
1709
|
+
* Whether a turn other than an event's start did more than its own effect:
|
|
1710
|
+
* performed an effect on another target (synchronous, or nested in it),
|
|
1711
|
+
* queued events, or read virtual time or randomness (effects advance the clock and draws the
|
|
1712
|
+
* stream). Turns told apart by their parked effects' targets need not
|
|
1713
|
+
* commute then. A start is ordered against every turn anyway, so what it
|
|
1714
|
+
* does does not count.
|
|
1715
|
+
*/
|
|
1716
|
+
get turnsMayNotCommute() {
|
|
1717
|
+
return this.turns.mayNotCommute;
|
|
1718
|
+
}
|
|
1719
|
+
/**
|
|
1720
|
+
* Concurrent runs: events were queued since the last decision (follow-ups
|
|
1721
|
+
* of a delivery that ended, or `enqueue`). The queue's order is shared, so
|
|
1722
|
+
* within a turn this is another dependence.
|
|
1723
|
+
*/
|
|
1724
|
+
queuedEvents() {
|
|
1725
|
+
this.turns.queuedEvents();
|
|
1726
|
+
}
|
|
1727
|
+
get unsupportedReasons() {
|
|
1728
|
+
return this.reasons;
|
|
1729
|
+
}
|
|
1730
|
+
/** Replace the nondeterministic globals and `fetch` for this run. Call `uninstall` in a finally. */
|
|
1731
|
+
install(externals = []) {
|
|
1732
|
+
installed = this;
|
|
1733
|
+
if (!this.patched) {
|
|
1734
|
+
this.patched = patchGlobals(this.options.schedule.seed, { trackIo: (work) => {
|
|
1735
|
+
this.frames.inFlight++;
|
|
1736
|
+
return work.finally(() => {
|
|
1737
|
+
this.frames.inFlight--;
|
|
1738
|
+
if (this.concurrent) this.progressed();
|
|
1739
|
+
});
|
|
1740
|
+
} });
|
|
1741
|
+
if (this.concurrent) {
|
|
1742
|
+
const clock = this.patched.clock;
|
|
1743
|
+
clock.ownerNow = () => this.running();
|
|
1744
|
+
clock.bind = (callback) => {
|
|
1745
|
+
const cell = deliveryScope?.getStore();
|
|
1746
|
+
if (!cell || !deliveryScope) return callback;
|
|
1747
|
+
const scope = deliveryScope;
|
|
1748
|
+
return (...args) => scope.run(cell, () => callback(...args));
|
|
1749
|
+
};
|
|
1750
|
+
}
|
|
1751
|
+
}
|
|
1752
|
+
if (!this.restoreFetch) this.restoreFetch = installScriptedFetch(externals, {
|
|
1753
|
+
hooks: this,
|
|
1754
|
+
invocation: () => this.running()
|
|
1755
|
+
}, (reason) => this.unsupported(reason));
|
|
1756
|
+
}
|
|
1757
|
+
uninstall() {
|
|
1758
|
+
if (installed === this) installed = null;
|
|
1759
|
+
this.restoreFetch?.();
|
|
1760
|
+
this.restoreFetch = null;
|
|
1761
|
+
this.patched?.restore();
|
|
1762
|
+
this.patched = null;
|
|
1763
|
+
}
|
|
1764
|
+
/** Virtual milliseconds since the epoch, or the real clock when the globals are not installed. */
|
|
1765
|
+
now() {
|
|
1766
|
+
return this.patched ? this.patched.clock.now() : Date.now();
|
|
1767
|
+
}
|
|
1768
|
+
/** Timers scheduled and not yet fired or cancelled (0 when the globals are not installed). */
|
|
1769
|
+
pendingTimers() {
|
|
1770
|
+
return this.patched?.clock.pendingTimers() ?? 0;
|
|
1771
|
+
}
|
|
1772
|
+
startInvocation(id, options = {}) {
|
|
1773
|
+
const inv = this.track(id);
|
|
1774
|
+
if (options.bookkeeping) return inv;
|
|
1775
|
+
if (this.concurrent) {
|
|
1776
|
+
this.turns.started(id);
|
|
1777
|
+
const cell = deliveryScope?.getStore();
|
|
1778
|
+
if (cell && cell.id === null) {
|
|
1779
|
+
cell.id = id;
|
|
1780
|
+
this.runAs(id);
|
|
1781
|
+
}
|
|
1782
|
+
return inv;
|
|
1783
|
+
}
|
|
1784
|
+
this.runAs(id);
|
|
1785
|
+
return inv;
|
|
1786
|
+
}
|
|
1787
|
+
enqueue(event) {
|
|
1788
|
+
this.queued.push(event);
|
|
1789
|
+
if (this.concurrent) this.progressed();
|
|
1790
|
+
}
|
|
1791
|
+
/** Events platforms queued with `enqueue` since the last call. */
|
|
1792
|
+
takeQueued() {
|
|
1793
|
+
const queued = this.queued;
|
|
1794
|
+
this.queued = [];
|
|
1795
|
+
return queued;
|
|
1796
|
+
}
|
|
1797
|
+
running() {
|
|
1798
|
+
if (!this.concurrent) return this.current;
|
|
1799
|
+
return deliveryScope?.getStore()?.id ?? this.current;
|
|
1800
|
+
}
|
|
1801
|
+
runAs(id) {
|
|
1802
|
+
if (this.patched) this.patched.clock.owner = id;
|
|
1803
|
+
if (id !== null) this.current = id;
|
|
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
|
+
}
|
|
1815
|
+
invocation(id) {
|
|
1816
|
+
const inv = this.invocations.get(id);
|
|
1817
|
+
if (!inv) throw new Error(`effect from unknown invocation ${id}`);
|
|
1818
|
+
return inv;
|
|
1819
|
+
}
|
|
1820
|
+
/** Effect points so far that could take a fault (see `RunOptions.faultPlan`). */
|
|
1821
|
+
get eligiblePoints() {
|
|
1822
|
+
return this.eligibleSeen;
|
|
1823
|
+
}
|
|
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
|
+
}
|
|
1834
|
+
const chooser = this.options.chooser;
|
|
1835
|
+
if (chooser && this.options.mode === "explore") {
|
|
1836
|
+
if (point.allowed.length === 0 || this.faults.length >= this.options.bounds.maxFaultsPerRun) return null;
|
|
1837
|
+
const i = chooser.choose("fault", [{ label: "none" }, ...point.allowed.map((f) => ({ label: f }))]);
|
|
1838
|
+
return i === 0 ? null : point.allowed[i - 1] ?? null;
|
|
1839
|
+
}
|
|
1840
|
+
if (this.options.mode === "replay") {
|
|
1841
|
+
const d = this.options.schedule.faults.find((f) => f.invocation === point.invocation && f.ordinal === ordinal);
|
|
1842
|
+
return d && point.allowed.includes(d.fault) ? d.fault : null;
|
|
1843
|
+
}
|
|
1844
|
+
const [fault, next] = decideFault(this.prng, point.allowed, this.faults.length, {
|
|
1845
|
+
maxFaultsPerRun: this.options.bounds.maxFaultsPerRun,
|
|
1846
|
+
faultProbability: this.options.faultProbability
|
|
1847
|
+
});
|
|
1848
|
+
this.prng = next;
|
|
1849
|
+
return fault;
|
|
1850
|
+
}
|
|
1851
|
+
record(point, kind, payload) {
|
|
1852
|
+
if (kind === "result") this.turns.performed(point.target);
|
|
1853
|
+
this.logState = appendEffect(this.logState, {
|
|
1854
|
+
kind,
|
|
1855
|
+
invocation: point.invocation,
|
|
1856
|
+
target: point.target,
|
|
1857
|
+
op: point.op,
|
|
1858
|
+
payload
|
|
1859
|
+
});
|
|
1860
|
+
}
|
|
1861
|
+
/** Open an effect point: record the call and decide the fault. */
|
|
1862
|
+
open(point, inv) {
|
|
1863
|
+
this.effectIndex++;
|
|
1864
|
+
const ordinal = inv.ordinal++;
|
|
1865
|
+
this.record(point, "call", { args: point.args });
|
|
1866
|
+
const fault = this.decide(point, ordinal);
|
|
1867
|
+
if (fault) this.faults.push({
|
|
1868
|
+
invocation: point.invocation,
|
|
1869
|
+
ordinal,
|
|
1870
|
+
fault,
|
|
1871
|
+
target: point.target,
|
|
1872
|
+
op: point.op
|
|
1873
|
+
});
|
|
1874
|
+
return fault;
|
|
1875
|
+
}
|
|
1876
|
+
async effect(point, perform, summarize, options = {}) {
|
|
1877
|
+
const inv = this.invocation(point.invocation);
|
|
1878
|
+
if (inv.isCrashed()) return hang();
|
|
1879
|
+
const enclosing = this.frames.enclosing(point.invocation);
|
|
1880
|
+
const nested = enclosing !== void 0;
|
|
1881
|
+
if (this.concurrent && !nested) {
|
|
1882
|
+
await new Promise((go) => this.turns.park(inv, point.target, go));
|
|
1883
|
+
if (inv.isCrashed()) return hang();
|
|
1884
|
+
} else if (this.concurrent && enclosing?.hosts && enclosing.mayPark()) {
|
|
1885
|
+
const host = enclosing;
|
|
1886
|
+
let released = false;
|
|
1887
|
+
this.frames.adjust(host, () => {
|
|
1888
|
+
host.children++;
|
|
1889
|
+
host.waitingChildren++;
|
|
1890
|
+
});
|
|
1891
|
+
this.turns.park(inv, point.target, () => released = true, host);
|
|
1892
|
+
while (!released && !inv.isCrashed()) await realTick();
|
|
1893
|
+
if (!released) {
|
|
1894
|
+
this.frames.adjust(host, () => {
|
|
1895
|
+
host.children--;
|
|
1896
|
+
host.waitingChildren--;
|
|
1897
|
+
});
|
|
1898
|
+
return hang();
|
|
1899
|
+
}
|
|
1900
|
+
try {
|
|
1901
|
+
return await this.performEffect(point, perform, summarize, options, inv, enclosing, host);
|
|
1902
|
+
} finally {
|
|
1903
|
+
this.frames.adjust(host, () => host.children--);
|
|
1904
|
+
}
|
|
1905
|
+
}
|
|
1906
|
+
return this.performEffect(point, perform, summarize, options, inv, enclosing);
|
|
1907
|
+
}
|
|
1908
|
+
/** The effect once it has its turn: the fault, the perform under its deadline, the record. */
|
|
1909
|
+
async performEffect(point, perform, summarize, options, inv, enclosing, host) {
|
|
1910
|
+
const dead = () => {
|
|
1911
|
+
enclosing?.crash();
|
|
1912
|
+
return hang();
|
|
1913
|
+
};
|
|
1914
|
+
const fault = this.open(point, inv);
|
|
1915
|
+
if (fault === "crash_before" || fault === "cut_off") {
|
|
1916
|
+
this.record(point, "fault", {
|
|
1917
|
+
args: point.args,
|
|
1918
|
+
fault
|
|
1919
|
+
});
|
|
1920
|
+
inv.crash();
|
|
1921
|
+
return dead();
|
|
1922
|
+
}
|
|
1923
|
+
if (fault === "error") {
|
|
1924
|
+
this.record(point, "fault", {
|
|
1925
|
+
args: point.args,
|
|
1926
|
+
fault
|
|
1927
|
+
});
|
|
1928
|
+
throw new InjectedEffectError(point, fault);
|
|
1929
|
+
}
|
|
1930
|
+
let settled;
|
|
1931
|
+
const deadline = realDeadline(this.options.bounds.budgetMs);
|
|
1932
|
+
const frame = new Frame(point.invocation, point.hostsEffects === true, options);
|
|
1933
|
+
frame.parent = host;
|
|
1934
|
+
this.frames.enter(frame);
|
|
1935
|
+
try {
|
|
1936
|
+
const inside = () => effectScope ? effectScope.run(frame, perform) : perform();
|
|
1937
|
+
const io = this.patched ? this.patched.libraryIo(inside) : inside();
|
|
1938
|
+
settled = await Promise.race([
|
|
1939
|
+
io.then((value) => ({
|
|
1940
|
+
ok: true,
|
|
1941
|
+
value
|
|
1942
|
+
}), (error) => ({
|
|
1943
|
+
ok: false,
|
|
1944
|
+
error
|
|
1945
|
+
})),
|
|
1946
|
+
deadline.expired,
|
|
1947
|
+
frame.crashed
|
|
1948
|
+
]);
|
|
1949
|
+
} catch (err) {
|
|
1950
|
+
settled = {
|
|
1951
|
+
ok: false,
|
|
1952
|
+
error: err
|
|
1953
|
+
};
|
|
1954
|
+
} finally {
|
|
1955
|
+
deadline.cancel();
|
|
1956
|
+
this.frames.leave(frame);
|
|
1957
|
+
this.patched?.clock.advance(1);
|
|
1958
|
+
if (this.concurrent) this.progressed();
|
|
1959
|
+
}
|
|
1960
|
+
if (settled === "expired") {
|
|
1961
|
+
this.unsupported(`${point.target} ${point.op} did not complete within ${this.options.bounds.budgetMs} ms of real time`);
|
|
1962
|
+
inv.crash();
|
|
1963
|
+
frame.abandon();
|
|
1964
|
+
return hang();
|
|
1965
|
+
}
|
|
1966
|
+
if (settled === "nested_crash") return dead();
|
|
1967
|
+
if (!settled.ok) {
|
|
1968
|
+
this.record(point, "result", {
|
|
1969
|
+
args: point.args,
|
|
1970
|
+
result: null,
|
|
1971
|
+
error: String(settled.error)
|
|
1972
|
+
});
|
|
1973
|
+
throw settled.error;
|
|
1974
|
+
}
|
|
1975
|
+
const value = settled.value;
|
|
1976
|
+
this.record(point, "result", {
|
|
1977
|
+
args: point.args,
|
|
1978
|
+
result: summarize(value)
|
|
1979
|
+
});
|
|
1980
|
+
if (inv.isCrashed()) return hang();
|
|
1981
|
+
if (fault === "crash_after") {
|
|
1982
|
+
this.record(point, "fault", {
|
|
1983
|
+
args: point.args,
|
|
1984
|
+
fault
|
|
1985
|
+
});
|
|
1986
|
+
inv.crash();
|
|
1987
|
+
return dead();
|
|
1988
|
+
}
|
|
1989
|
+
if (fault === "ambiguous") {
|
|
1990
|
+
this.record(point, "fault", {
|
|
1991
|
+
args: point.args,
|
|
1992
|
+
fault
|
|
1993
|
+
});
|
|
1994
|
+
throw new InjectedEffectError(point, fault);
|
|
1995
|
+
}
|
|
1996
|
+
return value;
|
|
1997
|
+
}
|
|
1998
|
+
effectSync(point, perform, summarize) {
|
|
1999
|
+
const inv = this.invocation(point.invocation);
|
|
2000
|
+
if (inv.isCrashed()) throw new CrashSignal(inv.id);
|
|
2001
|
+
const fault = this.open(point, inv);
|
|
2002
|
+
if (fault === "crash_before" || fault === "cut_off") {
|
|
2003
|
+
this.record(point, "fault", {
|
|
2004
|
+
args: point.args,
|
|
2005
|
+
fault
|
|
2006
|
+
});
|
|
2007
|
+
inv.crash();
|
|
2008
|
+
throw new CrashSignal(inv.id);
|
|
2009
|
+
}
|
|
2010
|
+
if (fault === "error") {
|
|
2011
|
+
this.record(point, "fault", {
|
|
2012
|
+
args: point.args,
|
|
2013
|
+
fault
|
|
2014
|
+
});
|
|
2015
|
+
throw new InjectedEffectError(point, fault);
|
|
2016
|
+
}
|
|
2017
|
+
let value;
|
|
2018
|
+
try {
|
|
2019
|
+
value = perform();
|
|
2020
|
+
} catch (err) {
|
|
2021
|
+
this.record(point, "result", {
|
|
2022
|
+
args: point.args,
|
|
2023
|
+
result: null,
|
|
2024
|
+
error: String(err)
|
|
2025
|
+
});
|
|
2026
|
+
throw err;
|
|
2027
|
+
}
|
|
2028
|
+
this.record(point, "result", {
|
|
2029
|
+
args: point.args,
|
|
2030
|
+
result: summarize(value)
|
|
2031
|
+
});
|
|
2032
|
+
if (fault === "crash_after") {
|
|
2033
|
+
this.record(point, "fault", {
|
|
2034
|
+
args: point.args,
|
|
2035
|
+
fault
|
|
2036
|
+
});
|
|
2037
|
+
inv.crash();
|
|
2038
|
+
throw new CrashSignal(inv.id);
|
|
2039
|
+
}
|
|
2040
|
+
if (fault === "ambiguous") {
|
|
2041
|
+
this.record(point, "fault", {
|
|
2042
|
+
args: point.args,
|
|
2043
|
+
fault
|
|
2044
|
+
});
|
|
2045
|
+
throw new InjectedEffectError(point, fault);
|
|
2046
|
+
}
|
|
2047
|
+
return value;
|
|
2048
|
+
}
|
|
2049
|
+
unsupported(reason) {
|
|
2050
|
+
this.reasons.push(reason);
|
|
2051
|
+
}
|
|
2052
|
+
settle(promise, invocation) {
|
|
2053
|
+
const inv = this.invocation(invocation);
|
|
2054
|
+
if (this.concurrent) return Promise.race([promise, inv.crashed.then(() => hang())]);
|
|
2055
|
+
const patched = this.patched;
|
|
2056
|
+
if (patched) patched.clock.owner = invocation;
|
|
2057
|
+
this.current = invocation;
|
|
2058
|
+
if (!patched) return Promise.race([promise, inv.crashed.then(() => hang())]);
|
|
2059
|
+
return settleOn(promise, {
|
|
2060
|
+
clock: patched.clock,
|
|
2061
|
+
inFlight: () => this.frames.inFlight,
|
|
2062
|
+
crashed: () => inv.isCrashed(),
|
|
2063
|
+
stuck: () => {
|
|
2064
|
+
this.unsupported(waitingUnseen(invocation));
|
|
2065
|
+
inv.crash();
|
|
2066
|
+
}
|
|
2067
|
+
});
|
|
2068
|
+
}
|
|
2069
|
+
/** Concurrent runs: start a delivery in its own async context. */
|
|
2070
|
+
startDelivery(deliver) {
|
|
2071
|
+
if (!deliveryScope) throw new Error("concurrent invocations need AsyncLocalStorage");
|
|
2072
|
+
const cell = { id: null };
|
|
2073
|
+
this.runAs(null);
|
|
2074
|
+
return {
|
|
2075
|
+
promise: deliveryScope.run(cell, deliver),
|
|
2076
|
+
invocation: () => cell.id
|
|
2077
|
+
};
|
|
2078
|
+
}
|
|
2079
|
+
/** Concurrent runs: something moved (an invocation parked, a delivery ended, I/O completed). */
|
|
2080
|
+
progressed() {
|
|
2081
|
+
this.turns.progressed();
|
|
2082
|
+
}
|
|
2083
|
+
/**
|
|
2084
|
+
* Concurrent runs: wait until the running invocation has parked, finished
|
|
2085
|
+
* or gone idle. Parking, a delivery ending and I/O completing wake the wait
|
|
2086
|
+
* at once; then every pending microtask runs, so continuations the turn set
|
|
2087
|
+
* off have run too. Code waiting on anything else gets one zero timer, the
|
|
2088
|
+
* same allowance the sequential path gives, before it counts as idle.
|
|
2089
|
+
*/
|
|
2090
|
+
quiesce() {
|
|
2091
|
+
return this.turns.quiesce();
|
|
2092
|
+
}
|
|
2093
|
+
/**
|
|
2094
|
+
* Concurrent runs: pick the next turn among the parked invocations and,
|
|
2095
|
+
* when `canStart`, starting the next event. Parked invocations are ordered
|
|
2096
|
+
* by start, then by when they parked, so the pick does not depend on
|
|
2097
|
+
* real-time arrival. Returns what was picked; "turn" has already released it.
|
|
2098
|
+
*/
|
|
2099
|
+
takeTurn(canStart) {
|
|
2100
|
+
return this.turns.takeTurn(canStart);
|
|
2101
|
+
}
|
|
2102
|
+
/**
|
|
2103
|
+
* Let virtual time pass until `at`: timers due by then fire first, in due
|
|
2104
|
+
* order, as the invocations that set them, each followed by the work it
|
|
2105
|
+
* sets off. No-op when `at` is not ahead.
|
|
2106
|
+
*/
|
|
2107
|
+
async advanceTo(at) {
|
|
2108
|
+
const clock = this.patched?.clock;
|
|
2109
|
+
if (!clock) return;
|
|
2110
|
+
for (let due = clock.nextDue(); due !== void 0 && due <= at; due = clock.nextDue()) {
|
|
2111
|
+
this.runAs(clock.nextOwner() ?? null);
|
|
2112
|
+
clock.fireNext();
|
|
2113
|
+
do
|
|
2114
|
+
await drainMicrotasks();
|
|
2115
|
+
while (this.frames.inFlight > 0);
|
|
2116
|
+
}
|
|
2117
|
+
clock.advance(at - clock.now());
|
|
2118
|
+
}
|
|
2119
|
+
/** When the next virtual timer is due, or undefined when none is pending. */
|
|
2120
|
+
nextTimerDue() {
|
|
2121
|
+
return this.patched?.clock.nextDue();
|
|
2122
|
+
}
|
|
2123
|
+
/** Concurrent runs: fire the next due timer as the invocation that set it. False when none is pending. */
|
|
2124
|
+
fireTimer() {
|
|
2125
|
+
const clock = this.patched?.clock;
|
|
2126
|
+
if (!clock) return false;
|
|
2127
|
+
const owner = clock.nextOwner();
|
|
2128
|
+
if (owner === void 0) return false;
|
|
2129
|
+
this.runAs(owner);
|
|
2130
|
+
return clock.fireNext();
|
|
2131
|
+
}
|
|
2132
|
+
/**
|
|
2133
|
+
* Concurrent runs: nothing can make progress; abandon these invocations so
|
|
2134
|
+
* the run can end. Returns how many were still alive.
|
|
2135
|
+
*/
|
|
2136
|
+
abandon(ids) {
|
|
2137
|
+
let abandoned = 0;
|
|
2138
|
+
for (const id of ids) {
|
|
2139
|
+
const inv = this.invocations.get(id);
|
|
2140
|
+
if (!inv || inv.isCrashed()) continue;
|
|
2141
|
+
this.unsupported(waitingUnseen(id));
|
|
2142
|
+
inv.crash();
|
|
2143
|
+
abandoned++;
|
|
2144
|
+
}
|
|
2145
|
+
return abandoned;
|
|
2146
|
+
}
|
|
2147
|
+
/** A call of a pure core function, recorded as a decision of the invocation running now (see `observeCore`). */
|
|
2148
|
+
decision(fn, payload) {
|
|
2149
|
+
this.logState = appendEffect(this.logState, {
|
|
2150
|
+
kind: "result",
|
|
2151
|
+
invocation: this.running(),
|
|
2152
|
+
target: decisionTarget(fn),
|
|
2153
|
+
op: "decide",
|
|
2154
|
+
payload
|
|
2155
|
+
});
|
|
2156
|
+
}
|
|
2157
|
+
snapshot(invocation, target, payload) {
|
|
2158
|
+
this.logState = appendEffect(this.logState, {
|
|
2159
|
+
kind: "snapshot",
|
|
2160
|
+
invocation,
|
|
2161
|
+
target,
|
|
2162
|
+
op: "snapshot",
|
|
2163
|
+
payload
|
|
2164
|
+
});
|
|
2165
|
+
}
|
|
2166
|
+
};
|
|
2167
|
+
// packages/engine/src/shrink.ts
|
|
2168
|
+
/**
|
|
2169
|
+
* Shrinking, the loop: try the pure candidates in order, replay each, keep
|
|
2170
|
+
* the first that still violates the same invariant for the same keys, and
|
|
2171
|
+
* repeat from there until nothing smaller works or the budget is spent.
|
|
2172
|
+
*/
|
|
2173
|
+
/** The scenario restricted to the kept events, with per-message invariants re-derived. */
|
|
2174
|
+
function restrictSpec(platform, spec, keepIds) {
|
|
2175
|
+
const restricted = platform.restrictEvents(spec, keepIds);
|
|
2176
|
+
const bodies = platform.initialEvents(restricted).map((e) => e.data);
|
|
2177
|
+
return {
|
|
2178
|
+
...restricted,
|
|
2179
|
+
invariants: recomputePerMessageExpected(restricted.invariants, bodies)
|
|
2180
|
+
};
|
|
2181
|
+
}
|
|
2182
|
+
async function shrink(spec, platform, schedule, violation, trace, options) {
|
|
2183
|
+
const allIds = platform.initialEvents(spec).map((e) => e.id);
|
|
2184
|
+
let state = {
|
|
2185
|
+
schedule,
|
|
2186
|
+
keepIds: allIds
|
|
2187
|
+
};
|
|
2188
|
+
let best = {
|
|
2189
|
+
trace,
|
|
2190
|
+
violation
|
|
2191
|
+
};
|
|
2192
|
+
let runs = 0;
|
|
2193
|
+
let improved = true;
|
|
2194
|
+
while (improved && runs < options.maxRuns && options.now() < options.deadline) {
|
|
2195
|
+
improved = false;
|
|
2196
|
+
for (const candidate of shrinkCandidates(state)) {
|
|
2197
|
+
if (runs >= options.maxRuns || options.now() >= options.deadline) break;
|
|
2198
|
+
const candidateSpec = restrictSpec(platform, spec, candidate.keepIds);
|
|
2199
|
+
const run = await replayRun(candidateSpec, platform, candidate.schedule);
|
|
2200
|
+
const log = run.log;
|
|
2201
|
+
runs++;
|
|
2202
|
+
if (run.unsupportedReasons.length > 0) continue;
|
|
2203
|
+
const found = checkInvariants(log, candidateSpec.invariants).find((v) => sameViolation(v, violation));
|
|
2204
|
+
if (found) {
|
|
2205
|
+
state = candidate;
|
|
2206
|
+
best = {
|
|
2207
|
+
trace: log,
|
|
2208
|
+
violation: found
|
|
2209
|
+
};
|
|
2210
|
+
improved = true;
|
|
2211
|
+
break;
|
|
2212
|
+
}
|
|
2213
|
+
}
|
|
2214
|
+
}
|
|
2215
|
+
return {
|
|
2216
|
+
spec: restrictSpec(platform, spec, state.keepIds),
|
|
2217
|
+
schedule: state.schedule,
|
|
2218
|
+
keptEvents: state.keepIds,
|
|
2219
|
+
trace: best.trace,
|
|
2220
|
+
violation: best.violation,
|
|
2221
|
+
runs,
|
|
2222
|
+
faultsRemoved: schedule.faults.length - state.schedule.faults.length,
|
|
2223
|
+
eventsRemoved: allIds.length - state.keepIds.length
|
|
2224
|
+
};
|
|
2225
|
+
}
|
|
2226
|
+
// packages/engine/src/explore.ts
|
|
2227
|
+
/**
|
|
2228
|
+
* The exploration loop: run the scenario under seeded fault injection until
|
|
2229
|
+
* an invariant breaks or the budget is spent; replay any violation before
|
|
2230
|
+
* reporting it.
|
|
2231
|
+
*/
|
|
2232
|
+
const engineAssumptions = [
|
|
2233
|
+
"schedule points are effect boundaries: proxied bindings, patched timers and fetch; other awaits run in program order",
|
|
2234
|
+
"faults: crash_before, crash_after, ambiguous, error at any effect point; redelivery per the platform's queue model",
|
|
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",
|
|
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",
|
|
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",
|
|
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",
|
|
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)",
|
|
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"
|
|
2241
|
+
];
|
|
2242
|
+
/** What a verdict rests on about concurrency, for these bounds. */
|
|
2243
|
+
function concurrencyAssumption(bounds) {
|
|
2244
|
+
if (bounds.maxConcurrentInvocations === 1) return "one invocation at a time (maxConcurrentInvocations = 1)";
|
|
2245
|
+
return `up to ${bounds.maxConcurrentInvocations} invocations in flight, interleaved only at asynchronous effects (proxied bindings, fetch): code between two such effects runs without interruption (except continuations of a promise it settles for another invocation, which run then and are still attributed to their own invocation), Web Crypto calls are waited for like I/O, other non-effect awaits (body reads included) settle within one turn of the event loop, synchronous effects are not interleaving points, an effect made by code another effect hosts (an object calling out during a call) is a turn of its own unless that code cannot be interrupted (an object inside blockConcurrencyWhile), when it runs within the hosting effect's turn, the next turn is a seeded pick among parked invocations, whether a new event starts while a slot is free is a seeded pick too, and timers fire only when no invocation can take a turn`;
|
|
2246
|
+
}
|
|
2247
|
+
/** The pending event to deliver next: the earliest by `at`, then the first queued. */
|
|
2248
|
+
function nextEvent(pending) {
|
|
2249
|
+
let best = 0;
|
|
2250
|
+
for (let i = 1; i < pending.length; i++) if ((pending[i]?.at ?? 0) < (pending[best]?.at ?? 0)) best = i;
|
|
2251
|
+
return best;
|
|
2252
|
+
}
|
|
2253
|
+
/** What a verdict rests on about how schedules were chosen, when exploration was exhaustive. */
|
|
2254
|
+
function explorationAssumption(options) {
|
|
2255
|
+
if (!options.exhaustive) return [];
|
|
2256
|
+
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)"] : []];
|
|
2257
|
+
}
|
|
2258
|
+
/** Deliver events one at a time, each to completion; time passes until a delayed one is due. */
|
|
2259
|
+
async function deliverInOrder(spec, platform, run) {
|
|
2260
|
+
const pending = [...platform.initialEvents(spec)];
|
|
2261
|
+
while (pending.length > 0) {
|
|
2262
|
+
const [event] = pending.splice(nextEvent(pending), 1);
|
|
2263
|
+
if (event.at !== void 0) await run.advanceTo(event.at);
|
|
2264
|
+
const result = await platform.deliver(event, run, spec);
|
|
2265
|
+
pending.push(...run.takeQueued(), ...result.followUps);
|
|
2266
|
+
}
|
|
2267
|
+
}
|
|
2268
|
+
/**
|
|
2269
|
+
* Deliver events with up to `maxConcurrentInvocations` in flight. Each turn
|
|
2270
|
+
* is a seeded pick: one parked invocation performs its effect and runs to
|
|
2271
|
+
* its next one, or, while a slot is free, the next event starts. When
|
|
2272
|
+
* nothing is parked and no event can start a timer fires, and when nothing
|
|
2273
|
+
* can move the remaining invocations are abandoned.
|
|
2274
|
+
*/
|
|
2275
|
+
async function deliverConcurrently(spec, platform, run) {
|
|
2276
|
+
const pending = [...platform.initialEvents(spec)];
|
|
2277
|
+
let active = [];
|
|
2278
|
+
for (;;) {
|
|
2279
|
+
const queuedBefore = pending.length;
|
|
2280
|
+
for (const d of active) {
|
|
2281
|
+
if (!d.outcome) continue;
|
|
2282
|
+
if ("error" in d.outcome) throw d.outcome.error;
|
|
2283
|
+
pending.push(...d.outcome.result.followUps);
|
|
2284
|
+
}
|
|
2285
|
+
active = active.filter((d) => !d.outcome);
|
|
2286
|
+
pending.push(...run.takeQueued());
|
|
2287
|
+
if (pending.length > queuedBefore) run.queuedEvents();
|
|
2288
|
+
if (active.length === 0 && pending.length === 0) return;
|
|
2289
|
+
const next = pending.length > 0 ? nextEvent(pending) : -1;
|
|
2290
|
+
const due = next >= 0 && (pending[next]?.at ?? 0) <= run.now();
|
|
2291
|
+
const canStart = active.length < spec.bounds.maxConcurrentInvocations && due;
|
|
2292
|
+
const turn = run.takeTurn(canStart);
|
|
2293
|
+
if (turn === "start") {
|
|
2294
|
+
const [event] = pending.splice(next, 1);
|
|
2295
|
+
const d = {
|
|
2296
|
+
started: run.startDelivery(() => platform.deliver(event, run, spec)),
|
|
2297
|
+
outcome: null
|
|
2298
|
+
};
|
|
2299
|
+
d.started.promise.then((result) => {
|
|
2300
|
+
d.outcome = { result };
|
|
2301
|
+
run.progressed();
|
|
2302
|
+
}, (error) => {
|
|
2303
|
+
d.outcome = { error };
|
|
2304
|
+
run.progressed();
|
|
2305
|
+
});
|
|
2306
|
+
active.push(d);
|
|
2307
|
+
} else if (turn === "none" && next >= 0 && !due && active.length < spec.bounds.maxConcurrentInvocations && (run.nextTimerDue() ?? Number.POSITIVE_INFINITY) > (pending[next]?.at ?? 0)) await run.advanceTo(pending[next]?.at ?? 0);
|
|
2308
|
+
else if (turn === "none" && !run.fireTimer()) {
|
|
2309
|
+
const stuck = active.flatMap((d) => d.started.invocation() ?? []);
|
|
2310
|
+
if (run.abandon(stuck) === 0) throw new Error(`the ${platform.name} platform's delivery made no progress and cannot be abandoned`);
|
|
2311
|
+
}
|
|
2312
|
+
await run.quiesce();
|
|
2313
|
+
}
|
|
2314
|
+
}
|
|
2315
|
+
/** Run the scenario once under the given run's fault decisions and return its log. */
|
|
2316
|
+
async function runOnce(spec, platform, run) {
|
|
2317
|
+
await platform.reset(spec);
|
|
2318
|
+
run.install(spec.externals);
|
|
2319
|
+
try {
|
|
2320
|
+
try {
|
|
2321
|
+
if (!run.concurrent) await deliverInOrder(spec, platform, run);
|
|
2322
|
+
else if (platform.concurrent) await deliverConcurrently(spec, platform, run);
|
|
2323
|
+
else throw new Error(`the ${platform.name} platform delivers one event at a time`);
|
|
2324
|
+
} finally {
|
|
2325
|
+
run.uninstall();
|
|
2326
|
+
}
|
|
2327
|
+
await platform.finish?.(spec, run);
|
|
2328
|
+
} finally {
|
|
2329
|
+
await platform.cleanup?.(spec);
|
|
2330
|
+
}
|
|
2331
|
+
return run.log;
|
|
2332
|
+
}
|
|
2333
|
+
/** Re-run a recorded schedule exactly and return the whole run (log and support status). */
|
|
2334
|
+
async function replayRun(spec, platform, schedule) {
|
|
2335
|
+
const run = new Run({
|
|
2336
|
+
mode: "replay",
|
|
2337
|
+
schedule,
|
|
2338
|
+
bounds: spec.bounds,
|
|
2339
|
+
faultProbability: 0
|
|
2340
|
+
});
|
|
2341
|
+
await runOnce(spec, platform, run);
|
|
2342
|
+
return run;
|
|
2343
|
+
}
|
|
2344
|
+
/** Re-run a recorded schedule exactly. */
|
|
2345
|
+
async function replay(spec, platform, schedule) {
|
|
2346
|
+
return (await replayRun(spec, platform, schedule)).log;
|
|
2347
|
+
}
|
|
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
|
+
};
|
|
2358
|
+
const now = options.now ?? (() => Date.now());
|
|
2359
|
+
const maxRuns = options.maxRuns ?? 100;
|
|
2360
|
+
const faultProbability = options.faultProbability ?? .9;
|
|
2361
|
+
const assumptions = [
|
|
2362
|
+
...engineAssumptions,
|
|
2363
|
+
concurrencyAssumption(spec.bounds),
|
|
2364
|
+
...explorationAssumption(options),
|
|
2365
|
+
...platform.assumptions
|
|
2366
|
+
];
|
|
2367
|
+
const start = now();
|
|
2368
|
+
const reached = {
|
|
2369
|
+
runs: 0,
|
|
2370
|
+
effectPoints: 0,
|
|
2371
|
+
faultsInjected: 0
|
|
2372
|
+
};
|
|
2373
|
+
const done = () => ({
|
|
2374
|
+
...reached,
|
|
2375
|
+
elapsedMs: now() - start
|
|
2376
|
+
});
|
|
2377
|
+
const base = {
|
|
2378
|
+
scenario: spec.name,
|
|
2379
|
+
seed: options.seed,
|
|
2380
|
+
assumptions
|
|
2381
|
+
};
|
|
2382
|
+
if (spec.bounds.maxConcurrentInvocations > 1 && !concurrencySupported) return {
|
|
2383
|
+
...base,
|
|
2384
|
+
kind: "UNSUPPORTED",
|
|
2385
|
+
cause: "unsupported_bounds",
|
|
2386
|
+
reason: "maxConcurrentInvocations above 1 needs AsyncLocalStorage (Node, or workerd with nodejs_compat or nodejs_als)",
|
|
2387
|
+
reached: done()
|
|
2388
|
+
};
|
|
2389
|
+
if (spec.bounds.maxConcurrentInvocations > 1 && !platform.concurrent) return {
|
|
2390
|
+
...base,
|
|
2391
|
+
kind: "UNSUPPORTED",
|
|
2392
|
+
cause: "unsupported_bounds",
|
|
2393
|
+
reason: `maxConcurrentInvocations above 1 is not supported on the ${platform.name} platform yet`,
|
|
2394
|
+
reached: done()
|
|
2395
|
+
};
|
|
2396
|
+
const leakCheckRuns = options.leakCheckRuns ?? 2;
|
|
2397
|
+
/** The first runs' schedules and digests, replayed in reverse order before BOUNDED. */
|
|
2398
|
+
const witnesses = [];
|
|
2399
|
+
let master = seedPrng(options.seed);
|
|
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;
|
|
2404
|
+
const doneNow = () => ({
|
|
2405
|
+
...done(),
|
|
2406
|
+
...exhaustive ? { exhaustive: exhaustive.reached } : {}
|
|
2407
|
+
});
|
|
2408
|
+
while ((exhaustive?.hasMore ?? true) && reached.runs < maxRuns && now() - start < spec.bounds.budgetMs) {
|
|
2409
|
+
const [runSeed, next] = nextU32(master);
|
|
2410
|
+
master = next;
|
|
2411
|
+
let faultPlan = [];
|
|
2412
|
+
if (!exhaustive) [faultPlan, master] = planFaults(master, baseline, longest, spec.bounds.maxFaultsPerRun, faultProbability);
|
|
2413
|
+
const run = new Run({
|
|
2414
|
+
mode: "explore",
|
|
2415
|
+
schedule: {
|
|
2416
|
+
seed: exhaustive ? 0 : runSeed,
|
|
2417
|
+
faults: []
|
|
2418
|
+
},
|
|
2419
|
+
bounds: spec.bounds,
|
|
2420
|
+
faultProbability,
|
|
2421
|
+
...exhaustive ? { chooser: exhaustive.next() } : { faultPlan }
|
|
2422
|
+
});
|
|
2423
|
+
const log = await runOnce(spec, platform, run);
|
|
2424
|
+
reached.runs++;
|
|
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 {
|
|
2429
|
+
...base,
|
|
2430
|
+
kind: "UNSUPPORTED",
|
|
2431
|
+
cause: "not_replayable",
|
|
2432
|
+
reason: `exhaustive exploration needs deterministic runs: ${exhaustive.mismatch}`,
|
|
2433
|
+
reached: doneNow()
|
|
2434
|
+
};
|
|
2435
|
+
if (!exhaustive.ran(() => run.turnsMayNotCommute)) continue;
|
|
2436
|
+
}
|
|
2437
|
+
reached.effectPoints += run.effectPoints;
|
|
2438
|
+
reached.faultsInjected += run.faultsInjected;
|
|
2439
|
+
if (witnesses.length < leakCheckRuns) witnesses.push({
|
|
2440
|
+
schedule: run.schedule,
|
|
2441
|
+
digest: digestLog(log)
|
|
2442
|
+
});
|
|
2443
|
+
if (run.unsupportedReasons.length > 0) return {
|
|
2444
|
+
...base,
|
|
2445
|
+
kind: "UNSUPPORTED",
|
|
2446
|
+
cause: "unsupported_api",
|
|
2447
|
+
reason: run.unsupportedReasons.join("; "),
|
|
2448
|
+
reached: doneNow()
|
|
2449
|
+
};
|
|
2450
|
+
const violation = checkInvariants(log, spec.invariants)[0];
|
|
2451
|
+
if (violation) {
|
|
2452
|
+
const schedule = run.schedule;
|
|
2453
|
+
const replayedRun = await replayRun(spec, platform, schedule);
|
|
2454
|
+
const replayed = replayedRun.log;
|
|
2455
|
+
reached.runs++;
|
|
2456
|
+
if (replayedRun.unsupportedReasons.length > 0 || digestLog(replayed) !== digestLog(log)) return {
|
|
2457
|
+
...base,
|
|
2458
|
+
kind: "UNSUPPORTED",
|
|
2459
|
+
cause: "not_replayable",
|
|
2460
|
+
reason: `the violating run of seed ${schedule.seed} did not reproduce on replay`,
|
|
2461
|
+
reached: doneNow()
|
|
2462
|
+
};
|
|
2463
|
+
const shrunk = await shrink(spec, platform, schedule, violation, replayed, {
|
|
2464
|
+
maxRuns: options.maxShrinkRuns ?? 200,
|
|
2465
|
+
deadline: now() + spec.bounds.budgetMs,
|
|
2466
|
+
now
|
|
2467
|
+
});
|
|
2468
|
+
reached.runs += shrunk.runs;
|
|
2469
|
+
return {
|
|
2470
|
+
...base,
|
|
2471
|
+
kind: "VIOLATED",
|
|
2472
|
+
violation: shrunk.violation,
|
|
2473
|
+
trace: shrunk.trace,
|
|
2474
|
+
schedule: shrunk.schedule,
|
|
2475
|
+
keptEvents: shrunk.keptEvents,
|
|
2476
|
+
shrunk: {
|
|
2477
|
+
faultsRemoved: shrunk.faultsRemoved,
|
|
2478
|
+
eventsRemoved: shrunk.eventsRemoved,
|
|
2479
|
+
runs: shrunk.runs
|
|
2480
|
+
},
|
|
2481
|
+
reached: doneNow()
|
|
2482
|
+
};
|
|
2483
|
+
}
|
|
2484
|
+
exhaustive?.checked();
|
|
2485
|
+
}
|
|
2486
|
+
for (const witness of [...witnesses].reverse()) {
|
|
2487
|
+
const again = await replayRun(spec, platform, witness.schedule);
|
|
2488
|
+
reached.runs++;
|
|
2489
|
+
if (again.unsupportedReasons.length > 0 || digestLog(again.log) !== witness.digest) return {
|
|
2490
|
+
...base,
|
|
2491
|
+
kind: "UNSUPPORTED",
|
|
2492
|
+
cause: "module_state_leak",
|
|
2493
|
+
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)`,
|
|
2494
|
+
reached: doneNow()
|
|
2495
|
+
};
|
|
2496
|
+
}
|
|
2497
|
+
return {
|
|
2498
|
+
...base,
|
|
2499
|
+
kind: "BOUNDED",
|
|
2500
|
+
bounds: spec.bounds,
|
|
2501
|
+
reached: doneNow()
|
|
2502
|
+
};
|
|
2503
|
+
}
|
|
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);
|
|
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;
|
|
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
|
+
*/
|
|
2589
|
+
function observeCore(namespace, functions) {
|
|
2590
|
+
const calls = [];
|
|
2591
|
+
const unobservable = Object.create(null);
|
|
2592
|
+
const undo = [];
|
|
2593
|
+
const target = namespace;
|
|
2594
|
+
for (const name of functions) {
|
|
2595
|
+
const original = target[name];
|
|
2596
|
+
if (typeof original !== "function") {
|
|
2597
|
+
unobservable[name] = `the module exports no function ${name}`;
|
|
2598
|
+
continue;
|
|
2599
|
+
}
|
|
2600
|
+
const wrapped = function(...args) {
|
|
2601
|
+
const run = installedRun();
|
|
2602
|
+
if (!run) return Reflect.apply(original, this, args);
|
|
2603
|
+
const record = (threw, payload) => {
|
|
2604
|
+
calls.push({
|
|
2605
|
+
function: name,
|
|
2606
|
+
args: [...args],
|
|
2607
|
+
threw
|
|
2608
|
+
});
|
|
2609
|
+
run.decision(name, {
|
|
2610
|
+
args: toJson(args),
|
|
2611
|
+
...payload
|
|
2612
|
+
});
|
|
2613
|
+
};
|
|
2614
|
+
let value;
|
|
2615
|
+
try {
|
|
2616
|
+
value = Reflect.apply(original, this, args);
|
|
2617
|
+
} catch (err) {
|
|
2618
|
+
record(true, { error: String(err) });
|
|
2619
|
+
throw err;
|
|
2620
|
+
}
|
|
2621
|
+
if (typeof value?.then === "function") {
|
|
2622
|
+
run.unsupported(`core function ${name} returned a promise; observed core functions must be synchronous and pure`);
|
|
2623
|
+
return value;
|
|
2624
|
+
}
|
|
2625
|
+
record(false, { result: toJson(value) });
|
|
2626
|
+
return value;
|
|
2627
|
+
};
|
|
2628
|
+
let restore;
|
|
2629
|
+
try {
|
|
2630
|
+
restore = patchProperty(target, name, { get: () => wrapped });
|
|
2631
|
+
} catch (err) {
|
|
2632
|
+
unobservable[name] = `its module's namespace cannot be changed here (${String(err)})`;
|
|
2633
|
+
continue;
|
|
2634
|
+
}
|
|
2635
|
+
if (target[name] !== wrapped) {
|
|
2636
|
+
restore();
|
|
2637
|
+
unobservable[name] = "its module's namespace did not take the observer";
|
|
2638
|
+
continue;
|
|
2639
|
+
}
|
|
2640
|
+
undo.push(restore);
|
|
2641
|
+
}
|
|
2642
|
+
let restored = false;
|
|
2643
|
+
return {
|
|
2644
|
+
calls,
|
|
2645
|
+
unobservable,
|
|
2646
|
+
restore() {
|
|
2647
|
+
if (restored) return;
|
|
2648
|
+
restored = true;
|
|
2649
|
+
for (const u of undo.reverse()) u();
|
|
2650
|
+
}
|
|
2651
|
+
};
|
|
2652
|
+
}
|
|
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 };
|
|
2654
|
+
|
|
2655
|
+
//# sourceMappingURL=src-Bqc9Eyb1.mjs.map
|