eutaxy 0.13.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"src-DPCF2XGv.mjs","names":[],"sources":["../../core/src/canonical-json.ts","../../core/src/selectors.ts","../../core/src/utf8.ts","../../core/src/effect-log.ts","../../core/src/prng.ts","../../core/src/faults.ts","../../core/src/refines.ts","../../core/src/state.ts","../../core/src/invariants.ts","../../core/src/scenario.ts","../../core/src/shrink.ts","../../core/src/to-json.ts","../../engine/src/chooser.ts","../../engine/src/context.ts","../../engine/src/patch.ts","../../engine/src/clock.ts","../../engine/src/fetch.ts","../../engine/src/frames.ts","../../engine/src/turns.ts","../../engine/src/run.ts","../../engine/src/deliver.ts","../../engine/src/exhaustive.ts","../../engine/src/shrink.ts","../../engine/src/explore.ts","../../engine/src/differential.ts","../../engine/src/observe.ts"],"sourcesContent":["/**\n * Canonical JSON: the one serialisation of a value, so that equal data always\n * produces equal bytes. Object keys are sorted; numbers must be finite; there\n * is no whitespace. Anything that is not plain JSON data is rejected.\n */\n\nexport type JsonValue =\n | null\n | boolean\n | number\n | string\n | readonly JsonValue[]\n | { readonly [key: string]: JsonValue };\n\nexport function canonicalJson(value: JsonValue): string {\n if (value === null) return \"null\";\n switch (typeof value) {\n case \"boolean\":\n return value ? \"true\" : \"false\";\n case \"number\":\n if (!Number.isFinite(value)) throw new TypeError(`non-finite number: ${value}`);\n return Object.is(value, -0) ? \"0\" : JSON.stringify(value);\n case \"string\":\n return JSON.stringify(value);\n case \"object\": {\n if (Array.isArray(value)) {\n const items: string[] = [];\n for (let i = 0; i < value.length; i++) {\n const v = value[i];\n if (v === undefined) throw new TypeError(`hole or undefined at index ${i}`);\n items.push(canonicalJson(v));\n }\n return `[${items.join(\",\")}]`;\n }\n const keys = Object.keys(value).sort();\n const parts: string[] = [];\n for (const k of keys) {\n const v = (value as { readonly [key: string]: JsonValue | undefined })[k];\n if (v === undefined) throw new TypeError(`undefined at key ${JSON.stringify(k)}`);\n parts.push(`${JSON.stringify(k)}:${canonicalJson(v)}`);\n }\n return `{${parts.join(\",\")}}`;\n }\n default:\n throw new TypeError(`not JSON data: ${typeof value}`);\n }\n}\n","/** Picking effect records out of the log, and reading paths out of their payloads. */\n\nimport { canonicalJson, type JsonValue } from \"./canonical-json.ts\";\nimport type { EffectKind, EffectLog, EffectRecord } from \"./effect-log.ts\";\n\n/** Picks effect records by target, op, kind and payload fields. */\nexport interface EffectSelector {\n readonly target: string;\n readonly op?: string;\n readonly kind?: EffectKind;\n /** Dot paths into the payload that must equal the given values. */\n readonly where?: { readonly [path: string]: JsonValue };\n /** Dot paths into the payload whose numeric value must be at least the given bound. */\n readonly atLeast?: { readonly [path: string]: number };\n}\n\n/** Read a dot path such as \"args.params.0\" out of JSON data; undefined when absent. */\nexport function getPath(value: JsonValue, path: string): JsonValue | undefined {\n let cur: JsonValue | undefined = value;\n if (path === \"\") return cur;\n for (const part of path.split(\".\")) {\n if (cur === null || typeof cur !== \"object\") return undefined;\n if (Array.isArray(cur)) {\n const i = Number(part);\n if (!Number.isInteger(i) || i < 0) return undefined;\n cur = cur[i];\n } else {\n cur = (cur as { readonly [k: string]: JsonValue })[part];\n }\n if (cur === undefined) return undefined;\n }\n return cur;\n}\n\nexport function jsonEqual(a: JsonValue | undefined, b: JsonValue): boolean {\n if (a === undefined) return false;\n if (a === b) return true;\n if (a === null || b === null || typeof a !== \"object\" || typeof b !== \"object\") return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((x, i) => jsonEqual(x, b[i] as JsonValue));\n }\n const ao = a as { readonly [k: string]: JsonValue };\n const bo = b as { readonly [k: string]: JsonValue };\n const ak = Object.keys(ao).sort();\n const bk = Object.keys(bo).sort();\n return (\n ak.length === bk.length &&\n ak.every((k, i) => k === bk[i] && jsonEqual(ao[k], bo[k] as JsonValue))\n );\n}\n\nexport function matches(record: EffectRecord, sel: EffectSelector): boolean {\n if (record.target !== sel.target) return false;\n if (sel.op !== undefined && record.op !== sel.op) return false;\n if (sel.kind !== undefined && record.kind !== sel.kind) return false;\n if (sel.where) {\n for (const [path, want] of Object.entries(sel.where)) {\n if (!jsonEqual(getPath(record.payload, path), want)) return false;\n }\n }\n if (sel.atLeast) {\n for (const [path, min] of Object.entries(sel.atLeast)) {\n const v = getPath(record.payload, path);\n if (typeof v !== \"number\" || v < min) return false;\n }\n }\n return true;\n}\n\nexport function selectEffects(log: EffectLog, sel: EffectSelector): readonly EffectRecord[] {\n return log.entries.filter((e) => matches(e, sel));\n}\n\n/** Canonical form of a key, so equal JSON values compare equal whatever their key order. */\nexport function keyOf(record: EffectRecord, path: string): string | undefined {\n const v = getPath(record.payload, path);\n return v === undefined ? undefined : canonicalJson(v);\n}\n","/**\n * UTF-8 encode a string, with no runtime dependency on TextEncoder. An unpaired\n * surrogate becomes U+FFFD, exactly as TextEncoder does, so the output is\n * always valid UTF-8.\n */\nexport function utf8Encode(s: string): Uint8Array {\n const out: number[] = [];\n for (const ch of s) {\n let cp = ch.codePointAt(0) ?? 0;\n if (cp >= 0xd800 && cp <= 0xdfff) cp = 0xfffd;\n if (cp < 0x80) out.push(cp);\n else if (cp < 0x800) out.push(0xc0 | (cp >> 6), 0x80 | (cp & 0x3f));\n else if (cp < 0x10000)\n out.push(0xe0 | (cp >> 12), 0x80 | ((cp >> 6) & 0x3f), 0x80 | (cp & 0x3f));\n else\n out.push(\n 0xf0 | (cp >> 18),\n 0x80 | ((cp >> 12) & 0x3f),\n 0x80 | ((cp >> 6) & 0x3f),\n 0x80 | (cp & 0x3f),\n );\n }\n return Uint8Array.from(out);\n}\n","/**\n * The effect log: the complete, ordered record of what a simulated run did at\n * its effect boundaries. It is plain data, appended immutably, and has one\n * canonical serialisation, so two runs are identical exactly when their\n * serialised logs are byte-identical.\n */\n\nimport { canonicalJson, type JsonValue } from \"./canonical-json.ts\";\nimport { utf8Encode } from \"./utf8.ts\";\n\n/** `snapshot` records platform state (e.g. D1 tables) captured at the end of a run; it is not an effect point. */\nexport type EffectKind = \"call\" | \"result\" | \"fault\" | \"snapshot\";\n\nexport interface EffectRecord {\n /** Position in the log, dense from 0. */\n readonly seq: number;\n readonly kind: EffectKind;\n /** The invocation (request, message, alarm) this effect belongs to. */\n readonly invocation: string;\n /** The binding or global the effect went through, e.g. \"D1:DB\". */\n readonly target: string;\n /** The operation, e.g. \"run\", \"batch\", \"send\". */\n readonly op: string;\n /** Operation-specific data: arguments, results, or the injected fault. */\n readonly payload: JsonValue;\n}\n\nexport interface EffectLog {\n readonly entries: readonly EffectRecord[];\n}\n\nexport const emptyLog: EffectLog = Object.freeze({ entries: Object.freeze([]) });\n\n/** Append one effect, assigning its sequence number. The input log is unchanged. */\nexport function appendEffect(log: EffectLog, effect: Omit<EffectRecord, \"seq\">): EffectLog {\n const record: EffectRecord = { ...effect, seq: log.entries.length };\n return { entries: [...log.entries, record] };\n}\n\n/** One canonical JSON object per line, in sequence order. */\nexport function serializeLog(log: EffectLog): string {\n return log.entries\n .map((e) =>\n canonicalJson({\n seq: e.seq,\n kind: e.kind,\n invocation: e.invocation,\n target: e.target,\n op: e.op,\n payload: e.payload,\n }),\n )\n .join(\"\\n\");\n}\n\n/** A 64-bit FNV-1a digest of the serialised log, as 16 hex digits. Not cryptographic. */\nexport function digestLog(log: EffectLog): string {\n const bytes = utf8Encode(serializeLog(log));\n let h = 0xcbf29ce484222325n;\n for (const b of bytes) {\n h ^= BigInt(b);\n h = (h * 0x100000001b3n) & 0xffffffffffffffffn;\n }\n return h.toString(16).padStart(16, \"0\");\n}\n","/**\n * A pure, seedable pseudo-random generator (xoshiro128**).\n *\n * State is an immutable tuple of four 32-bit words. Every operation returns a\n * value and the next state; nothing is mutated, so a schedule can be replayed\n * from any state and two explorations can never interfere with each other.\n * Not cryptographic.\n */\n\nexport type PrngState = readonly [number, number, number, number];\n\nfunction rotl(x: number, k: number): number {\n return ((x << k) | (x >>> (32 - k))) >>> 0;\n}\n\n/** splitmix32: expands a 32-bit seed into well-mixed words for seeding. */\nfunction splitmix32(seed: number): () => number {\n let a = seed >>> 0;\n return () => {\n a = (a + 0x9e3779b9) >>> 0;\n let t = a;\n t = Math.imul(t ^ (t >>> 16), 0x21f0aaad);\n t = Math.imul(t ^ (t >>> 15), 0x735a2d97);\n return (t ^ (t >>> 15)) >>> 0;\n };\n}\n\n/** FNV-1a over UTF-16 code units, so string seeds are stable across runtimes. */\nfunction hashString(s: string): number {\n let h = 0x811c9dc5;\n for (let i = 0; i < s.length; i++) {\n h ^= s.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n return h >>> 0;\n}\n\n/** Derive an initial state from a number (taken modulo 2^32) or a string. */\nexport function seedPrng(seed: number | string): PrngState {\n const word = typeof seed === \"string\" ? hashString(seed) : seed >>> 0;\n const next = splitmix32(word);\n const s: [number, number, number, number] = [next(), next(), next(), next()];\n if (s[0] === 0 && s[1] === 0 && s[2] === 0 && s[3] === 0) {\n s[0] = 1; // xoshiro must never hold the all-zero state\n }\n return s;\n}\n\n/** Next 32-bit unsigned integer and the state that follows it. */\nexport function nextU32(state: PrngState): readonly [number, PrngState] {\n const [s0, s1, s2, s3] = state;\n const result = Math.imul(rotl(Math.imul(s1, 5) >>> 0, 7), 9) >>> 0;\n const t = (s1 << 9) >>> 0;\n let n2 = (s2 ^ s0) >>> 0;\n let n3 = (s3 ^ s1) >>> 0;\n const n1 = (s1 ^ n2) >>> 0;\n const n0 = (s0 ^ n3) >>> 0;\n n2 = (n2 ^ t) >>> 0;\n n3 = rotl(n3, 11);\n return [result, [n0, n1, n2, n3]];\n}\n\n/** Next float in [0, 1) with 24 bits of precision. */\nexport function nextFloat(state: PrngState): readonly [number, PrngState] {\n const [u, next] = nextU32(state);\n return [(u >>> 8) * 2 ** -24, next];\n}\n\n/**\n * Next integer in [0, bound). Uses rejection sampling, so every value is\n * equally likely; a bound of 1 always yields 0 without consuming state.\n */\nexport function nextInt(state: PrngState, bound: number): readonly [number, PrngState] {\n if (!Number.isInteger(bound) || bound < 1 || bound > 0x1_0000_0000) {\n throw new RangeError(`nextInt bound must be an integer in [1, 2^32], got ${bound}`);\n }\n if (bound === 1) return [0, state];\n const limit = 0x1_0000_0000 - (0x1_0000_0000 % bound);\n let s = state;\n for (;;) {\n const [u, next] = nextU32(s);\n s = next;\n if (u < limit) return [u % bound, s];\n }\n}\n","/**\n * The fault model and the schedule. A schedule is the complete, replayable\n * record of which fault was injected at which effect point in one run.\n */\n\nimport { nextFloat, nextInt, type PrngState } from \"./prng.ts\";\n\n/**\n * `cut_off` is a crash that happens after a response or acknowledgement was\n * already sent, so only background work (ctx.waitUntil) is lost; platforms\n * offer it at the point where that work would start.\n */\nexport type FaultKind = \"crash_before\" | \"crash_after\" | \"ambiguous\" | \"error\" | \"cut_off\";\n\n/**\n * The ladders of faults an effect's kind admits, written once; a proxy names\n * one as a point's `allowed` faults. A point with a meaning of its own (the\n * response point, a Workflow step, the background point) lists its own.\n */\n/** An effect that may commit and whose answer may be lost: a write, a call into another system, an outbound request. */\nexport const writeFaults: readonly FaultKind[] = [\n \"crash_before\",\n \"crash_after\",\n \"ambiguous\",\n \"error\",\n];\n/** An effect with nothing to be ambiguous about: a read, or a handler run whose failure is seen either way. */\nexport const readFaults: readonly FaultKind[] = [\"crash_before\", \"crash_after\", \"error\"];\n/** A decision a platform records on the invocation's behalf (an ack, a delete): the invocation may die either side of it; it neither errors nor goes missing. */\nexport const decisionFaults: readonly FaultKind[] = [\"crash_before\", \"crash_after\"];\n\nexport interface FaultDecision {\n /** The invocation the effect belongs to, e.g. \"msg-1#2\". */\n readonly invocation: string;\n /** Position of the effect within that invocation, from 0. Stable when other invocations are removed. */\n readonly ordinal: number;\n readonly fault: FaultKind;\n /** What the effect was, for people reading the schedule. */\n readonly target: string;\n readonly op: string;\n}\n\nexport interface Schedule {\n /** The per-run seed the decisions were drawn from. */\n readonly seed: number;\n readonly faults: readonly FaultDecision[];\n /**\n * The turn picked at each scheduling decision with more than one option,\n * in order, as an index into the options (parked invocations by start\n * order, then starting the next event). Absent: turns follow the seed.\n * Exhaustive exploration records them, since it picks rather than draws.\n */\n readonly turns?: readonly number[];\n}\n\nexport interface FaultPolicy {\n readonly maxFaultsPerRun: number;\n /** Probability of injecting at an eligible effect point, in [0, 1]. */\n readonly faultProbability: number;\n}\n\n/**\n * Decide whether to inject a fault at an effect point during exploration.\n * Pure: the same state and inputs always give the same decision. The PRNG is\n * only consumed when a fault is possible, so adding an ineligible point does\n * not perturb later decisions.\n */\nexport function decideFault(\n state: PrngState,\n allowed: readonly FaultKind[],\n faultsSoFar: number,\n policy: FaultPolicy,\n): readonly [FaultKind | null, PrngState] {\n if (allowed.length === 0 || faultsSoFar >= policy.maxFaultsPerRun) return [null, state];\n const [p, s1] = nextFloat(state);\n if (p >= policy.faultProbability) return [null, s1];\n const [i, s2] = nextInt(s1, allowed.length);\n return [allowed[i] ?? null, s2];\n}\n\n/**\n * Where one seeded run injects its faults: with probability `probability`,\n * one up to `maxFaults` distinct positions, in increasing order; otherwise\n * none. Positions count the run's eligible points (those that may take a\n * fault) from 0. The first is uniform over the `baseline` points a run\n * without faults has, which every run reaches before its first fault; the\n * others come after it, uniform up to `longest`, the most any run has had\n * (earlier faults, a redelivery say, can make a run longer). Pure.\n */\nexport function planFaults(\n state: PrngState,\n baseline: number,\n longest: number,\n maxFaults: number,\n probability: number,\n): readonly [readonly number[], PrngState] {\n if (baseline <= 0 || maxFaults <= 0) return [[], state];\n const [p, s1] = nextFloat(state);\n if (p >= probability) return [[], s1];\n let [k, s] = nextInt(s1, maxFaults);\n const more = k;\n let first: number;\n [first, s] = nextInt(s, baseline);\n const room = Math.max(longest, baseline) - first - 1;\n const chosen = new Set<number>([first]);\n while (chosen.size < 1 + Math.min(more, room)) {\n [k, s] = nextInt(s, room);\n chosen.add(first + 1 + k);\n }\n return [[...chosen].sort((a, b) => a - b), s];\n}\n","/** `refines`: the shell carries out the decisions its pure core made, and not on a stale read. */\n\nimport { canonicalJson, type JsonValue } from \"./canonical-json.ts\";\nimport type { EffectLog, EffectRecord } from \"./effect-log.ts\";\nimport type { Violation } from \"./invariants.ts\";\nimport {\n type EffectSelector,\n getPath,\n jsonEqual,\n keyOf,\n matches,\n selectEffects,\n} from \"./selectors.ts\";\n\n/**\n * The shell follows the core. Calls to a pure core function are recorded as\n * decisions (`Core:<function>` results, payload `{ args, result }`). Every\n * selected effect must come after a decision of `decision` in its own\n * invocation; the latest such decision is the one it carries out. With\n * `follows`, the effect's payload agrees with that decision at each pair of\n * paths. With `state`, the decision rests on the last `read` its invocation\n * made before it (none is a violation), and no other invocation's `write`\n * (to the same `key`, when given) commits between that read and the effect:\n * otherwise the effect carried out a decision made on a stale read.\n */\nexport interface Refines {\n readonly kind: \"refines\";\n readonly name: string;\n /** The core function, as recorded. */\n readonly decision: string;\n readonly effect: EffectSelector;\n readonly follows?: readonly { readonly effect: string; readonly decision: string }[];\n readonly state?: {\n readonly read: EffectSelector;\n readonly write: EffectSelector;\n /** Dot path into the read's and the writes' payloads naming the state they touch. */\n readonly key?: string;\n };\n}\n\n/** The log target decisions of a core function are recorded under. */\nexport function decisionTarget(fn: string): string {\n return `Core:${fn}`;\n}\n\nexport function checkRefines(log: EffectLog, inv: Refines): Violation | null {\n const target = decisionTarget(inv.decision);\n const before = (seq: number, invocation: string, pick: (e: EffectRecord) => boolean) => {\n let found: EffectRecord | undefined;\n for (const e of log.entries) {\n if (e.seq >= seq) break;\n if (e.invocation === invocation && pick(e)) found = e;\n }\n return found;\n };\n for (const effect of selectEffects(log, inv.effect)) {\n const what = `${effect.target} ${effect.op} (seq ${effect.seq}) in ${effect.invocation}`;\n // A call that threw decided nothing.\n const decision = before(\n effect.seq,\n effect.invocation,\n (e) =>\n e.target === target && e.kind === \"result\" && getPath(e.payload, \"error\") === undefined,\n );\n if (!decision) {\n return {\n invariant: inv.name,\n message: `${what} carries out no decision: ${inv.decision} was not called before it in that invocation`,\n keys: [\"no_decision\"],\n evidence: [effect.seq],\n };\n }\n for (const pair of inv.follows ?? []) {\n const got = getPath(effect.payload, pair.effect);\n const want = getPath(decision.payload, pair.decision);\n if (want === undefined ? got !== undefined : !jsonEqual(got, want)) {\n const show = (v: JsonValue | undefined) => (v === undefined ? \"nothing\" : canonicalJson(v));\n return {\n invariant: inv.name,\n 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)}`,\n keys: [\"not_followed\", pair.effect],\n evidence: [decision.seq, effect.seq],\n };\n }\n }\n const state = inv.state;\n if (!state) continue;\n const read = before(decision.seq, effect.invocation, (e) => matches(e, state.read));\n if (!read) {\n return {\n invariant: inv.name,\n 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`,\n keys: [\"no_read\"],\n evidence: [decision.seq, effect.seq],\n };\n }\n const key = state.key === undefined ? undefined : keyOf(read, state.key);\n const write = log.entries.find(\n (e) =>\n e.seq > read.seq &&\n e.seq < effect.seq &&\n e.invocation !== effect.invocation &&\n matches(e, state.write) &&\n (state.key === undefined || keyOf(e, state.key) === key),\n );\n if (write) {\n return {\n invariant: inv.name,\n 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 === undefined ? \"\" : ` of ${key}`}, and ${write.invocation} changed it at seq ${write.seq} before the effect committed`,\n keys: [\"stale_read\", ...(key === undefined ? [] : [key])],\n evidence: [read.seq, decision.seq, write.seq, effect.seq],\n };\n }\n }\n return null;\n}\n","/** State invariants: conditions on the rows of the end-of-run snapshots recorded in the log. */\n\nimport { canonicalJson, type JsonValue } from \"./canonical-json.ts\";\nimport type { EffectLog, EffectRecord } from \"./effect-log.ts\";\nimport type { Violation } from \"./invariants.ts\";\nimport { type EffectSelector, getPath, jsonEqual, keyOf, selectEffects } from \"./selectors.ts\";\n\n/** A condition on one column of a row. */\nexport type RowCondition =\n | { readonly column: string; readonly op: \"eq\" | \"neq\"; readonly value: JsonValue }\n | { readonly column: string; readonly op: \"gt\" | \"gte\" | \"lt\" | \"lte\"; readonly value: number }\n | { readonly column: string; readonly op: \"in\"; readonly value: readonly JsonValue[] }\n | { readonly column: string; readonly op: \"notNull\" };\n\n/** Rows of a table in the last snapshot of a target, optionally filtered. */\nexport interface StateQuery {\n /** The snapshot target, e.g. \"D1:DB\". */\n readonly target: string;\n readonly table: string;\n readonly where?: readonly RowCondition[];\n}\n\n/** Every row the query returns satisfies all of `holds`. */\nexport interface EveryRow {\n readonly kind: \"everyRow\";\n readonly name: string;\n readonly query: StateQuery;\n readonly holds: readonly RowCondition[];\n}\n\n/**\n * For every selected effect, a row exists whose `column` equals the effect's\n * key. Ties what the shell did to what the state says, e.g. \"every acked\n * message has its payment row\".\n */\nexport interface Implies {\n readonly kind: \"implies\";\n readonly name: string;\n readonly when: EffectSelector;\n /** Dot path into the effect payload that yields the key. */\n readonly key: string;\n readonly state: StateQuery;\n readonly column: string;\n}\n\n/**\n * No two rows the query returns share the value at `path`, a dot path into\n * the row (a column name for flat rows). Rows where it is absent or null are\n * skipped. Catches a resource handed out twice, e.g. \"no project holds two\n * slots\".\n */\nexport interface Unique {\n readonly kind: \"unique\";\n readonly name: string;\n readonly query: StateQuery;\n readonly path: string;\n}\n\n/**\n * Every row the query returns is pointed at: some row of `in` has its\n * `column` equal to the row's value at `path`, as with a foreign key. Rows\n * where the value is absent or null are skipped. Catches orphans across two\n * stores, e.g. \"no stored object without the row that names it\".\n */\nexport interface References {\n readonly kind: \"references\";\n readonly name: string;\n readonly query: StateQuery;\n readonly path: string;\n readonly in: StateQuery;\n readonly column: string;\n}\n\nexport type Row = { readonly [column: string]: JsonValue };\n\n/** The tables in the last snapshot recorded for a target, or undefined when none was. */\nexport function lastSnapshot(\n log: EffectLog,\n target: string,\n): { readonly [table: string]: readonly Row[] } | undefined {\n for (let i = log.entries.length - 1; i >= 0; i--) {\n const e = log.entries[i] as EffectRecord;\n if (e.kind === \"snapshot\" && e.target === target) {\n const tables = getPath(e.payload, \"tables\");\n if (tables && typeof tables === \"object\" && !Array.isArray(tables)) {\n return tables as { readonly [table: string]: readonly Row[] };\n }\n return {};\n }\n }\n return undefined;\n}\n\nexport function rowMatches(row: Row, condition: RowCondition): boolean {\n const v = row[condition.column];\n switch (condition.op) {\n case \"eq\":\n return v !== undefined && jsonEqual(v, condition.value);\n case \"neq\":\n return v === undefined || !jsonEqual(v, condition.value);\n case \"gt\":\n return typeof v === \"number\" && v > condition.value;\n case \"gte\":\n return typeof v === \"number\" && v >= condition.value;\n case \"lt\":\n return typeof v === \"number\" && v < condition.value;\n case \"lte\":\n return typeof v === \"number\" && v <= condition.value;\n case \"in\":\n return v !== undefined && condition.value.some((c) => jsonEqual(v, c));\n case \"notNull\":\n return v !== undefined && v !== null;\n }\n}\n\n/** Rows a state query selects from the log's last snapshot; undefined when there is no snapshot. */\nexport function queryRows(log: EffectLog, query: StateQuery): readonly Row[] | undefined {\n const tables = lastSnapshot(log, query.target);\n if (!tables) return undefined;\n const rows = tables[query.table] ?? [];\n const where = query.where ?? [];\n return rows.filter((r) => where.every((c) => rowMatches(r, c)));\n}\n\nfunction snapshotSeq(log: EffectLog, target: string): number[] {\n let last: number | undefined;\n for (const e of log.entries) if (e.kind === \"snapshot\" && e.target === target) last = e.seq;\n return last === undefined ? [] : [last];\n}\n\nexport function checkEveryRow(log: EffectLog, inv: EveryRow): Violation | null {\n const rows = queryRows(log, inv.query);\n if (rows === undefined) {\n return {\n invariant: inv.name,\n message: `no snapshot of ${inv.query.target} was recorded`,\n keys: [],\n evidence: [],\n };\n }\n const failing = rows.filter((r) => !inv.holds.every((c) => rowMatches(r, c)));\n if (failing.length === 0) return null;\n const keys = failing.map((r) => canonicalJson(r));\n const shown = keys.slice(0, 3).join(\", \") + (failing.length > 3 ? \", …\" : \"\");\n return {\n invariant: inv.name,\n message: `${failing.length} row(s) of ${inv.query.table} in ${inv.query.target} violate the condition: ${shown}`,\n keys,\n evidence: snapshotSeq(log, inv.query.target),\n };\n}\n\nexport function checkUnique(log: EffectLog, inv: Unique): Violation | null {\n const rows = queryRows(log, inv.query);\n if (rows === undefined) {\n return {\n invariant: inv.name,\n message: `no snapshot of ${inv.query.target} was recorded`,\n keys: [],\n evidence: [],\n };\n }\n const counts = new Map<string, number>();\n for (const r of rows) {\n const v = getPath(r as JsonValue, inv.path);\n if (v === undefined || v === null) continue;\n const k = canonicalJson(v);\n counts.set(k, (counts.get(k) ?? 0) + 1);\n }\n const shared = [...counts].filter(([, n]) => n > 1);\n if (shared.length === 0) return null;\n const shown = shared.map(\n ([k, n]) => `${n} rows of ${inv.query.table} in ${inv.query.target} share ${inv.path} = ${k}`,\n );\n return {\n invariant: inv.name,\n message: shown.join(\"; \"),\n keys: shared.map(([k]) => k),\n evidence: snapshotSeq(log, inv.query.target),\n };\n}\n\nexport function checkImplies(log: EffectLog, inv: Implies): Violation | null {\n const rows = queryRows(log, inv.state);\n if (rows === undefined) {\n return {\n invariant: inv.name,\n message: `no snapshot of ${inv.state.target} was recorded`,\n keys: [],\n evidence: [],\n };\n }\n const present = new Set<string>();\n for (const r of rows) {\n const v = r[inv.column];\n if (v !== undefined) present.add(canonicalJson(v));\n }\n const missing: string[] = [];\n const evidence: number[] = [];\n for (const e of selectEffects(log, inv.when)) {\n const k = keyOf(e, inv.key);\n if (k === undefined || present.has(k)) continue;\n if (!missing.includes(k)) missing.push(k);\n evidence.push(e.seq);\n }\n if (missing.length === 0) return null;\n return {\n invariant: inv.name,\n 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`,\n keys: missing,\n evidence,\n };\n}\n\nexport function checkReferences(log: EffectLog, inv: References): Violation | null {\n const rows = queryRows(log, inv.query);\n const targets = queryRows(log, inv.in);\n for (const [q, r] of [\n [inv.query, rows],\n [inv.in, targets],\n ] as const) {\n if (r === undefined)\n return {\n invariant: inv.name,\n message: `no snapshot of ${q.target} was recorded`,\n keys: [],\n evidence: [],\n };\n }\n const pointedAt = new Set<string>();\n for (const t of targets ?? []) {\n const v = t[inv.column];\n if (v !== undefined && v !== null) pointedAt.add(canonicalJson(v));\n }\n const orphans = new Set<string>();\n for (const r of rows ?? []) {\n const v = getPath(r as JsonValue, inv.path);\n if (v === undefined || v === null) continue;\n const k = canonicalJson(v);\n if (!pointedAt.has(k)) orphans.add(k);\n }\n if (orphans.size === 0) return null;\n const missing = [...orphans];\n return {\n invariant: inv.name,\n 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 ? \", …\" : \"\"}`,\n keys: missing,\n evidence: [...snapshotSeq(log, inv.query.target), ...snapshotSeq(log, inv.in.target)],\n };\n}\n","/**\n * Invariants are plain data describing a property of the effect log; checkers\n * are pure functions from (log, invariant) to a violation or null. The\n * library starts with what the first planted bug needs and grows from there.\n */\n\nimport { canonicalJson, type JsonValue } from \"./canonical-json.ts\";\nimport type { EffectLog } from \"./effect-log.ts\";\nimport { checkRefines, type Refines } from \"./refines.ts\";\nimport { type EffectSelector, getPath, keyOf, selectEffects } from \"./selectors.ts\";\nimport {\n checkEveryRow,\n checkImplies,\n checkReferences,\n checkUnique,\n type EveryRow,\n type Implies,\n type References,\n type Unique,\n} from \"./state.ts\";\n\n/** No two selected effects share the same key. Catches duplicate writes. */\nexport interface AtMostOncePerKey {\n readonly kind: \"atMostOncePerKey\";\n readonly name: string;\n readonly effect: EffectSelector;\n /** Dot path into the payload that identifies the key. */\n readonly key: string;\n}\n\n/** Every expected key appears in at least one selected effect. Catches lost work. */\nexport interface AtLeastOnce {\n readonly kind: \"atLeastOnce\";\n readonly name: string;\n readonly effect: EffectSelector;\n readonly key: string;\n readonly expected: readonly JsonValue[];\n /** Set when `expected` was derived from the drive's message bodies, so it can be re-derived when messages are removed. */\n readonly perMessage?: { readonly bodyKey: string };\n}\n\n/** Re-derive `expected` for per-message invariants from the bodies that remain. */\nexport function recomputePerMessageExpected(\n invariants: readonly Invariant[],\n bodies: readonly JsonValue[],\n): readonly Invariant[] {\n return invariants.map((inv) => {\n if (inv.kind !== \"atLeastOnce\" || !inv.perMessage) return inv;\n const bodyKey = inv.perMessage.bodyKey;\n const expected: JsonValue[] = [];\n for (const b of bodies) {\n const v = getPath(b, bodyKey);\n if (v !== undefined) expected.push(v);\n }\n return { ...inv, expected };\n });\n}\n\nexport type Invariant =\n | AtMostOncePerKey\n | AtLeastOnce\n | EveryRow\n | Implies\n | Unique\n | References\n | Refines;\n\nexport interface Violation {\n readonly invariant: string;\n readonly message: string;\n /** The keys involved, in canonical JSON, so two violations can be compared across runs. */\n readonly keys: readonly string[];\n /** Sequence numbers of the effects that witness the violation. */\n readonly evidence: readonly number[];\n}\n\n/** True when two violations are of the same invariant for the same keys, whatever the traces. */\nexport function sameViolation(a: Violation, b: Violation): boolean {\n return (\n a.invariant === b.invariant &&\n a.keys.length === b.keys.length &&\n a.keys.every((k, i) => k === b.keys[i])\n );\n}\n\nexport function checkInvariant(log: EffectLog, inv: Invariant): Violation | null {\n switch (inv.kind) {\n case \"refines\":\n return checkRefines(log, inv);\n case \"everyRow\":\n return checkEveryRow(log, inv);\n case \"implies\":\n return checkImplies(log, inv);\n case \"unique\":\n return checkUnique(log, inv);\n case \"references\":\n return checkReferences(log, inv);\n case \"atMostOncePerKey\": {\n const seen = new Map<string, number>();\n for (const e of selectEffects(log, inv.effect)) {\n const k = keyOf(e, inv.key);\n if (k === undefined) continue;\n const first = seen.get(k);\n if (first !== undefined) {\n return {\n invariant: inv.name,\n message: `${inv.effect.target} ${inv.effect.op ?? \"*\"} happened twice for key ${k} (seq ${first} and ${e.seq})`,\n keys: [k],\n evidence: [first, e.seq],\n };\n }\n seen.set(k, e.seq);\n }\n return null;\n }\n case \"atLeastOnce\": {\n const present = new Set<string>();\n const selected = selectEffects(log, inv.effect);\n for (const e of selected) {\n const k = keyOf(e, inv.key);\n if (k !== undefined) present.add(k);\n }\n const missing = inv.expected.map((v) => canonicalJson(v)).filter((k) => !present.has(k));\n if (missing.length === 0) return null;\n return {\n invariant: inv.name,\n message: `${inv.effect.target} ${inv.effect.op ?? \"*\"} never happened for key(s) ${missing.join(\", \")}`,\n keys: missing,\n evidence: selected.map((e) => e.seq),\n };\n }\n }\n}\n\nexport function checkInvariants(\n log: EffectLog,\n invariants: readonly Invariant[],\n): readonly Violation[] {\n const out: Violation[] = [];\n for (const inv of invariants) {\n const v = checkInvariant(log, inv);\n if (v) out.push(v);\n }\n return out;\n}\n","/**\n * The scenario spec: everything Eutaxy needs to run one scenario, as plain\n * data. The platform-neutral parts are typed here; what a platform needs to\n * drive the Worker and set up its state travels as `PlatformData`, which only\n * that platform's package knows how to build and interpret.\n */\n\nimport type { JsonValue } from \"./canonical-json.ts\";\nimport type { Invariant } from \"./invariants.ts\";\n\n/** Opaque, JSON-shaped data owned by a platform package. `kind` names its shape. */\nexport interface PlatformData {\n readonly kind: string;\n readonly [key: string]: JsonValue;\n}\n\n/** Where the Worker under test lives, relative to the scenario file. */\nexport interface WorkerRef {\n readonly entry: string;\n readonly config: string;\n}\n\n/** A scripted reply from an external: the first matching entry answers a request. */\nexport interface ScriptedResponse {\n /** HTTP method to match; any when absent. */\n readonly method?: string;\n /** URL path to match exactly, or a prefix when it ends with \"*\"; any when absent. */\n readonly path?: string;\n readonly status: number;\n readonly headers?: { readonly [name: string]: string };\n /** JSON body (sent as application/json) or a string body. */\n readonly body?: JsonValue;\n}\n\n/**\n * An external service the Worker talks to, what it promises, and how it\n * answers. Requests never reach the network: they are answered from\n * `responses`, and an undeclared host makes the run UNSUPPORTED.\n */\nexport interface ExternalDecl {\n readonly name: string;\n /** Host to match exactly, or a suffix pattern such as \"*.example.com\". */\n readonly host: string;\n readonly guarantees: {\n /**\n * Header whose value makes repeated requests idempotent: a request\n * repeating an earlier one's key gets the earlier response and is\n * recorded as not effective.\n */\n readonly dedupeBy?: string;\n };\n /** Omitted: every request gets 200 with an empty body. Present but unmatched: the run is UNSUPPORTED. */\n readonly responses?: readonly ScriptedResponse[];\n}\n\n/** Exploration bounds. Every verdict reports the bounds actually reached. */\nexport interface Bounds {\n readonly maxFaultsPerRun: number;\n readonly maxRedeliveries: number;\n readonly maxConcurrentInvocations: number;\n readonly budgetMs: number;\n}\n\nexport interface ScenarioSpec {\n readonly version: 1;\n readonly name: string;\n /** Which platform package built and runs this scenario, e.g. \"cloudflare\" or \"aws\". Absent means cloudflare. */\n readonly platform?: string;\n readonly worker: WorkerRef;\n /** How the scenario drives the Worker (which events, with what payloads). */\n readonly drive: PlatformData;\n /** State to establish before each run, in order. */\n readonly setup: readonly PlatformData[];\n readonly externals: readonly ExternalDecl[];\n readonly invariants: readonly Invariant[];\n readonly bounds: Bounds;\n /**\n * Modules of pure core functions with specs, relative to the scenario;\n * each module's specs are in the spec file beside it (`domain.ts` has\n * `domain.props.ts`). Calls to the functions with specs are recorded as\n * decisions during exploration, and each property is checked on the\n * inputs seen.\n */\n readonly specs?: readonly string[];\n}\n\nexport const defaultBounds: Bounds = {\n maxFaultsPerRun: 1,\n maxRedeliveries: 2,\n maxConcurrentInvocations: 1,\n budgetMs: 2000,\n};\n\nfunction isPositiveInt(n: unknown): n is number {\n return typeof n === \"number\" && Number.isInteger(n) && n > 0;\n}\n\n/** Every reason a spec is not usable; empty when it is. */\nexport function validateScenario(spec: ScenarioSpec): readonly string[] {\n const errors: string[] = [];\n if (spec.version !== 1) errors.push(`version must be 1, got ${String(spec.version)}`);\n if (!spec.name.trim()) errors.push(\"name must not be empty\");\n if (spec.platform !== undefined && !spec.platform)\n errors.push(\"platform must not be empty when given\");\n if (!/^[a-z0-9][a-z0-9-]*$/.test(spec.name))\n errors.push(`name must be lowercase letters, digits and dashes: ${JSON.stringify(spec.name)}`);\n if (!spec.worker.entry) errors.push(\"worker.entry must not be empty\");\n if (!spec.worker.config) errors.push(\"worker.config must not be empty\");\n if (!spec.drive.kind) errors.push(\"drive.kind must not be empty\");\n spec.setup.forEach((s, i) => {\n if (!s.kind) errors.push(`setup[${i}].kind must not be empty`);\n });\n if (spec.invariants.length === 0) errors.push(\"at least one invariant is required\");\n const names = new Set<string>();\n for (const inv of spec.invariants) {\n if (!inv.name) errors.push(\"every invariant needs a name\");\n else if (names.has(inv.name))\n errors.push(`duplicate invariant name ${JSON.stringify(inv.name)}`);\n names.add(inv.name);\n }\n const specs = new Set<string>();\n for (const m of spec.specs ?? []) {\n if (!m) errors.push(\"every specs entry needs a module path\");\n else if (specs.has(m)) errors.push(`duplicate specs module ${JSON.stringify(m)}`);\n specs.add(m);\n }\n const ext = new Set<string>();\n for (const e of spec.externals) {\n if (!e.name) errors.push(\"every external needs a name\");\n if (ext.has(e.name)) errors.push(`duplicate external ${JSON.stringify(e.name)}`);\n ext.add(e.name);\n if (!e.host) errors.push(`external ${JSON.stringify(e.name)} needs a host`);\n (e.responses ?? []).forEach((r, i) => {\n if (!(Number.isInteger(r.status) && r.status >= 100 && r.status <= 599)) {\n errors.push(\n `external ${JSON.stringify(e.name)} responses[${i}].status must be an HTTP status`,\n );\n }\n });\n }\n for (const k of [\"maxFaultsPerRun\", \"maxRedeliveries\"] as const) {\n const v = spec.bounds[k];\n if (!(Number.isInteger(v) && v >= 0)) errors.push(`bounds.${k} must be a non-negative integer`);\n }\n for (const k of [\"maxConcurrentInvocations\", \"budgetMs\"] as const) {\n if (!isPositiveInt(spec.bounds[k])) errors.push(`bounds.${k} must be a positive integer`);\n }\n return errors;\n}\n","/**\n * Shrinking, the pure part: given a violating schedule and the ids of the\n * events that drove it, the candidates to try next, smallest change first.\n * The engine replays each candidate and keeps it when the same invariant is\n * still violated for the same keys.\n */\n\nimport type { Schedule } from \"./faults.ts\";\n\nexport interface ShrinkState {\n readonly schedule: Schedule;\n readonly keepIds: readonly string[];\n}\n\n/** One-step candidates: each single fault removed, then each single event removed. */\nexport function shrinkCandidates(state: ShrinkState): readonly ShrinkState[] {\n const out: ShrinkState[] = [];\n state.schedule.faults.forEach((_, i) => {\n out.push({\n // Recorded turns stay: a candidate replays the same turn picks as far as they still apply.\n schedule: { ...state.schedule, faults: state.schedule.faults.filter((_, j) => j !== i) },\n keepIds: state.keepIds,\n });\n });\n if (state.keepIds.length > 1) {\n state.keepIds.forEach((id) => {\n out.push({\n schedule: {\n ...state.schedule,\n // Faults that belonged to the removed event's invocations can no longer fire.\n faults: state.schedule.faults.filter((f) => !f.invocation.startsWith(`${id}#`)),\n },\n keepIds: state.keepIds.filter((k) => k !== id),\n });\n });\n }\n return out;\n}\n","/**\n * The one reduction of runtime values to JSON data for the effect log. It\n * never throws and reads the same on every machine (no locale or time zone).\n */\n\nimport type { JsonValue } from \"./canonical-json.ts\";\n\n/** A platform's own encoding of an object, or undefined to use the default. */\nexport type JsonExtra = (value: object) => JsonValue | undefined;\n\nconst maxDepth = 10;\n\n/**\n * Exact for JSON data. Otherwise: -0, NaN and the infinities as strings,\n * bigints as their digits, symbols as `Symbol(s)`, functions as `<function>`, Dates\n * as ISO strings, Sets as arrays, Maps as `[key, value]` pairs, Errors as\n * `Name: message`, byte buffers as `<bytes n>`, other objects by their own\n * enumerable keys; a cycle or nesting deeper than ten as `<nested>`, a\n * property that throws when read as `<unreadable>`. `extra` is tried first\n * on every object.\n */\nexport function toJson(value: unknown, extra?: JsonExtra): JsonValue {\n return walk(value, extra, 0, new Set());\n}\n\nfunction walk(\n value: unknown,\n extra: JsonExtra | undefined,\n depth: number,\n seen: Set<object>,\n): JsonValue {\n if (value === null || value === undefined) return null;\n switch (typeof value) {\n case \"string\":\n case \"boolean\":\n return value;\n case \"number\":\n if (Object.is(value, -0)) return \"-0\";\n return Number.isFinite(value) ? value : String(value);\n case \"bigint\":\n // As D1 parameters and object values have always been logged, so selectors on them keep matching.\n return value.toString();\n case \"symbol\":\n return String(value);\n case \"function\":\n return \"<function>\";\n }\n const object = value as object;\n if (depth > maxDepth || seen.has(object)) return \"<nested>\";\n const own = extra?.(object);\n if (own !== undefined) return own;\n if (object instanceof Date)\n return Number.isNaN(object.getTime()) ? \"Invalid Date\" : object.toISOString();\n if (object instanceof Error) return `${object.name}: ${object.message}`;\n if (object instanceof ArrayBuffer || ArrayBuffer.isView(object))\n return `<bytes ${object.byteLength}>`;\n const next = (v: unknown) => walk(v, extra, depth + 1, seen);\n seen.add(object);\n try {\n // Array.from, not map: a hole reads as undefined, so null, and canonical JSON allows no holes.\n if (Array.isArray(object)) return Array.from(object, next);\n if (object instanceof Set) return [...object].map(next);\n if (object instanceof Map) return [...object].map(([k, v]) => [next(k), next(v)]);\n const out: { [key: string]: JsonValue } = {};\n for (const key of Object.keys(object)) {\n let v: JsonValue;\n try {\n v = next((object as Record<string, unknown>)[key]);\n } catch {\n v = \"<unreadable>\";\n }\n // Defined, not assigned: an own `__proto__` key stays a key.\n Object.defineProperty(out, key, {\n value: v,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n return out;\n } finally {\n seen.delete(object);\n }\n}\n","/**\n * How a run chooses. A run's nondeterminism is a sequence of decisions: a\n * fault (or none) at each effect point that may take one, and the next turn\n * at each scheduling decision of a concurrent run. One object makes them\n * all. Exploring from a seed draws them (`seededChooser`), replaying a\n * schedule looks them up (`replayChooser`), and exhaustive exploration picks\n * them from the enumerator (`exhaustive.ts`), which walks every sequence of\n * choices once. The run only asks; which faults a run may take, how many and\n * where is the chooser's, so the run loop holds no policy.\n */\n\nimport {\n decideFault,\n type FaultKind,\n type FaultPolicy,\n nextInt,\n type Schedule,\n seedPrng,\n} from \"@eutaxy/core\";\n\n/** One option at a decision the run cannot make by itself. */\nexport interface ChoiceOption {\n /** Names the option the same way in every run that reaches it, e.g. \"req-1#1@2\", \"start:0\" or \"crash_after\". */\n readonly label: string;\n /** The invocation the option belongs to: the one a turn continues, or the one whose effect point a fault is at. */\n readonly invocation?: string;\n /** A turn: the target of the effect it performs. */\n readonly target?: string;\n /** A fault: the ordinal of the effect point within its invocation, which a recorded schedule keys on. */\n readonly ordinal?: number;\n}\n\n/**\n * Makes a run's choices: which fault (or none) at an effect point, and which\n * turn next in a concurrent run.\n */\nexport interface Chooser {\n /** The seed of the run's virtual globals (time, randomness), and of every choice drawn rather than made. */\n readonly seed: number;\n /** Whether the turns it picks do not follow the seed, so the schedule must record them for replay. */\n readonly recordsTurns: boolean;\n /**\n * The index of the option taken. A fault decision offers \"none\" first,\n * then the faults the point allows, each option naming the point. A turn\n * decision offers the parked invocations in start order, then starting the\n * next event while a slot is free; it is put to the chooser even with one\n * option (an enumerated run can repeat an explored order there), and the\n * run records the pick only when there was more than one.\n */\n choose(kind: \"fault\" | \"turn\", options: readonly ChoiceOption[]): number;\n}\n\n/** Where a seeded run's faults go. */\nexport interface FaultPlacement extends FaultPolicy {\n /**\n * The eligible points (fault decisions, counted from 0) that take a fault,\n * kinds drawn from the seed (see `planFaults`). Absent: each eligible point\n * takes a fault with probability `faultProbability` (see `decideFault`).\n */\n readonly faultPlan?: readonly number[];\n}\n\n/**\n * Choices drawn from the seed: faults from a stream seeded by it, placed by\n * the plan; turns from a separate stream (`turns:<seed>`), so a fault more\n * or less does not move the picks after it.\n */\nexport function seededChooser(seed: number, placement: FaultPlacement): Chooser {\n let faults = seedPrng(seed);\n let turns = seedPrng(`turns:${seed}`);\n let position = 0;\n let injected = 0;\n return {\n seed,\n recordsTurns: false,\n choose(kind, options) {\n if (kind === \"turn\") {\n if (options.length < 2) return 0;\n const [i, next] = nextInt(turns, options.length);\n turns = next;\n return i;\n }\n if (options.length < 2) return 0;\n const at = position++;\n let i = 0;\n if (placement.faultPlan) {\n if (injected >= placement.maxFaultsPerRun || !placement.faultPlan.includes(at)) return 0;\n const [k, next] = nextInt(faults, options.length - 1);\n faults = next;\n i = k + 1;\n } else {\n // The options past \"none\" are the point's allowed faults, labelled by kind.\n const kinds = options.slice(1).map((o) => o.label as FaultKind);\n const [fault, next] = decideFault(faults, kinds, injected, placement);\n faults = next;\n i = fault === null ? 0 : kinds.indexOf(fault) + 1;\n }\n if (i > 0) injected++;\n return i;\n },\n };\n}\n\n/**\n * Choices a recorded schedule made: its fault at the point (none when it\n * recorded none, or one the point no longer allows), its turns when it\n * recorded them (the run takes one past the options as the first), else the\n * seed's.\n */\nexport function replayChooser(schedule: Schedule): Chooser {\n const recorded = schedule.turns;\n let replayed = 0;\n let turns = seedPrng(`turns:${schedule.seed}`);\n return {\n seed: schedule.seed,\n recordsTurns: recorded !== undefined,\n choose(kind, options) {\n if (kind === \"turn\") {\n if (options.length < 2) return 0;\n if (recorded) {\n return recorded[replayed++] ?? 0;\n }\n const [i, next] = nextInt(turns, options.length);\n turns = next;\n return i;\n }\n if (options.length < 2) return 0;\n const at = options[0];\n const decision = schedule.faults.find(\n (f) => f.invocation === at?.invocation && f.ordinal === at?.ordinal,\n );\n if (!decision) return 0;\n const i = options.findIndex((o) => o.label === decision.fault);\n return Math.max(i, 0);\n },\n };\n}\n\n/**\n * The chooser under the run's fault bound: once it has taken `max` faults,\n * no further fault decision is put to it (the enumerator then sees no\n * choice there).\n */\nexport function limitFaults(chooser: Chooser, max: number): Chooser {\n let injected = 0;\n return {\n seed: chooser.seed,\n recordsTurns: chooser.recordsTurns,\n choose(kind, options) {\n if (kind !== \"fault\") return chooser.choose(kind, options);\n if (injected >= max) return 0;\n const i = chooser.choose(kind, options);\n if (i > 0) injected++;\n return i;\n },\n };\n}\n","/**\n * Async context, where the host has it. Node's AsyncLocalStorage (also in\n * workerd with Node compatibility) follows promise chains, I/O callbacks\n * and continuations, so a value set around a call is visible to every piece\n * of code that call goes on to run, whenever it runs. Reached through\n * `process.getBuiltinModule`, so a host without it still loads the engine.\n */\n\nexport interface AsyncScope<T> {\n run<R>(store: T, fn: () => R): R;\n getStore(): T | undefined;\n}\n\n/** A new async context slot, or null where the host has no AsyncLocalStorage. */\nexport function asyncScope<T>(): AsyncScope<T> | null {\n const mod =\n typeof process !== \"undefined\"\n ? (process?.getBuiltinModule?.(\"node:async_hooks\") as\n | { AsyncLocalStorage?: new () => AsyncScope<T> }\n | undefined)\n : undefined;\n return mod?.AsyncLocalStorage ? new mod.AsyncLocalStorage() : null;\n}\n","/** The one way the engine and its platforms replace a property for a while. */\n\n/**\n * Replace `target[key]` with a value or a getter until the returned\n * function is called, which puts the property back exactly as it was (its\n * descriptor, or no property at all). The replacement is configurable and\n * keeps the original's enumerability. Calling the restore twice is\n * harmless. Throws where the property cannot be redefined.\n */\nexport function patchProperty(\n target: object,\n key: PropertyKey,\n patch: { readonly value: unknown } | { readonly get: () => unknown },\n): () => void {\n const saved = Object.getOwnPropertyDescriptor(target, key);\n const enumerable = saved?.enumerable ?? false;\n Object.defineProperty(\n target,\n key,\n \"get\" in patch\n ? { get: patch.get, configurable: true, enumerable }\n : { value: patch.value, writable: true, configurable: true, enumerable },\n );\n let restored = false;\n return () => {\n if (restored) return;\n restored = true;\n if (saved) Object.defineProperty(target, key, saved);\n else Reflect.deleteProperty(target, key);\n };\n}\n","/**\n * The virtual clock and the globals patch. Within a run, Date, Math.random,\n * crypto.randomUUID, crypto.getRandomValues, performance.now and the timer\n * functions are replaced by deterministic versions driven by the run's seed\n * and by a clock that starts at a fixed epoch and advances only when the\n * engine says so: one millisecond per effect, and to each timer's due time\n * when the timer fires. Timers fire only while the invocation is idle (no\n * effect in flight), in due order, so they never race real I/O.\n */\n\nimport { nextFloat, nextU32, type PrngState, seedPrng } from \"@eutaxy/core\";\nimport { asyncScope } from \"./context.ts\";\nimport { patchProperty } from \"./patch.ts\";\n\n/** 2026-01-01T00:00:00.000Z. Every run starts here. */\nexport const virtualEpoch = Date.UTC(2026, 0, 1);\n\n/** Virtual time advances this much at each effect completion. */\nexport const effectLatencyMs = 1;\n\n// Captured before any patching, so the engine can yield to the real event loop.\nconst realSetTimeout = globalThis.setTimeout.bind(globalThis);\nconst realSetInterval = globalThis.setInterval.bind(globalThis);\nconst realClearTimeout = globalThis.clearTimeout.bind(globalThis);\nconst realClearInterval = globalThis.clearInterval.bind(globalThis);\n\n/**\n * Tells library code apart from handler code while an effect's real I/O runs.\n * SDKs back off and time out with timers, which must be real; a handler timer\n * scheduled meanwhile must stay virtual. Node's AsyncLocalStorage follows the\n * library's promise chains and I/O callbacks but not the handler's own\n * continuations. Where it is unavailable (workerd without Node compatibility)\n * every timer stays virtual; the Cloudflare bindings do not use timers.\n */\nconst libraryScope = asyncScope<boolean>();\n\ninterface Timer {\n readonly id: number;\n due: number;\n readonly callback: (...args: unknown[]) => void;\n readonly args: readonly unknown[];\n readonly interval: number | null;\n /** The invocation that scheduled it; cancelled with that invocation when it crashes. */\n readonly owner: string | null;\n}\n\nexport class VirtualClock {\n private time = virtualEpoch;\n private timers: Timer[] = [];\n private nextId = 1;\n /** The invocation whose code is running; timers scheduled now belong to it. */\n owner: string | null = null;\n /** Set by a concurrent run: who is running, asked when a timer is scheduled (overrides `owner`). */\n ownerNow: (() => string | null) | null = null;\n /** Set by a concurrent run: binds a callback to the async context it was scheduled in. */\n bind: ((callback: (...args: unknown[]) => void) => (...args: unknown[]) => void) | null = null;\n\n now(): number {\n return this.time;\n }\n\n advance(ms: number): void {\n if (ms > 0) this.time += ms;\n }\n\n private schedule(\n callback: (...args: unknown[]) => void,\n delay: number,\n args: readonly unknown[],\n interval: number | null,\n ): number {\n const ms = Number.isFinite(delay) && delay > 0 ? Math.floor(delay) : 0;\n const timer: Timer = {\n id: this.nextId++,\n due: this.time + ms,\n callback: this.bind ? this.bind(callback) : callback,\n args,\n interval,\n owner: this.ownerNow ? this.ownerNow() : this.owner,\n };\n this.timers.push(timer);\n return timer.id;\n }\n\n setTimeout(callback: (...args: unknown[]) => void, delay = 0, ...args: unknown[]): number {\n return this.schedule(callback, delay, args, null);\n }\n\n setInterval(callback: (...args: unknown[]) => void, delay = 0, ...args: unknown[]): number {\n return this.schedule(callback, delay, args, Math.max(1, Math.floor(delay)));\n }\n\n clear(id: number): void {\n this.timers = this.timers.filter((t) => t.id !== id);\n }\n\n /** Whether this clock issued the handle (and the timer is still pending). */\n owns(id: unknown): id is number {\n return typeof id === \"number\" && this.timers.some((t) => t.id === id);\n }\n\n pendingTimers(): number {\n return this.timers.length;\n }\n\n /** Drop every timer an invocation scheduled: a crashed invocation's code must never run again. */\n cancelOwner(owner: string): void {\n this.timers = this.timers.filter((t) => t.owner !== owner);\n }\n\n private earliest(): Timer | undefined {\n let earliest = this.timers[0];\n for (const t of this.timers)\n if (earliest && (t.due < earliest.due || (t.due === earliest.due && t.id < earliest.id)))\n earliest = t;\n return earliest;\n }\n\n /** When the next timer is due, or undefined when none is pending. */\n nextDue(): number | undefined {\n return this.earliest()?.due;\n }\n\n /** Who set the timer `fireNext` would run: an invocation, null for none, undefined when no timer is pending. */\n nextOwner(): string | null | undefined {\n return this.earliest()?.owner;\n }\n\n /** Advance to the earliest due timer and run it. False when none is pending. */\n fireNext(): boolean {\n const earliest = this.earliest();\n if (!earliest) return false;\n if (earliest.due > this.time) this.time = earliest.due;\n if (earliest.interval === null) this.timers = this.timers.filter((t) => t !== earliest);\n else earliest.due = this.time + earliest.interval;\n try {\n earliest.callback(...earliest.args);\n } catch {\n // An exception in a timer callback is uncaught in the real runtime too; it does not stop the run.\n }\n return true;\n }\n}\n\n/** Deterministic randomness for a run: Math.random, UUIDs and random bytes from one seeded stream. */\nexport class VirtualRandom {\n private state: PrngState;\n\n constructor(seed: number | string) {\n this.state = seedPrng(`random:${seed}`);\n }\n\n float(): number {\n const [f, next] = nextFloat(this.state);\n this.state = next;\n return f;\n }\n\n u32(): number {\n const [u, next] = nextU32(this.state);\n this.state = next;\n return u;\n }\n\n fill<T extends ArrayBufferView>(view: T): T {\n const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);\n for (let i = 0; i < bytes.length; i += 4) {\n const u = this.u32();\n for (let j = 0; j < 4 && i + j < bytes.length; j++) bytes[i + j] = (u >>> (8 * j)) & 0xff;\n }\n return view;\n }\n\n /** A version-4 UUID from the stream. */\n uuid(): string {\n const b = this.fill(new Uint8Array(16));\n b[6] = ((b[6] as number) & 0x0f) | 0x40;\n b[8] = ((b[8] as number) & 0x3f) | 0x80;\n const hex = [...b].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n }\n}\n\nexport interface Patched {\n readonly clock: VirtualClock;\n readonly random: VirtualRandom;\n /**\n * Reads of the shared virtual state, by any code: the time (Date,\n * performance.now, scheduling a virtual timer) and the random stream. Code that reads them can tell orders of other invocations' turns\n * apart; the counter is the run's to reset.\n */\n readonly reads: { count: number };\n /** Put every global back. Safe to call twice. */\n restore(): void;\n /**\n * Run an effect's real I/O: timers the library schedules inside it are\n * real (backoff, timeouts); timers the handler schedules meanwhile stay\n * virtual. The clock, Date and randomness stay virtual throughout.\n */\n libraryIo<T>(perform: () => Promise<T>): Promise<T>;\n /** Run handler code inside an effect's I/O (a called Worker's code inside the call): its timers are virtual again. */\n handlerCode<T>(work: () => Promise<T>): Promise<T>;\n}\n\ntype Global = Record<string, unknown>;\n\n/** Web Crypto's asynchronous methods: real work that always finishes on its own. */\nconst subtleMethods = [\n \"encrypt\",\n \"decrypt\",\n \"sign\",\n \"verify\",\n \"digest\",\n \"generateKey\",\n \"deriveKey\",\n \"deriveBits\",\n \"importKey\",\n \"exportKey\",\n \"wrapKey\",\n \"unwrapKey\",\n] as const;\n\nexport interface PatchOptions {\n /**\n * Called with the promise of every host call that is real asynchronous\n * work but not an effect (Web Crypto), so the run can wait for it like\n * I/O instead of guessing when it is done.\n */\n readonly trackIo?: <T>(work: Promise<T>) => Promise<T>;\n}\n\n/** Replace the nondeterministic globals for one run. Returns the handle that restores them. */\nexport function patchGlobals(seed: number | string, options: PatchOptions = {}): Patched {\n const clock = new VirtualClock();\n const random = new VirtualRandom(seed);\n const reads = { count: 0 };\n const inLibrary = () => libraryScope?.getStore() === true;\n /** Counts a read of the shared virtual state, an effect's own I/O included: its result may depend on it. */\n const read = (): void => {\n reads.count++;\n };\n const g = globalThis as unknown as Global;\n const undo: (() => void)[] = [];\n const define = (target: object, key: string, value: unknown): void => {\n undo.push(patchProperty(target, key, { value }));\n };\n\n const RealDate = Date;\n const VirtualDate = function (this: unknown, ...args: unknown[]): unknown {\n if (new.target === undefined || args.length === 0) read();\n if (new.target === undefined) return new RealDate(clock.now()).toString();\n return Reflect.construct(RealDate, args.length === 0 ? [clock.now()] : args, new.target);\n } as unknown as DateConstructor;\n Object.setPrototypeOf(VirtualDate, RealDate);\n Object.defineProperty(VirtualDate, \"prototype\", { value: RealDate.prototype, writable: false });\n Object.defineProperty(VirtualDate, \"now\", {\n value: () => {\n read();\n return clock.now();\n },\n configurable: true,\n writable: true,\n });\n Object.defineProperty(VirtualDate, \"name\", { value: \"Date\" });\n\n define(g, \"Date\", VirtualDate);\n define(Math, \"random\", () => {\n read();\n return random.float();\n });\n // A virtual timer's due time is read from the clock when it is scheduled.\n define(g, \"setTimeout\", (cb: (...a: unknown[]) => void, ms?: number, ...args: unknown[]) => {\n if (inLibrary()) return realSetTimeout(cb, ms, ...args);\n read();\n return clock.setTimeout(cb, ms, ...args);\n });\n define(g, \"setInterval\", (cb: (...a: unknown[]) => void, ms?: number, ...args: unknown[]) => {\n if (inLibrary()) return realSetInterval(cb, ms, ...args);\n read();\n return clock.setInterval(cb, ms, ...args);\n });\n // Clearing dispatches on the handle: a virtual timer cancelled from library code, or a real\n // one cancelled from handler code, each reach the implementation that owns it.\n define(g, \"clearTimeout\", (id?: unknown) => {\n if (clock.owns(id)) clock.clear(id);\n else realClearTimeout(id as Parameters<typeof realClearTimeout>[0]);\n });\n define(g, \"clearInterval\", (id?: unknown) => {\n if (clock.owns(id)) clock.clear(id);\n else realClearInterval(id as Parameters<typeof realClearInterval>[0]);\n });\n const perf = g[\"performance\"];\n if (perf && typeof perf === \"object\")\n define(perf, \"now\", () => {\n read();\n return clock.now() - virtualEpoch;\n });\n const cryptoObj = g[\"crypto\"];\n if (cryptoObj && typeof cryptoObj === \"object\") {\n define(cryptoObj, \"randomUUID\", () => {\n read();\n return random.uuid();\n });\n define(cryptoObj, \"getRandomValues\", <T extends ArrayBufferView>(view: T) => {\n read();\n return random.fill(view);\n });\n const subtle = (cryptoObj as { subtle?: Record<string, unknown> }).subtle;\n const trackIo = options.trackIo;\n if (trackIo && subtle && typeof subtle === \"object\") {\n for (const name of subtleMethods) {\n const real = subtle[name];\n if (typeof real !== \"function\") continue;\n define(subtle, name, function (this: unknown, ...args: unknown[]) {\n return trackIo(Promise.resolve(real.apply(this, args)));\n });\n }\n }\n }\n\n let restored = false;\n return {\n clock,\n random,\n reads,\n libraryIo<T>(perform: () => Promise<T>): Promise<T> {\n return libraryScope ? libraryScope.run(true, perform) : perform();\n },\n handlerCode<T>(work: () => Promise<T>): Promise<T> {\n return libraryScope ? libraryScope.run(false, work) : work();\n },\n restore() {\n if (restored) return;\n restored = true;\n for (const u of undo.reverse()) u();\n },\n };\n}\n\n/** The longest timeout hosts accept: 2^31 - 1 ms. */\nconst maxTimeoutMs = 2 ** 31 - 1;\n\n/** A real-time deadline: `expired` resolves after `ms` unless cancelled first. */\nexport function realDeadline(ms: number): { readonly expired: Promise<\"expired\">; cancel(): void } {\n let handle: ReturnType<typeof realSetTimeout> | undefined;\n const expired = new Promise<\"expired\">((resolve) => {\n // Hosts fire a timeout above this after 1 ms; the longest they can wait (about 24.8 days) is as good as never.\n handle = realSetTimeout(() => resolve(\"expired\"), Math.min(ms, maxTimeoutMs));\n });\n return { expired, cancel: () => realClearTimeout(handle) };\n}\n\n/** Yield to the real event loop so microtasks and pending I/O can make progress. */\nexport function realTick(): Promise<void> {\n return new Promise((resolve) => realSetTimeout(() => resolve(), 0));\n}\n\n// Not in every host's types, so looked up loosely; captured before any patching.\nconst hostSetImmediate = (globalThis as { setImmediate?: (callback: () => void) => unknown })\n .setImmediate;\n// workerd names itself in `navigator.userAgent` (Cloudflare, Compatibility flags: Global navigator,\n// on by default since 2022-03-21) and is the host with `WebSocketPair` (Cloudflare, WebSockets).\nconst hostAgent = (globalThis as { navigator?: { userAgent?: unknown } }).navigator?.userAgent;\nconst inWorkerd =\n hostAgent === \"Cloudflare-Workers\" ||\n typeof (globalThis as { WebSocketPair?: unknown }).WebSocketPair === \"function\";\n\n/**\n * A turn of the real event loop without a timer's delay, where the host\n * gives one cheaply: Node's `setImmediate` (microseconds), after which every\n * pending microtask has run and I/O callbacks that were due have been\n * delivered. Null in workerd, which has `setImmediate` too but runs it as a\n * timer, about a millisecond like `setTimeout(0)`, and where nothing else\n * reaches the event loop (streams, bodies, message ports, crypto and the\n * cache all resolve without a turn of it), so a zero timer is the turn.\n * Measured in the Cloudflare Vitest pool (workerd 1.2026-10, 2026-10-30),\n * not documented: a workerd whose `setImmediate` became cheap would only\n * run slower here, never wrong.\n */\nexport const cheapEventLoopTurn: (() => Promise<void>) | null =\n hostSetImmediate && !inWorkerd\n ? () => new Promise((resolve) => hostSetImmediate.call(globalThis, () => resolve()))\n : null;\n\n/** One turn of the real event loop: the cheap one where the host has it, else a zero timer. */\nexport function eventLoopTurn(): Promise<void> {\n return cheapEventLoopTurn ? cheapEventLoopTurn() : realTick();\n}\n\nexport interface SettleContext {\n readonly clock: VirtualClock;\n /** Effects currently performing real I/O. */\n readonly inFlight: () => number;\n /** True once the invocation has been crashed; the promise is then abandoned. */\n readonly crashed: () => boolean;\n /** Called when nothing can make progress: no I/O, no timers, not done. */\n readonly stuck: () => void;\n}\n\n/**\n * Wait for a promise under the virtual clock: while it is pending, let real\n * I/O complete, and when the invocation is idle fire the next due timer.\n */\nexport async function settleOn<T>(promise: Promise<T>, ctx: SettleContext): Promise<T> {\n let done = false;\n let failed = false;\n let value: T | undefined;\n let error: unknown;\n const tracked = promise.then(\n (v) => {\n done = true;\n value = v;\n },\n (e: unknown) => {\n done = true;\n failed = true;\n error = e;\n },\n );\n for (;;) {\n await Promise.race([tracked, realTick()]);\n if (done) {\n if (failed) throw error;\n return value as T;\n }\n if (ctx.crashed()) return new Promise<T>(() => {});\n if (ctx.inFlight() > 0) continue;\n if (ctx.clock.fireNext()) continue;\n ctx.stuck();\n return new Promise<T>(() => {});\n }\n}\n","/**\n * Scripted outbound fetch. During a run, `fetch` is replaced by a function\n * that answers from the scenario's declared externals instead of the\n * network. Each request is an effect point (with every fault available) when\n * run hooks are given; without hooks it is the same scripted behaviour with\n * no recording, which the differential's raw side uses.\n *\n * An external that declares `dedupeBy` remembers the first response per key\n * for the run: a repeated key gets that response back and is recorded as\n * not effective. A request to an undeclared host, or one no scripted\n * response answers, makes the run unsupported.\n */\n\nimport {\n type ExternalDecl,\n type JsonValue,\n type RunHooks,\n type ScriptedResponse,\n writeFaults,\n} from \"@eutaxy/core\";\nimport { patchProperty } from \"./patch.ts\";\n\nexport interface FetchHooks {\n readonly hooks: RunHooks;\n readonly invocation: () => string;\n}\n\n/** Match a host against an exact host or a \"*.suffix\" pattern. */\nexport function hostMatches(pattern: string, host: string): boolean {\n if (pattern.startsWith(\"*.\")) {\n const suffix = pattern.slice(1); // \".example.com\"\n return host.endsWith(suffix) && host.length > suffix.length;\n }\n return pattern === host;\n}\n\nexport function findExternal(\n externals: readonly ExternalDecl[],\n host: string,\n): ExternalDecl | undefined {\n return externals.find((e) => hostMatches(e.host, host));\n}\n\nexport function findResponse(\n external: ExternalDecl,\n method: string,\n path: string,\n): ScriptedResponse | undefined | null {\n if (!external.responses) return null; // null: no script at all, default reply\n return external.responses.find((r) => {\n if (r.method && r.method.toUpperCase() !== method) return false;\n if (r.path === undefined) return true;\n return r.path.endsWith(\"*\") ? path.startsWith(r.path.slice(0, -1)) : r.path === path;\n });\n}\n\n/** A scripted reply, ready to become a Response: lower-cased header names, the body as text. */\nexport interface Reply {\n readonly status: number;\n readonly headers: { readonly [name: string]: string };\n readonly body: string;\n}\n\nconst REDIRECTS = new Set([301, 302, 303, 307, 308]);\n\n/** Whether a status is a redirect `fetch` would follow unless told `redirect: \"manual\"`. */\nexport function isRedirect(status: number): boolean {\n return REDIRECTS.has(status);\n}\n\n/** The reply a scripted response stands for; `null` is the default reply, 200 with an empty body. */\nexport function replyOf(r: ScriptedResponse | null): Reply {\n if (r === null) return { status: 200, headers: {}, body: \"\" };\n const json = r.body !== undefined && typeof r.body !== \"string\";\n const headers: Record<string, string> = {};\n for (const [name, value] of Object.entries(r.headers ?? {})) headers[name.toLowerCase()] = value;\n if (json && !(\"content-type\" in headers)) headers[\"content-type\"] = \"application/json\";\n const body = r.body === undefined ? \"\" : json ? JSON.stringify(r.body) : (r.body as string);\n return { status: r.status, headers, body };\n}\n\nexport function toResponse(reply: Reply): Response {\n return new Response(reply.body === \"\" ? null : reply.body, {\n status: reply.status,\n headers: reply.headers,\n });\n}\n\n/** A request or reply body as effect-log data: JSON when it parses, the text otherwise, null when empty. */\nexport function parseBody(text: string): JsonValue {\n if (text === \"\") return null;\n try {\n return JSON.parse(text) as JsonValue;\n } catch {\n return text;\n }\n}\n\nexport interface ScriptedFetch {\n readonly fetch: typeof fetch;\n /** Replies already given per external and dedupe key, for the run. */\n readonly dedupe: Map<string, Reply>;\n}\n\n/**\n * Build the replacement `fetch`. With `hooks`, every request is an effect\n * point recorded as `Fetch:<external>` with the method as op; the result\n * summary carries `status`, `effective` and the dedupe key.\n */\nexport function createScriptedFetch(\n externals: readonly ExternalDecl[],\n hooks: FetchHooks | null,\n unsupported: (reason: string) => void,\n /** Called after each answered request without hooks, e.g. to advance a clock the way an effect would. */\n afterRequest: () => void = () => {},\n): ScriptedFetch {\n const dedupe = new Map<string, Reply>();\n\n const scripted = (async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n const request = new Request(input, init);\n const url = new URL(request.url);\n const method = request.method.toUpperCase();\n const external = findExternal(externals, url.host);\n if (!external) {\n unsupported(\n `fetch to undeclared host ${url.host}; declare it as an external in the scenario`,\n );\n throw new TypeError(`fetch failed: ${url.host} is not a declared external`);\n }\n const headers: Record<string, string> = {};\n request.headers.forEach((value, name) => {\n headers[name.toLowerCase()] = value;\n });\n const dedupeHeader = external.guarantees.dedupeBy?.toLowerCase();\n const dedupeKey = dedupeHeader ? (headers[dedupeHeader] ?? null) : null;\n const body = parseBody(await request.text());\n const args: JsonValue = { url: request.url, method, headers, body, dedupeKey };\n\n const perform = async (): Promise<{ reply: Reply; effective: boolean }> => {\n const memo = dedupeKey === null ? null : `${external.name}\\u0000${dedupeKey}`;\n if (memo !== null) {\n const earlier = dedupe.get(memo);\n if (earlier) return { reply: earlier, effective: false };\n }\n const script = findResponse(external, method, url.pathname);\n if (script === undefined) {\n unsupported(\n `no scripted response in external ${external.name} for ${method} ${url.pathname}`,\n );\n throw new TypeError(`fetch failed: no scripted response for ${method} ${url.pathname}`);\n }\n const reply = replyOf(script);\n if (isRedirect(reply.status) && request.redirect !== \"manual\") {\n unsupported(\n `external ${external.name} answers ${method} ${url.pathname} with a ${reply.status} redirect; script the final reply or fetch with redirect: \"manual\"`,\n );\n throw new TypeError(\n `fetch failed: redirects are not modelled (${reply.status} from ${url.host})`,\n );\n }\n if (memo !== null) dedupe.set(memo, reply);\n return { reply, effective: true };\n };\n\n if (!hooks) {\n const { reply } = await perform();\n afterRequest();\n return toResponse(reply);\n }\n const { reply } = await hooks.hooks.effect(\n {\n invocation: hooks.invocation(),\n target: `Fetch:${external.name}`,\n op: method,\n args,\n allowed: writeFaults,\n },\n perform,\n (r) => ({ status: r.reply.status, effective: r.effective, dedupeKey }),\n );\n return toResponse(reply);\n }) as typeof fetch;\n\n return { fetch: scripted, dedupe };\n}\n\n/** Replace the global `fetch` for a run; returns the function that restores it. */\nexport function installScriptedFetch(\n externals: readonly ExternalDecl[],\n hooks: FetchHooks | null,\n unsupported: (reason: string) => void,\n afterRequest?: () => void,\n): () => void {\n const { fetch: scripted } = createScriptedFetch(externals, hooks, unsupported, afterRequest);\n return patchProperty(globalThis, \"fetch\", { value: scripted });\n}\n\n/**\n * Run platform work (a reset, a snapshot) with no network: `fetch` rejects\n * while it runs. Reports whether anything tried, so code that runs outside\n * the simulation (an object's constructor during a reset) cannot reach the\n * network unseen.\n */\nexport async function withoutNetwork<T>(\n work: () => Promise<T>,\n): Promise<{ readonly value: T; readonly requested: boolean }> {\n let requested = false;\n const restore = patchProperty(globalThis, \"fetch\", {\n value: async () => {\n requested = true;\n throw new TypeError(\"network access is blocked while Eutaxy resets or snapshots state\");\n },\n });\n try {\n return { value: await work(), requested };\n } finally {\n restore();\n }\n}\n","/**\n * Effects being performed, and what is in flight. An effect made inside\n * another's perform (an object calling out during a call) is nested in it;\n * a hosting effect (`hostsEffects`) runs user code that makes effects of its\n * own. The in-flight count is what the settle loop and the concurrent\n * scheduler wait on: real I/O pending, minus hosting effects that are only\n * waiting on parked effects of their own.\n */\n\nimport type { EffectOptions } from \"@eutaxy/core\";\nimport { asyncScope } from \"./context.ts\";\n\n/**\n * An effect being performed. An effect made inside it is nested in it; when\n * a crash is injected there, the nested effect hangs like any crashed\n * effect and tells this frame, so the enclosing effect ends too. User code\n * never sees the crash as an error it could catch.\n */\nexport class Frame {\n /** The invocation whose effect this is. */\n readonly invocation: string;\n /** Whether the effect hosts user code that makes effects of its own (`hostsEffects`). */\n readonly hosts: boolean;\n /** False once the effect's perform has ended. */\n active = true;\n /** The effect's `onAbandon`, called where the crash happens (inside the hosted code's context). */\n private readonly onAbandon: (() => void) | undefined;\n /** The effect's `mayPark`: whether an effect its hosted code makes may wait for a turn now. */\n readonly mayPark: () => boolean;\n /** The hosting effect this one was made inside of and waited for a turn under, if any. */\n parent: Frame | undefined;\n /** Effects the hosted code made that are parked or running now. */\n children = 0;\n /** Of those, the ones parked, or running but only waiting on parked effects of their own. */\n waitingChildren = 0;\n private abandoned = false;\n private wake: () => void = () => {};\n readonly crashed = new Promise<\"nested_crash\">((resolve) => {\n this.wake = () => resolve(\"nested_crash\");\n });\n constructor(invocation: string, hosts: boolean, options: EffectOptions) {\n this.invocation = invocation;\n this.hosts = hosts;\n this.onAbandon = options.onAbandon;\n this.mayPark = options.mayPark ?? (() => true);\n }\n\n /** Its hosted code is only waiting on effects of its own that are parked (however deep). */\n isWaiting(): boolean {\n return this.children > 0 && this.waitingChildren === this.children;\n }\n\n crash(): void {\n this.abandon();\n this.wake();\n }\n\n abandon(): void {\n if (this.abandoned) return;\n this.abandoned = true;\n this.onAbandon?.();\n }\n}\n\n/** The frame of the effect whose `perform` the current code runs inside. */\nexport const effectScope = asyncScope<Frame>();\n\n/** One run's frames and in-flight count. */\nexport class Frames {\n /** Real I/O pending: effects being performed and tracked work, less hosting effects only waiting. */\n inFlight = 0;\n /** Effects being performed, innermost last (the nesting test where there is no async context). */\n private readonly stack: Frame[] = [];\n /** Per invocation, its effects with `hostsEffects` being performed, innermost last. */\n private readonly hosting = new Map<string, Frame[]>();\n /** Effects with `hostsEffects` being performed now, across invocations. */\n private hostingCount = 0;\n\n /** How many effects with `hostsEffects` are being performed now: above 0, hosted code may be running. */\n get hostingNow(): number {\n return this.hostingCount;\n }\n\n /**\n * The effect an invocation's new effect is made inside of, if any. Async\n * context tells exactly which code is inside; an invocation merely woken\n * meanwhile is not. A hosting effect's own effects are attributed to its\n * invocation: only those count as nested. Async context can be stale (code\n * resumed in the context of an effect that has ended, as an object's code\n * may run in the context it was built in): trust only a live frame of the\n * same invocation (the innermost), else the invocation's own hosting effect.\n */\n enclosing(invocation: string): Frame | undefined {\n const store = effectScope?.getStore();\n const live = store?.active && store.invocation === invocation ? store : undefined;\n return effectScope ? (live ?? this.hosting.get(invocation)?.at(-1)) : this.stack.at(-1);\n }\n\n /**\n * The effect whose perform the current code runs inside, whatever\n * invocation it belongs to: the live frame of the async context, else the\n * innermost being performed. Where another invocation's code is hosted.\n */\n current(): Frame | undefined {\n if (!effectScope) return this.stack.at(-1);\n const store = effectScope.getStore();\n return store?.active ? store : undefined;\n }\n\n /** An effect starts being performed: it is in flight. */\n enter(frame: Frame): void {\n this.inFlight++;\n this.stack.push(frame);\n if (frame.hosts) {\n this.hostingFrames(frame.invocation).push(frame);\n this.hostingCount++;\n }\n }\n\n /** An effect's perform has ended. */\n leave(frame: Frame): void {\n if (frame.hosts) {\n const hosted = this.hostingFrames(frame.invocation);\n hosted.splice(hosted.lastIndexOf(frame), 1);\n this.hostingCount--;\n }\n this.stack.splice(this.stack.lastIndexOf(frame), 1);\n // A frame only waiting on parked effects already counts as not in flight, and as waiting for\n // its parent: undo both as it ends.\n if (!frame.isWaiting()) this.inFlight--;\n else if (frame.parent) {\n const parent = frame.parent;\n this.adjust(parent, () => parent.waitingChildren--);\n }\n frame.active = false;\n frame.parent = undefined;\n }\n\n /**\n * Change a hosting frame's children and keep `inFlight` in step: a frame\n * counts in flight unless it is only waiting on parked effects of its own,\n * and a frame that starts or stops waiting does so for its parent too.\n */\n adjust(frame: Frame, change: () => void): void {\n const before = frame.isWaiting();\n change();\n const after = frame.isWaiting();\n if (before === after) return;\n if (frame.active) this.inFlight += after ? -1 : 1;\n const parent = frame.parent;\n if (frame.active && parent)\n this.adjust(parent, () => (parent.waitingChildren += after ? 1 : -1));\n }\n\n private hostingFrames(invocation: string): Frame[] {\n let frames = this.hosting.get(invocation);\n if (!frames) {\n frames = [];\n this.hosting.set(invocation, frames);\n }\n return frames;\n }\n}\n","/**\n * The concurrent scheduler. Each asynchronous effect of a concurrent run is\n * a turn: the invocation parks there, and once every invocation has parked,\n * finished or gone idle the run's chooser picks which parked one goes next\n * (or whether a new event starts). It also tracks whether turns told apart\n * by their parked effects' targets may not commute, which partial-order\n * reduction needs.\n *\n * Between turns the run waits for the code it released to come to rest\n * (`quiesce`): progress (a park, a delivery's end, real I/O completing)\n * wakes it, and before it decides every continuation that progress set off\n * has run, which takes one turn of the host's event loop: `setImmediate`\n * where that is cheap (Node), else the real zero timer the wait armed, which\n * also polls for the moves of hosted code, which cannot wake it, and gives\n * code waiting on something it cannot see its allowance. One such turn per\n * decision is the floor in workerd, where a zero timer is the only way to\n * the event loop and costs about a millisecond.\n */\n\nimport type { ChoiceOption, Chooser } from \"./chooser.ts\";\nimport { cheapEventLoopTurn, realDeadline } from \"./clock.ts\";\nimport type { Frame, Frames } from \"./frames.ts\";\n\n/** What the scheduler needs of an invocation. */\nexport interface Turner {\n readonly id: string;\n /** Times it has parked for a turn; names its next turn the same in every run. */\n parks: number;\n isCrashed(): boolean;\n}\n\ninterface Parked {\n readonly inv: Turner;\n readonly seq: number;\n readonly go: () => void;\n /** For hosted code's effects: the hosting effect, waiting on this one meanwhile. */\n readonly host?: Frame;\n /** The turn as a choice: its label and the target of the effect it performs. */\n readonly option: ChoiceOption;\n}\n\nexport class Turns {\n private readonly chooser: Chooser;\n private readonly frames: Frames;\n /** Makes an invocation the running one. */\n private readonly runAs: (id: string | null) => void;\n /** The virtual globals' read counter, when they are installed. */\n private readonly reads: () => { count: number } | undefined;\n /** Invocations waiting at an effect for their turn. */\n private parked: Parked[] = [];\n private parkSeq = 0;\n /** The turns picked at decisions with more than one option, in order (see Schedule.turns). */\n private readonly picked: number[] = [];\n /** Events started so far, to name the next start the same in every run. */\n private starts = 0;\n /** The target of the turn running since the last decision; null for an event's start or none. */\n private turnTarget: string | null = null;\n private commuteNot = false;\n /** Woken whenever an invocation parks, a delivery ends or I/O completes (see `progressed`). */\n private progressWaiters: (() => void)[] = [];\n /** Times something moved, hosted code's moves included, and the count the last wait or step saw. */\n private moves = 0;\n private seenMoves = 0;\n /** Parks and delivery ends so far, and the count when the current step began. */\n private rests = 0;\n private restsAtStep = 0;\n /** The order invocations started in, which orders the parked ones. */\n private readonly startOrder = new Map<string, number>();\n\n constructor(\n chooser: Chooser,\n frames: Frames,\n runAs: (id: string | null) => void,\n reads: () => { count: number } | undefined,\n ) {\n this.chooser = chooser;\n this.frames = frames;\n this.runAs = runAs;\n this.reads = reads;\n }\n\n /** The turns picked so far, as a copy. */\n get picks(): readonly number[] {\n return [...this.picked];\n }\n\n /** An invocation started; its start orders its parked turns against others'. */\n started(id: string): void {\n this.startOrder.set(id, this.startOrder.size);\n }\n\n /** Park an invocation at an effect until `takeTurn` releases it with `go`. */\n park(inv: Turner, target: string, go: () => void, host?: Frame): void {\n const option = { label: `${inv.id}@${inv.parks++}`, invocation: inv.id, target };\n this.parked.push({ inv, seq: this.parkSeq++, go, option, ...(host ? { host } : {}) });\n this.rested();\n }\n\n /** See `Run.rested`. */\n rested(): void {\n this.rests++;\n this.progressed();\n }\n\n /**\n * A step begins: a turn is released, an event starts or a timer fires.\n * `quiesce` then waits for what the step set off to come to rest. Called\n * by `takeTurn` and, for timers, by the run.\n */\n step(): void {\n this.restsAtStep = this.rests;\n this.seenMoves = this.moves;\n }\n\n /** See `Run.turnsMayNotCommute`. */\n get mayNotCommute(): boolean {\n this.endSegment();\n return this.commuteNot;\n }\n\n /** See `Run.queuedEvents`. */\n queuedEvents(): void {\n if (this.turnTarget !== null) this.commuteNot = true;\n }\n\n /** An effect was performed: within a turn, one on another target is shared with other turns. */\n performed(target: string): void {\n if (this.turnTarget !== null && target !== this.turnTarget) this.commuteNot = true;\n }\n\n /** Close the code run since the last decision, noting whether a turn read the shared virtual state. */\n private endSegment(): void {\n const reads = this.reads();\n if (!reads) return;\n if (this.turnTarget !== null && reads.count > 0) this.commuteNot = true;\n reads.count = 0;\n }\n\n /** See `Run.progressed`. */\n progressed(): void {\n this.moves++;\n // While hosted code runs (a Durable Object call), a wake could come from inside it, and the\n // scheduler would resume in that object's I/O context, where workerd refuses other calls\n // (\"Cannot perform I/O on behalf of a different Durable Object\"). The scheduler's own zero\n // timer polls for the move then instead (see quiesce).\n if (this.frames.hostingNow > 0) return;\n const waiters = this.progressWaiters;\n this.progressWaiters = [];\n for (const wake of waiters) wake();\n }\n\n /** See `Run.quiesce`. */\n async quiesce(): Promise<void> {\n for (;;) {\n const moved = await this.wait();\n // Real I/O: its completion wakes the next wait, and hosted code's moves show at its end.\n if (this.frames.inFlight > 0) continue;\n // An invocation parked or a delivery ended since the step: what the step set off is at rest.\n if (this.rests !== this.restsAtStep) return;\n // Nothing in flight and nothing at rest: code waiting on something Eutaxy cannot see has one\n // turn of the event loop, as the sequential path gives, before it counts as idle; a wait\n // that saw nothing move was that turn.\n if (!moved) return;\n }\n }\n\n /**\n * Wait for a move (see `progressed`) or one real zero timer, whichever\n * comes first (no wait when something moved since the last one), then\n * let everything the move set off run before the caller looks: one turn\n * of the event loop, the cheap one where the host has it, else the timer\n * armed for the wait, after which the microtask queue is empty too.\n * Returns whether anything moved since the last wait.\n */\n private async wait(): Promise<boolean> {\n const before = this.seenMoves;\n const racing = this.moves === before;\n const tick = racing || !cheapEventLoopTurn ? realDeadline(0) : undefined;\n if (racing && tick) {\n let wake: () => void = () => {};\n const woken = new Promise<void>((resolve) => {\n wake = resolve;\n });\n this.progressWaiters.push(wake);\n await Promise.race([woken, tick.expired]);\n const i = this.progressWaiters.indexOf(wake);\n if (i >= 0) this.progressWaiters.splice(i, 1);\n }\n if (cheapEventLoopTurn) {\n tick?.cancel();\n await cheapEventLoopTurn();\n } else await tick?.expired;\n this.seenMoves = this.moves;\n return this.moves !== before;\n }\n\n /** See `Run.takeTurn`. */\n takeTurn(canStart: boolean): \"turn\" | \"start\" | \"none\" {\n const order = (inv: Turner) => this.startOrder.get(inv.id) ?? 0;\n this.parked = this.parked\n .filter((p) => !p.inv.isCrashed())\n .sort((a, b) => order(a.inv) - order(b.inv) || a.seq - b.seq);\n const options = this.parked.length + (canStart ? 1 : 0);\n this.endSegment();\n this.turnTarget = null;\n this.step();\n if (options === 0) return \"none\";\n // Put to the chooser even with one option (the enumerator sees it: a single turn can still\n // repeat an explored order); recorded only when it was a choice. An answer past the options\n // (a recorded turn from a run that had more) means the first.\n const answer = this.chooser.choose(\"turn\", this.turnOptions(canStart));\n const pick = answer < options ? answer : 0;\n if (options > 1) this.picked.push(pick);\n const [chosen] = pick < this.parked.length ? this.parked.splice(pick, 1) : [];\n if (!chosen) {\n this.starts++;\n return \"start\";\n }\n this.turnTarget = chosen.option.target ?? null;\n this.runAs(chosen.inv.id);\n const host = chosen.host;\n // Hosted code resumes: its host counts in flight again from now, before the code runs.\n if (host) this.frames.adjust(host, () => host.waitingChildren--);\n chosen.go();\n return \"turn\";\n }\n\n /** The turns on offer, as choices: the parked invocations in order, then starting the next event. */\n private turnOptions(canStart: boolean): ChoiceOption[] {\n return [\n ...this.parked.map((p) => p.option),\n ...(canStart ? [{ label: `start:${this.starts}` }] : []),\n ];\n }\n}\n","/**\n * One run of a scenario: the effect log being built, the fault decisions\n * (made by the run's chooser, see `chooser.ts`), and the invocations in\n * flight. Proxies in the platform package call `effect`/`effectSync`\n * around every real effect; everything else is engine-internal.\n *\n * With `maxConcurrentInvocations` above 1 the run is concurrent: several\n * invocations are in flight and each asynchronous effect is a turn, which\n * `turns.ts` schedules; `frames.ts` tracks effects nested in others and what\n * is in flight. Each delivery runs in its own async context, so an effect is\n * attributed to the invocation whose code made it even when a promise shared\n * between invocations resumes one during another's turn.\n */\n\nimport {\n appendEffect,\n type Bounds,\n decisionTarget,\n type EffectLog,\n type EffectOptions,\n type EffectPoint,\n type EventRef,\n type ExternalDecl,\n emptyLog,\n type FaultDecision,\n type FaultKind,\n type Invocation,\n type JsonValue,\n type RunHooks,\n type Schedule,\n} from \"@eutaxy/core\";\nimport type { Chooser } from \"./chooser.ts\";\nimport {\n effectLatencyMs,\n eventLoopTurn,\n type Patched,\n patchGlobals,\n realDeadline,\n realTick,\n settleOn,\n type VirtualClock,\n} from \"./clock.ts\";\nimport { asyncScope } from \"./context.ts\";\nimport { installScriptedFetch } from \"./fetch.ts\";\nimport { effectScope, Frame, Frames } from \"./frames.ts\";\nimport { Turns } from \"./turns.ts\";\n\n/** Thrown into user code by a synchronous effect that crashes the invocation. */\nexport class CrashSignal extends Error {\n override readonly name = \"CrashSignal\";\n readonly invocation: string;\n constructor(invocation: string) {\n super(`invocation ${invocation} crashed by an injected fault`);\n this.invocation = invocation;\n }\n}\n\n/** The error user code sees for an injected `error` or `ambiguous` fault. */\nexport class InjectedEffectError extends Error {\n override readonly name = \"InjectedEffectError\";\n readonly point: EffectPoint;\n readonly fault: FaultKind;\n constructor(point: EffectPoint, fault: FaultKind) {\n super(`${point.target} ${point.op} failed (injected ${fault})`);\n this.point = point;\n this.fault = fault;\n }\n}\n\nexport interface RunOptions {\n readonly bounds: Bounds;\n /**\n * Makes the run's choices, faults and turns alike, and gives the seed of\n * its virtual globals. The run applies no fault policy of its own: how many\n * faults a run takes is the chooser's (`seededChooser` places them, a\n * replayed schedule has them, `limitFaults` bounds any other), so a\n * chooser built by hand is unbounded unless wrapped.\n */\n readonly chooser: Chooser;\n}\n\nclass InvocationState implements Invocation {\n readonly crashed: Promise<void>;\n private readonly onCrash: () => void;\n /** Effect points seen so far in this invocation; the next effect's ordinal. */\n ordinal = 0;\n /** Times this invocation has parked for a turn; names its next turn the same in every run. */\n parks = 0;\n private crashedFlag = false;\n private resolveCrashed: () => void = () => {};\n readonly id: string;\n\n constructor(id: string, onCrash: () => void) {\n this.id = id;\n this.onCrash = onCrash;\n this.crashed = new Promise<void>((resolve) => {\n this.resolveCrashed = resolve;\n });\n }\n\n isCrashed(): boolean {\n return this.crashedFlag;\n }\n\n crash(): void {\n if (this.crashedFlag) return;\n this.crashedFlag = true;\n this.onCrash();\n this.resolveCrashed();\n }\n}\n\n/** The invocation a delivery started, set when it starts it; carried by the delivery's async context. */\ninterface DeliveryCell {\n id: string | null;\n}\n\nconst deliveryScope = asyncScope<DeliveryCell>();\n\n/** The run whose globals are installed, if any: where code observed from outside records into. */\nlet installed: Run | null = null;\n\nexport function installedRun(): Run | null {\n return installed;\n}\n\n/** Whether this host can run concurrent invocations: attribution needs async context. */\nexport const concurrencySupported = deliveryScope !== null;\n\n/** A delivery started by a concurrent run. */\nexport interface StartedDelivery<T> {\n readonly promise: Promise<T>;\n /** The invocation it started; null until it starts one. */\n invocation(): string | null;\n}\n\n/** A promise that never settles: how an abandoned invocation experiences a crash. */\nfunction hang<T>(): Promise<T> {\n return new Promise<T>(() => {});\n}\n\n/** Why an invocation that nothing can move is abandoned. */\nfunction waitingUnseen(invocation: string): string {\n return `invocation ${invocation} is waiting on something Eutaxy cannot see (no effect in flight, no timer due)`;\n}\n\n/** Delivered invocations are `<event>#<attempt>`, so this id is never one of theirs. */\nconst bookkeepingId = \"platform\";\n\nexport class Run implements RunHooks {\n private logState: EffectLog = emptyLog;\n private readonly faults: FaultDecision[] = [];\n private effectIndex = 0;\n private eligibleSeen = 0;\n private readonly invocations = new Map<string, InvocationState>();\n private readonly reasons: string[] = [];\n private readonly frames = new Frames();\n /**\n * Invocations whose code runs inside an effect of another's (a called\n * Worker's code inside the call's effect), with the frame hosting each; see\n * `hosted`.\n */\n private readonly hosts = new Map<string, Frame>();\n private patched: Patched | null = null;\n private restoreFetch: (() => void) | null = null;\n /** The invocation whose code is running (one at a time); outbound fetches are attributed to it. */\n private current = \"\";\n /** Events a platform queued during a delivery, for the run loop to pick up. */\n private queued: EventRef[] = [];\n /** Concurrent runs only: the scheduler of turns. */\n private readonly turns: Turns;\n\n /** Whether several invocations may be in flight (`maxConcurrentInvocations` above 1). */\n readonly concurrent: boolean;\n\n readonly options: RunOptions;\n\n constructor(options: RunOptions) {\n this.options = options;\n this.turns = new Turns(\n options.chooser,\n this.frames,\n (id) => this.runAs(id),\n () => this.patched?.reads,\n );\n this.concurrent = options.bounds.maxConcurrentInvocations > 1;\n }\n\n get log(): EffectLog {\n return this.logState;\n }\n\n /** The schedule as actually executed: the faults taken and, when they do not follow the seed, the turns. */\n get schedule(): Schedule {\n const { seed, recordsTurns } = this.options.chooser;\n return {\n seed,\n faults: [...this.faults],\n ...(recordsTurns ? { turns: [...this.turns.picks] } : {}),\n };\n }\n\n get effectPoints(): number {\n return this.effectIndex;\n }\n\n get faultsInjected(): number {\n return this.faults.length;\n }\n\n /**\n * Whether a turn other than an event's start did more than its own effect:\n * performed an effect on another target (synchronous, or nested in it),\n * queued events, or read virtual time or randomness (effects advance the clock and draws the\n * stream). Turns told apart by their parked effects' targets need not\n * commute then. A start is ordered against every turn anyway, so what it\n * does does not count.\n */\n get turnsMayNotCommute(): boolean {\n return this.turns.mayNotCommute;\n }\n\n /**\n * Concurrent runs: events were queued since the last decision (follow-ups\n * of a delivery that ended, or `enqueue`). The queue's order is shared, so\n * within a turn this is another dependence.\n */\n queuedEvents(): void {\n this.turns.queuedEvents();\n }\n\n get unsupportedReasons(): readonly string[] {\n return this.reasons;\n }\n\n /** Replace the nondeterministic globals and `fetch` for this run. Call `uninstall` in a finally. */\n install(externals: readonly ExternalDecl[] = []): void {\n installed = this;\n if (!this.patched) {\n this.patched = patchGlobals(this.options.chooser.seed, {\n // Web Crypto is real work the handler waits on: the run waits for it like an effect's I/O.\n trackIo: (work) => {\n this.frames.inFlight++;\n return work.finally(() => {\n this.frames.inFlight--;\n if (this.concurrent) this.progressed();\n });\n },\n });\n // Timers belong to the invocation running when they are set, hosted code's included (its\n // context is a cell of its own in either mode); in a sequential run that is `current` otherwise.\n const clock = this.patched.clock;\n clock.ownerNow = () => this.running();\n // A timer's callback, and everything it goes on to run, belongs to the invocation that set it:\n // its delivery's or hosted cell where it has one, else a cell naming the invocation running now,\n // so a sequential caller's timer fired while a hosted callee waits is still the caller's.\n clock.bind = (callback) => {\n if (!deliveryScope) return callback;\n const scope = deliveryScope;\n const cell = scope.getStore() ?? { id: this.running() };\n return (...args) => scope.run(cell, () => callback(...args));\n };\n }\n if (!this.restoreFetch) {\n this.restoreFetch = installScriptedFetch(\n externals,\n { hooks: this, invocation: () => this.running() },\n (reason) => this.unsupported(reason),\n );\n }\n }\n\n uninstall(): void {\n if (installed === this) installed = null;\n this.restoreFetch?.();\n this.restoreFetch = null;\n this.patched?.restore();\n this.patched = null;\n }\n\n /** Virtual milliseconds since the epoch, or the real clock when the globals are not installed. */\n now(): number {\n return this.patched ? this.patched.clock.now() : Date.now();\n }\n\n /** Timers scheduled and not yet fired or cancelled (0 when the globals are not installed). */\n pendingTimers(): number {\n return this.patched?.clock.pendingTimers() ?? 0;\n }\n\n startInvocation(id: string, options: { readonly bookkeeping?: boolean } = {}): Invocation {\n const inv = this.track(id);\n if (options.bookkeeping) return inv;\n if (this.concurrent) {\n this.turns.started(id);\n // Only a delivery's first invocation is its own; a platform's bookkeeping invocation,\n // started during another's turn or after every delivery, takes nothing over.\n const cell = deliveryScope?.getStore();\n if (cell && cell.id === null) {\n cell.id = id;\n this.runAs(id);\n }\n return inv;\n }\n this.runAs(id);\n return inv;\n }\n\n enqueue(event: EventRef): void {\n this.queued.push(event);\n if (this.concurrent) this.progressed();\n }\n\n /** Events platforms queued with `enqueue` since the last call. */\n takeQueued(): EventRef[] {\n const queued = this.queued;\n this.queued = [];\n return queued;\n }\n\n running(): string {\n // A delivery's cell in a concurrent run, a hosted invocation's cell in either; else the one run as.\n return deliveryScope?.getStore()?.id ?? this.current;\n }\n\n private runAs(id: string | null): void {\n if (this.patched) this.patched.clock.owner = id;\n if (id !== null) this.current = id;\n }\n\n bookkeeping(): string {\n if (!this.invocations.has(bookkeepingId)) this.track(bookkeepingId);\n return bookkeepingId;\n }\n\n private track(id: string): InvocationState {\n if (this.invocations.has(id)) throw new Error(`invocation ${id} already started`);\n const inv = new InvocationState(id, () => this.patched?.clock.cancelOwner(id));\n this.invocations.set(id, inv);\n return inv;\n }\n\n private invocation(id: string): InvocationState {\n const inv = this.invocations.get(id);\n if (!inv) throw new Error(`effect from unknown invocation ${id}`);\n return inv;\n }\n\n /** Effect points so far that could take a fault (the positions a seeded chooser's plan counts). */\n get eligiblePoints(): number {\n return this.eligibleSeen;\n }\n\n /** The fault at an eligible point, if any: the chooser's pick among none and the allowed kinds. */\n private decide(point: EffectPoint, ordinal: number): FaultKind | null {\n if (point.allowed.length === 0) return null;\n this.eligibleSeen++;\n const at = { invocation: point.invocation, ordinal };\n const i = this.options.chooser.choose(\"fault\", [\n { label: \"none\", ...at },\n ...point.allowed.map((fault) => ({ label: fault, ...at })),\n ]);\n return i === 0 ? null : (point.allowed[i - 1] ?? null);\n }\n\n private record(point: EffectPoint, kind: \"call\" | \"result\" | \"fault\", payload: JsonValue): void {\n if (kind === \"result\") this.turns.performed(point.target);\n this.logState = appendEffect(this.logState, {\n kind,\n invocation: point.invocation,\n target: point.target,\n op: point.op,\n payload,\n });\n }\n\n /** Open an effect point: record the call and decide the fault. */\n private open(point: EffectPoint, inv: InvocationState): FaultKind | null {\n this.effectIndex++;\n const ordinal = inv.ordinal++;\n this.record(point, \"call\", { args: point.args });\n const fault = this.decide(point, ordinal);\n if (fault) {\n this.faults.push({\n invocation: point.invocation,\n ordinal,\n fault,\n target: point.target,\n op: point.op,\n });\n }\n return fault;\n }\n\n async effect<T>(\n point: EffectPoint,\n perform: () => Promise<T>,\n summarize: (value: T) => JsonValue,\n options: EffectOptions = {},\n ): Promise<T> {\n const inv = this.invocation(point.invocation);\n if (inv.isCrashed()) return hang();\n // An effect made inside another's perform (an object calling out during a call) is part of\n // that effect's turn: parking it would wait for the outer one, which waits for it.\n const enclosing = this.frames.enclosing(point.invocation);\n const nested = enclosing !== undefined;\n if (this.concurrent && !nested) {\n const host = this.hosts.get(point.invocation);\n if (host?.active) {\n // Code another invocation's effect hosts (a called Worker's): a turn of its own, during which the\n // host waits on it; while it performs, the host is in flight again. Nothing cuts this code off\n // from async context, so a promise settled from outside wakes it.\n this.frames.adjust(host, () => {\n host.children++;\n host.waitingChildren++;\n });\n await new Promise<void>((go) => this.turns.park(inv, point.target, go, host));\n try {\n return await this.performEffect(point, perform, summarize, options, inv, undefined, host);\n } finally {\n this.frames.adjust(host, () => host.children--);\n }\n }\n await new Promise<void>((go) => this.turns.park(inv, point.target, go));\n if (inv.isCrashed()) return hang();\n } else if (this.concurrent && enclosing?.hosts && enclosing.mayPark()) {\n // Hosted code calling out (an object's fetch during a call) is a turn too: the object's\n // input gate is open meanwhile, so another call into it may run first. While all such\n // effects of the host are parked the host is waiting, not performing I/O.\n const host = enclosing;\n let released = false;\n this.frames.adjust(host, () => {\n host.children++;\n host.waitingChildren++;\n });\n this.turns.park(inv, point.target, () => (released = true), host);\n // Wait by polling a flag with real zero timers made here, inside the hosted code: no\n // promise is settled from outside it (workerd refuses that for a Durable Object), and no\n // event has to enter it (its input gate may be closed, as in blockConcurrencyWhile).\n while (!released && !inv.isCrashed()) await realTick();\n if (!released) {\n this.frames.adjust(host, () => {\n host.children--;\n host.waitingChildren--;\n });\n return hang();\n }\n try {\n return await this.performEffect(point, perform, summarize, options, inv, enclosing, host);\n } finally {\n this.frames.adjust(host, () => host.children--);\n }\n }\n return this.performEffect(point, perform, summarize, options, inv, enclosing);\n }\n\n /** The effect once it has its turn: the fault, the perform under its deadline, the record. */\n private async performEffect<T>(\n point: EffectPoint,\n perform: () => Promise<T>,\n summarize: (value: T) => JsonValue,\n options: EffectOptions,\n inv: InvocationState,\n enclosing: Frame | undefined,\n /** The hosting effect this one waited for a turn under, which waits on it while it waits. */\n host?: Frame,\n ): Promise<T> {\n // A crash hangs this effect; inside another effect's perform it ends that effect too.\n const dead = (): Promise<T> => {\n enclosing?.crash();\n return hang();\n };\n const fault = this.open(point, inv);\n if (fault === \"crash_before\" || fault === \"cut_off\") {\n this.record(point, \"fault\", { args: point.args, fault });\n inv.crash();\n return dead();\n }\n if (fault === \"error\") {\n this.record(point, \"fault\", { args: point.args, fault });\n throw new InjectedEffectError(point, fault);\n }\n let settled:\n | { readonly ok: true; readonly value: T }\n | { readonly ok: false; readonly error: unknown }\n | \"expired\"\n | \"nested_crash\";\n // Real I/O that outlasts the scenario's whole budget is treated as hung, so the run ends.\n const deadline = realDeadline(this.options.bounds.budgetMs);\n const frame = new Frame(point.invocation, point.hostsEffects === true, options);\n frame.parent = host;\n this.frames.enter(frame);\n try {\n const inside = (): Promise<T> => (effectScope ? effectScope.run(frame, perform) : perform());\n // The library's own timers inside the I/O are real; the handler's stay virtual.\n const io = this.patched ? this.patched.libraryIo(inside) : inside();\n settled = await Promise.race([\n io.then(\n (value) => ({ ok: true as const, value }),\n (error: unknown) => ({ ok: false as const, error }),\n ),\n deadline.expired,\n frame.crashed,\n ]);\n } catch (err) {\n // `perform` threw before returning a promise.\n settled = { ok: false, error: err };\n } finally {\n deadline.cancel();\n this.frames.leave(frame);\n this.patched?.clock.advance(effectLatencyMs);\n if (this.concurrent) this.progressed();\n }\n if (settled === \"expired\") {\n this.unsupported(\n `${point.target} ${point.op} did not complete within ${this.options.bounds.budgetMs} ms of real time`,\n );\n inv.crash();\n frame.abandon();\n return hang();\n }\n // A crash injected into an effect made during this one: it ends this one too, and outwards.\n // The frame already told the effect's onAbandon, from where the crash happened.\n if (settled === \"nested_crash\") return dead();\n if (!settled.ok) {\n this.record(point, \"result\", {\n args: point.args,\n result: null,\n error: String(settled.error),\n });\n throw settled.error;\n }\n const value = settled.value;\n this.record(point, \"result\", { args: point.args, result: summarize(value) });\n // The effect committed while the invocation was dying: nothing after it runs.\n if (inv.isCrashed()) return hang();\n if (fault === \"crash_after\") {\n this.record(point, \"fault\", { args: point.args, fault });\n inv.crash();\n return dead();\n }\n if (fault === \"ambiguous\") {\n this.record(point, \"fault\", { args: point.args, fault });\n throw new InjectedEffectError(point, fault);\n }\n return value;\n }\n\n effectSync<T>(point: EffectPoint, perform: () => T, summarize: (value: T) => JsonValue): T {\n const inv = this.invocation(point.invocation);\n if (inv.isCrashed()) throw new CrashSignal(inv.id);\n const fault = this.open(point, inv);\n if (fault === \"crash_before\" || fault === \"cut_off\") {\n this.record(point, \"fault\", { args: point.args, fault });\n inv.crash();\n throw new CrashSignal(inv.id);\n }\n if (fault === \"error\") {\n this.record(point, \"fault\", { args: point.args, fault });\n throw new InjectedEffectError(point, fault);\n }\n let value: T;\n try {\n value = perform();\n } catch (err) {\n this.record(point, \"result\", { args: point.args, result: null, error: String(err) });\n throw err;\n }\n this.record(point, \"result\", { args: point.args, result: summarize(value) });\n if (fault === \"crash_after\") {\n this.record(point, \"fault\", { args: point.args, fault });\n inv.crash();\n throw new CrashSignal(inv.id);\n }\n if (fault === \"ambiguous\") {\n this.record(point, \"fault\", { args: point.args, fault });\n throw new InjectedEffectError(point, fault);\n }\n return value;\n }\n\n unsupported(reason: string): void {\n this.reasons.push(reason);\n }\n\n settle<T>(promise: Promise<T>, invocation: string): Promise<T> {\n const inv = this.invocation(invocation);\n // In a concurrent run the run itself fires timers and detects a stuck run (see `quiesce`).\n if (this.concurrent) return Promise.race([promise, inv.crashed.then(() => hang<T>())]);\n const patched = this.patched;\n // A hosted invocation is known by its cell, never by `current`: the caller's own code may still\n // run beside it (two calls awaited together) and must stay the caller's.\n if (!this.hosts.has(invocation)) {\n if (patched) patched.clock.owner = invocation;\n this.current = invocation;\n }\n if (!patched) {\n // Globals not installed (direct use outside runOnce): just wait, abandoning on crash.\n return Promise.race([promise, inv.crashed.then(() => hang<T>())]);\n }\n return settleOn(promise, {\n clock: patched.clock,\n // An invocation hosted inside one of this one's effects is work of this one's, which its own\n // settle drives: not a timer to fire here, nor a reason to call this one stuck.\n inFlight: () => this.frames.inFlight + this.hostedBy(invocation),\n crashed: () => inv.isCrashed(),\n stuck: () => {\n // Nothing can make progress: report it and abandon the invocation so the run can end.\n this.unsupported(waitingUnseen(invocation));\n inv.crash();\n },\n });\n }\n\n /**\n * Run `work` as the code of a new invocation `id` inside the effect being\n * performed now (see `hostInvocation`): the invocation is started in a\n * delivery context of its own, so async context attributes its effects to\n * it while the host's own code stays the host's, the hosting effect waits\n * on it without counting as I/O of its own (the hosted code's effects and\n * tracked work count), and the hosting invocation is the running one again\n * once it ends. A fault that crashes `id` ends `id` alone: nothing here\n * tells the host's frame, so what the host sees is `work`'s to decide.\n */\n async hosted<T>(id: string, work: (inv: Invocation) => Promise<T>): Promise<T> {\n const frame = this.frames.current();\n if (!frame)\n throw new Error(`invocation ${id} can only be hosted inside an effect being performed`);\n if (!deliveryScope)\n throw new Error(\"hosting an invocation needs AsyncLocalStorage (node:async_hooks)\");\n const run = async (): Promise<T> => {\n // Tracked, not made the running one: the hosted code is known by its own cell, so the caller's\n // code that goes on meanwhile (a second call awaited together) stays the caller's.\n const inv = this.track(id);\n if (this.concurrent) this.turns.started(id);\n this.hosts.set(id, frame);\n this.frames.adjust(frame, () => {\n frame.children++;\n frame.waitingChildren++;\n });\n try {\n return await work(inv);\n } finally {\n this.frames.adjust(frame, () => {\n frame.children--;\n frame.waitingChildren--;\n });\n this.hosts.delete(id);\n }\n };\n // Inside an effect's perform the library's timers are real; the hosted code is handler code, so\n // its timers are virtual again, and it runs in a delivery context of its own in either mode.\n const asHandler = (): Promise<T> => (this.patched ? this.patched.handlerCode(run) : run());\n return deliveryScope.run({ id }, asHandler);\n }\n\n /** How many invocations are hosted inside effects of `invocation` now. */\n private hostedBy(invocation: string): number {\n let n = 0;\n for (const frame of this.hosts.values()) if (frame.invocation === invocation) n++;\n return n;\n }\n\n /** Concurrent runs: start a delivery in its own async context. */\n startDelivery<T>(deliver: () => Promise<T>): StartedDelivery<T> {\n if (!deliveryScope) throw new Error(\"concurrent invocations need AsyncLocalStorage\");\n const cell: DeliveryCell = { id: null };\n this.runAs(null);\n const promise = deliveryScope.run(cell, deliver);\n return { promise, invocation: () => cell.id };\n }\n\n /** Concurrent runs: something moved (I/O completed, an event was queued). */\n progressed(): void {\n this.turns.progressed();\n }\n\n /** Concurrent runs: a delivery ended. */\n rested(): void {\n this.turns.rested();\n }\n\n /**\n * Concurrent runs: wait until what the last step set off (a turn\n * released, an event started, a timer fired) has parked, finished or\n * gone idle. Parking, a delivery ending and I/O completing wake the wait\n * at once, except while a Durable Object's code runs, which cannot wake\n * it (the wait's zero timer polls then); every continuation they set off\n * runs before it returns (one turn of the event loop), so code another\n * invocation's promise resumed reaches its own effect too. Code waiting\n * on anything else gets one such turn, the same allowance the sequential\n * path gives, before it counts as idle.\n */\n quiesce(): Promise<void> {\n return this.turns.quiesce();\n }\n\n /**\n * Concurrent runs: pick the next turn among the parked invocations and,\n * when `canStart`, starting the next event. Parked invocations are ordered\n * by start, then by when they parked, so the pick does not depend on\n * real-time arrival. Returns what was picked; \"turn\" has already released it.\n */\n takeTurn(canStart: boolean): \"turn\" | \"start\" | \"none\" {\n return this.turns.takeTurn(canStart);\n }\n\n /**\n * Let virtual time pass until `at`: timers due by then fire first, in due\n * order, as the invocations that set them, each followed by the work it\n * sets off. No-op when `at` is not ahead. Returns whether a timer fired.\n */\n async advanceTo(at: number): Promise<boolean> {\n const clock = this.patched?.clock;\n if (!clock) return false;\n let fired = false;\n for (let due = clock.nextDue(); due !== undefined && due <= at; due = clock.nextDue()) {\n this.fireNextTimer(clock);\n fired = true;\n // What the timer set off runs at its own time, before the clock moves on.\n do await eventLoopTurn();\n while (this.frames.inFlight > 0);\n }\n clock.advance(at - clock.now());\n return fired;\n }\n\n /** When the next virtual timer is due, or undefined when none is pending. */\n nextTimerDue(): number | undefined {\n return this.patched?.clock.nextDue();\n }\n\n /** Concurrent runs: fire the next due timer as the invocation that set it. False when none is pending. */\n fireTimer(): boolean {\n const clock = this.patched?.clock;\n if (!clock || clock.nextOwner() === undefined) return false;\n return this.fireNextTimer(clock);\n }\n\n /** Fire the next due timer as the invocation that set it (a step of a concurrent run). */\n private fireNextTimer(clock: VirtualClock): boolean {\n this.runAs(clock.nextOwner() ?? null);\n if (this.concurrent) this.turns.step();\n return clock.fireNext();\n }\n\n /**\n * Concurrent runs: nothing can make progress; abandon these invocations so\n * the run can end. Returns how many were still alive.\n */\n abandon(ids: readonly string[]): number {\n let abandoned = 0;\n for (const id of ids) {\n const inv = this.invocations.get(id);\n if (!inv || inv.isCrashed()) continue;\n this.unsupported(waitingUnseen(id));\n inv.crash();\n abandoned++;\n }\n return abandoned;\n }\n\n /** A call of a pure core function, recorded as a decision of the invocation running now (see `observeCore`). */\n decision(fn: string, payload: JsonValue): void {\n this.logState = appendEffect(this.logState, {\n kind: \"result\",\n invocation: this.running(),\n target: decisionTarget(fn),\n op: \"decide\",\n payload,\n });\n }\n\n snapshot(invocation: string, target: string, payload: JsonValue): void {\n this.logState = appendEffect(this.logState, {\n kind: \"snapshot\",\n invocation,\n target,\n op: \"snapshot\",\n payload,\n });\n }\n}\n","/**\n * The skeleton of a delivery, written once for every platform: user code\n * runs as an invocation under the engine's settle, and how it ended is one\n * of three outcomes rather than an exception to sort.\n */\n\nimport type { Invocation, RunHooks } from \"@eutaxy/core\";\nimport { CrashSignal, Run } from \"./run.ts\";\n\n/** How user code run as an invocation ended: it returned, it threw, or an injected fault crashed it. */\nexport type Outcome<T> =\n | { readonly status: \"completed\"; readonly value: T }\n | { readonly status: \"errored\"; readonly error: unknown }\n | { readonly status: \"crashed\" };\n\n/**\n * Run user code as an invocation: under `RunHooks.settle` (real I/O\n * completes, timers fire while it is idle) and ended as \"crashed\" when an\n * injected fault crashes the invocation, whether the code saw the crash as\n * a `CrashSignal` or an effect of its hung, as \"errored\" when it threw\n * anything else.\n */\nexport async function runInvocation<T>(\n hooks: RunHooks,\n inv: Invocation,\n work: () => T | Promise<T>,\n): Promise<Outcome<T>> {\n const outcome: Promise<Outcome<T>> = Promise.resolve()\n .then(work)\n .then(\n (value) => ({ status: \"completed\", value }),\n (error: unknown) =>\n error instanceof CrashSignal ? { status: \"crashed\" } : { status: \"errored\", error },\n );\n return Promise.race([\n hooks.settle(outcome, inv.id),\n inv.crashed.then((): Outcome<T> => ({ status: \"crashed\" })),\n ]);\n}\n\n/**\n * Run user code as an invocation of its own inside the effect being performed\n * (a called Worker's code inside the call's effect). The engine attributes\n * the effects `work` makes to `id` and schedules them as turns of their own,\n * has the hosting effect wait on the work without counting as I/O, and makes\n * the hosting invocation the running one again afterwards. `work` runs the\n * user code through `runInvocation` (and whatever follows it, such as\n * background work) so that it ends as an outcome; a fault that crashes `id`\n * ends `id` alone, and what the hosting code then throws or returns is the\n * platform's to decide.\n */\nexport function hostInvocation<T>(\n hooks: RunHooks,\n id: string,\n work: (inv: Invocation) => Promise<T>,\n): Promise<T> {\n if (!(hooks instanceof Run)) throw new Error(\"hostInvocation needs the engine's run\");\n return hooks.hosted(id, work);\n}\n","/**\n * Exhaustive exploration: every schedule within the bounds, each once. A\n * schedule is the sequence of choices a run makes: a fault or none at each\n * effect point that may still take one, and the next turn at each decision\n * of a concurrent run. Runs are deterministic, so forcing a prefix of\n * choices reproduces the run up to there; the enumerator walks the tree of\n * choice sequences depth first, one run per leaf, without saving state\n * (each run starts from the scenario's reset).\n *\n * Reduction, when on, uses sleep sets (Godefroid, Partial-Order Methods for\n * the Verification of Concurrent Systems, 1996): two turns of different\n * invocations whose effects have different targets commute, so after one\n * order of them has been explored the other is not. Starting an event is\n * dependent on everything. A run whose every option is asleep repeats an\n * explored order; it still runs (the choices are forced up to it) but is not\n * counted as a schedule and nothing below it is explored.\n */\n\nimport { type ChoiceOption, type Chooser, limitFaults } from \"./chooser.ts\";\n\ninterface Node {\n readonly kind: \"fault\" | \"turn\";\n readonly options: readonly ChoiceOption[];\n picked: number;\n /** Options already explored from this node, in the order they were. */\n readonly done: number[];\n /** Turns not to take from this node: their order with the path here is explored. */\n readonly sleep: ReadonlyMap<string, ChoiceOption>;\n}\n\n/** Whether two turns commute: different invocations, effects on different targets. */\nexport function independent(a: ChoiceOption, b: ChoiceOption): boolean {\n return (\n a.invocation !== undefined &&\n b.invocation !== undefined &&\n a.invocation !== b.invocation &&\n a.target !== undefined &&\n b.target !== undefined &&\n a.target !== b.target\n );\n}\n\nconst asleep = new Map<string, ChoiceOption>();\n\nexport class Enumerator {\n private readonly stack: Node[] = [];\n private depth = 0;\n /** The depth of the first node in the run just made whose every option was asleep, or null. */\n private blockedAt: number | null = null;\n private mismatchReason: string | null = null;\n private readonly reduction: boolean;\n\n constructor(options: { readonly reduction: boolean }) {\n this.reduction = options.reduction;\n }\n\n /** Whether the run just made repeats an explored order (every option at some point was asleep). */\n get blocked(): boolean {\n return this.blockedAt !== null;\n }\n\n /** Set when a run made different choices than the same prefix did before: not deterministic. */\n get mismatch(): string | null {\n return this.mismatchReason;\n }\n\n /**\n * The chooser for the next run: the explored prefix, then the first option\n * not asleep. Enumerated runs pick their choices and share one seed for\n * the virtual globals; their turns are recorded, since they do not follow it.\n */\n next(): Chooser {\n this.depth = 0;\n this.blockedAt = null;\n return { seed: 0, recordsTurns: true, choose: (kind, options) => this.choose(kind, options) };\n }\n\n private choose(kind: \"fault\" | \"turn\", options: readonly ChoiceOption[]): number {\n const i = this.depth++;\n const known = this.stack[i];\n if (known) {\n const same =\n known.kind === kind &&\n known.options.length === options.length &&\n known.options.every((o, j) => o.label === options[j]?.label);\n if (!same && this.mismatchReason === null) {\n 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(\", \")})`;\n }\n return known.picked < options.length ? known.picked : 0;\n }\n // Below a blocked node every order is explored already: the run finishes, nothing is recorded.\n if (this.blockedAt !== null) return 0;\n const sleep = this.sleepAt(i);\n let picked = kind === \"turn\" ? options.findIndex((o) => !sleep.has(o.label)) : 0;\n if (picked < 0) {\n this.blockedAt = i;\n picked = 0;\n }\n this.stack.push({ kind, options, picked, done: [], sleep });\n return picked;\n }\n\n /** The sleep set of a new node at depth i, from its parent's. */\n private sleepAt(i: number): ReadonlyMap<string, ChoiceOption> {\n const parent = this.stack[i - 1];\n if (!this.reduction || !parent) return asleep;\n // A fault decision belongs to the effect of the turn being taken: the sleep set passes through.\n if (parent.kind === \"fault\") return parent.sleep;\n const taken = parent.options[parent.picked];\n if (!taken) return asleep;\n const sleep = new Map<string, ChoiceOption>();\n const candidates = [...parent.sleep.values(), ...parent.done.map((j) => parent.options[j])];\n for (const c of candidates) if (c && independent(c, taken)) sleep.set(c.label, c);\n return sleep;\n }\n\n /** Move to the next schedule after a run. False once every schedule has been explored. */\n advance(): boolean {\n // A run blocked by its sleep set explores nothing below the blocking node.\n this.stack.length = Math.min(this.stack.length, this.depth, (this.blockedAt ?? Infinity) + 1);\n while (this.stack.length > 0) {\n const node = this.stack[this.stack.length - 1] as Node;\n if (!node.done.includes(node.picked)) node.done.push(node.picked);\n const next = node.options.findIndex(\n (o, j) => !node.done.includes(j) && (node.kind === \"fault\" || !node.sleep.has(o.label)),\n );\n if (next >= 0) {\n node.picked = next;\n return true;\n }\n this.stack.pop();\n }\n return false;\n }\n}\n\n/**\n * The exhaustive half of `explore`: the chooser for each run, what a run\n * counts for, and starting the enumeration again with the reduction off\n * once a run shows its turns may not commute.\n */\nexport class ExhaustiveDriver {\n private reduction: boolean;\n private enumerator: Enumerator;\n private readonly maxFaultsPerRun: number;\n private schedules = 0;\n private more = true;\n private restart = false;\n\n constructor(reduction: boolean, maxFaultsPerRun: number) {\n this.reduction = reduction;\n this.maxFaultsPerRun = maxFaultsPerRun;\n this.enumerator = new Enumerator({ reduction });\n }\n\n /** Whether schedules are left to run. */\n get hasMore(): boolean {\n return this.more;\n }\n\n /** See `Enumerator.mismatch`. */\n get mismatch(): string | null {\n return this.enumerator.mismatch;\n }\n\n /** The chooser for the next run, under the run's fault bound. */\n next(): Chooser {\n return limitFaults(this.enumerator.next(), this.maxFaultsPerRun);\n }\n\n /**\n * Account for the run just made. False when it only repeated an order the\n * reduction had covered: it is not a new schedule and its checks repeat\n * others'. A run that shows its turns may not commute counts and is\n * checked, and `checked` then starts again over every order.\n */\n ran(turnsMayNotCommute: () => boolean): boolean {\n this.restart = this.reduction && turnsMayNotCommute();\n if (!this.restart) {\n this.more = this.enumerator.advance();\n if (this.enumerator.blocked) return false;\n }\n this.schedules++;\n return true;\n }\n\n /** The run's checks passed: if it turned the reduction off, every order from the start. */\n checked(): void {\n if (!this.restart) return;\n this.reduction = false;\n this.enumerator = new Enumerator({ reduction: false });\n this.schedules = 0;\n }\n\n /** What the verdict reports (see `BoundsReached.exhaustive`). */\n get reached(): {\n readonly complete: boolean;\n readonly schedules: number;\n readonly reduction: boolean;\n } {\n return { complete: !this.more, schedules: this.schedules, reduction: this.reduction };\n }\n}\n","/**\n * Shrinking, the loop: try the pure candidates in order, replay each, keep\n * the first that still violates the same invariant for the same keys, and\n * repeat from there until nothing smaller works or the budget is spent.\n */\n\nimport {\n checkInvariants,\n type EffectLog,\n type Platform,\n recomputePerMessageExpected,\n type ScenarioSpec,\n type Schedule,\n type ShrinkState,\n sameViolation,\n shrinkCandidates,\n type Violation,\n} from \"@eutaxy/core\";\nimport { replayRun } from \"./explore.ts\";\n\nexport interface ShrinkOptions {\n readonly maxRuns: number;\n readonly deadline: number;\n readonly now: () => number;\n}\n\nexport interface ShrinkResult {\n readonly spec: ScenarioSpec;\n readonly schedule: Schedule;\n readonly keptEvents: readonly string[];\n readonly trace: EffectLog;\n readonly violation: Violation;\n readonly runs: number;\n readonly faultsRemoved: number;\n readonly eventsRemoved: number;\n}\n\n/** The scenario restricted to the kept events, with per-message invariants re-derived. */\nexport function restrictSpec(\n platform: Platform,\n spec: ScenarioSpec,\n keepIds: readonly string[],\n): ScenarioSpec {\n const restricted = platform.restrictEvents(spec, keepIds);\n const bodies = platform.initialEvents(restricted).map((e) => e.data);\n return { ...restricted, invariants: recomputePerMessageExpected(restricted.invariants, bodies) };\n}\n\nexport async function shrink(\n spec: ScenarioSpec,\n platform: Platform,\n schedule: Schedule,\n violation: Violation,\n trace: EffectLog,\n options: ShrinkOptions,\n): Promise<ShrinkResult> {\n const allIds = platform.initialEvents(spec).map((e) => e.id);\n let state: ShrinkState = { schedule, keepIds: allIds };\n let best = { trace, violation };\n let runs = 0;\n\n let improved = true;\n while (improved && runs < options.maxRuns && options.now() < options.deadline) {\n improved = false;\n for (const candidate of shrinkCandidates(state)) {\n if (runs >= options.maxRuns || options.now() >= options.deadline) break;\n const candidateSpec = restrictSpec(platform, spec, candidate.keepIds);\n const run = await replayRun(candidateSpec, platform, candidate.schedule);\n const log = run.log;\n runs++;\n // A smaller run that touches something Eutaxy cannot control is not a valid counterexample.\n if (run.unsupportedReasons.length > 0) continue;\n const found = checkInvariants(log, candidateSpec.invariants).find((v) =>\n sameViolation(v, violation),\n );\n if (found) {\n state = candidate;\n best = { trace: log, violation: found };\n improved = true;\n break;\n }\n }\n }\n return {\n spec: restrictSpec(platform, spec, state.keepIds),\n schedule: state.schedule,\n keptEvents: state.keepIds,\n trace: best.trace,\n violation: best.violation,\n runs,\n faultsRemoved: schedule.faults.length - state.schedule.faults.length,\n eventsRemoved: allIds.length - state.keepIds.length,\n };\n}\n","/**\n * The exploration loop: run the scenario under seeded fault injection until\n * an invariant breaks or the budget is spent; replay any violation before\n * reporting it.\n */\n\nimport {\n type Bounds,\n type BoundsReached,\n checkInvariants,\n type DeliveryResult,\n digestLog,\n type EffectLog,\n type EventRef,\n nextU32,\n type Platform,\n type PrngState,\n planFaults,\n type ScenarioSpec,\n type ScenarioVerdict,\n type Schedule,\n seedPrng,\n} from \"@eutaxy/core\";\nimport { replayChooser, seededChooser } from \"./chooser.ts\";\nimport { ExhaustiveDriver } from \"./exhaustive.ts\";\nimport { concurrencySupported, Run, type StartedDelivery } from \"./run.ts\";\nimport { shrink } from \"./shrink.ts\";\n\nexport interface ExploreOptions {\n readonly seed: number | string;\n /** Hard cap on runs, in addition to the scenario's time budget. */\n readonly maxRuns?: number;\n /**\n * Replaces the scenario's `budgetMs` for this exploration: the real time\n * exploring and shrinking may take, and the real time one effect's I/O\n * may take before it counts as hung. With a generous budget and\n * `maxRuns`, the run cap ends exploration, so a seed decides the verdict\n * on any machine.\n */\n readonly budgetMs?: number;\n /**\n * The share of seeded runs after the first (which injects none) that\n * inject faults (see `planFaults`). Default 0.9: the runs without faults\n * also check the scenario as it runs without them, and measure how many\n * eligible points a run without faults has, which can vary with the seed.\n */\n readonly faultProbability?: number;\n /** Clock for the time budget; injectable for tests. */\n readonly now?: () => number;\n /** Hard cap on replay runs spent shrinking a violation. */\n readonly maxShrinkRuns?: number;\n /**\n * How many of the first exploration runs to replay in reverse order\n * before reporting BOUNDED, to detect module-level state leaking between\n * runs. 0 disables the pass.\n */\n readonly leakCheckRuns?: number;\n /**\n * Explore every schedule within the bounds, each once, instead of drawing\n * schedules from the seed: every fault (or none) at every effect point\n * that may still take one, and every order of turns. With `reduction`\n * (the default), turns of different invocations on different targets\n * commute and only one order of them is run.\n */\n readonly exhaustive?: boolean | { readonly reduction?: boolean };\n}\n\nconst engineAssumptions: readonly string[] = [\n \"schedule points are effect boundaries: proxied bindings, patched timers and fetch; other awaits run in program order\",\n \"faults: crash_before, crash_after, ambiguous, error at any effect point; redelivery per the platform's queue model\",\n \"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\",\n \"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\",\n \"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\",\n \"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\",\n \"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)\",\n \"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\",\n];\n\n/** What a verdict rests on about concurrency, for these bounds. */\nfunction concurrencyAssumption(bounds: Bounds): string {\n if (bounds.maxConcurrentInvocations === 1)\n return \"one invocation at a time (maxConcurrentInvocations = 1)\";\n 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`;\n}\n\n/** The pending event to deliver next: the earliest by `at`, then the first queued. */\nfunction nextEvent(pending: readonly EventRef[]): number {\n let best = 0;\n for (let i = 1; i < pending.length; i++)\n if ((pending[i]?.at ?? 0) < (pending[best]?.at ?? 0)) best = i;\n return best;\n}\n\n/** What a verdict rests on about how schedules were chosen, when exploration was exhaustive. */\nfunction explorationAssumption(options: ExploreOptions): readonly string[] {\n if (!options.exhaustive) return [];\n const reduction =\n typeof options.exhaustive === \"object\" ? (options.exhaustive.reduction ?? true) : true;\n return [\n \"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)\",\n ...(reduction\n ? [\n \"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)\",\n ]\n : []),\n ];\n}\n\n/** Deliver events one at a time, each to completion; time passes until a delayed one is due. */\nasync function deliverInOrder(spec: ScenarioSpec, platform: Platform, run: Run): Promise<void> {\n const pending: EventRef[] = [...platform.initialEvents(spec)];\n while (pending.length > 0) {\n const [event] = pending.splice(nextEvent(pending), 1) as [EventRef];\n if (event.at !== undefined) await run.advanceTo(event.at);\n const result = await platform.deliver(event, run, spec);\n pending.push(...run.takeQueued(), ...result.followUps);\n }\n}\n\ninterface Delivery {\n readonly started: StartedDelivery<DeliveryResult>;\n outcome: { readonly result: DeliveryResult } | { readonly error: unknown } | null;\n}\n\n/**\n * Deliver events with up to `maxConcurrentInvocations` in flight. Each turn\n * is a seeded pick: one parked invocation performs its effect and runs to\n * its next one, or, while a slot is free, the next event starts. When\n * nothing is parked and no event can start a timer fires, and when nothing\n * can move the remaining invocations are abandoned.\n */\nasync function deliverConcurrently(\n spec: ScenarioSpec,\n platform: Platform,\n run: Run,\n): Promise<void> {\n const pending: EventRef[] = [...platform.initialEvents(spec)];\n let active: Delivery[] = [];\n for (;;) {\n // Finished deliveries leave in the order they started; their follow-ups queue behind the rest.\n const queuedBefore = pending.length;\n for (const d of active) {\n if (!d.outcome) continue;\n if (\"error\" in d.outcome) throw d.outcome.error;\n pending.push(...d.outcome.result.followUps);\n }\n active = active.filter((d) => !d.outcome);\n pending.push(...run.takeQueued());\n if (pending.length > queuedBefore) run.queuedEvents();\n if (active.length === 0 && pending.length === 0) return;\n const next = pending.length > 0 ? nextEvent(pending) : -1;\n const due = next >= 0 && (pending[next]?.at ?? 0) <= run.now();\n const canStart = active.length < spec.bounds.maxConcurrentInvocations && due;\n const turn = run.takeTurn(canStart);\n if (turn === \"start\") {\n const [event] = pending.splice(next, 1) as [EventRef];\n const d: Delivery = {\n started: run.startDelivery(() => platform.deliver(event, run, spec)),\n outcome: null,\n };\n d.started.promise.then(\n (result) => {\n d.outcome = { result };\n run.rested();\n },\n (error: unknown) => {\n d.outcome = { error };\n run.rested();\n },\n );\n active.push(d);\n } else if (\n turn === \"none\" &&\n next >= 0 &&\n !due &&\n active.length < spec.bounds.maxConcurrentInvocations &&\n (run.nextTimerDue() ?? Number.POSITIVE_INFINITY) > (pending[next]?.at ?? 0)\n ) {\n // Nothing can move before the next delayed event is due: let time pass until then. With no\n // timer fired on the way, nothing was set off that a wait could settle.\n if (!(await run.advanceTo(pending[next]?.at ?? 0))) continue;\n } else if (turn === \"none\" && !run.fireTimer()) {\n const stuck = active.flatMap((d) => d.started.invocation() ?? []);\n if (run.abandon(stuck) === 0)\n throw new Error(\n `the ${platform.name} platform's delivery made no progress and cannot be abandoned`,\n );\n }\n await run.quiesce();\n }\n}\n\n/** Run the scenario once under the given run's fault decisions and return its log. */\nexport async function runOnce(\n spec: ScenarioSpec,\n platform: Platform,\n run: Run,\n): Promise<EffectLog> {\n // Reset and the end-of-run snapshot are platform work, not user code: they run with the real\n // globals, so an in-process local service (which shares them) keeps its own timers.\n await platform.reset(spec);\n run.install(spec.externals);\n try {\n try {\n if (!run.concurrent) await deliverInOrder(spec, platform, run);\n else if (platform.concurrent) await deliverConcurrently(spec, platform, run);\n else throw new Error(`the ${platform.name} platform delivers one event at a time`);\n } finally {\n run.uninstall();\n }\n await platform.finish?.(spec, run);\n } finally {\n // Whatever happened above, the platform undoes its per-run patching.\n await platform.cleanup?.(spec);\n }\n return run.log;\n}\n\n/** Re-run a recorded schedule exactly and return the whole run (log and support status). */\nexport async function replayRun(\n spec: ScenarioSpec,\n platform: Platform,\n schedule: Schedule,\n): Promise<Run> {\n const run = new Run({ bounds: spec.bounds, chooser: replayChooser(schedule) });\n await runOnce(spec, platform, run);\n return run;\n}\n\n/** Re-run a recorded schedule exactly. */\nexport async function replay(\n spec: ScenarioSpec,\n platform: Platform,\n schedule: Schedule,\n): Promise<EffectLog> {\n return (await replayRun(spec, platform, schedule)).log;\n}\n\nexport async function explore(\n scenario: ScenarioSpec,\n platform: Platform,\n options: ExploreOptions,\n): Promise<ScenarioVerdict> {\n const budgetMs = options.budgetMs;\n if (budgetMs !== undefined && !(Number.isFinite(budgetMs) && budgetMs > 0))\n throw new Error(`budgetMs must be a positive finite number, got ${budgetMs}`);\n const spec =\n budgetMs === undefined ? scenario : { ...scenario, bounds: { ...scenario.bounds, budgetMs } };\n const now = options.now ?? (() => Date.now());\n const maxRuns = options.maxRuns ?? 100;\n // The runs kept fault-free re-measure the path without faults, which can vary with the seed.\n const faultProbability = options.faultProbability ?? 0.9;\n const assumptions = [\n ...engineAssumptions,\n concurrencyAssumption(spec.bounds),\n ...explorationAssumption(options),\n ...platform.assumptions,\n ];\n const start = now();\n const reached = { runs: 0, effectPoints: 0, faultsInjected: 0 };\n const done = (): BoundsReached => ({ ...reached, elapsedMs: now() - start });\n const base = { scenario: spec.name, seed: options.seed, assumptions };\n\n if (spec.bounds.maxConcurrentInvocations > 1 && !concurrencySupported) {\n return {\n ...base,\n kind: \"UNSUPPORTED\",\n cause: \"unsupported_bounds\",\n reason:\n \"maxConcurrentInvocations above 1 needs AsyncLocalStorage (Node, or workerd with nodejs_compat or nodejs_als)\",\n reached: done(),\n };\n }\n if (spec.bounds.maxConcurrentInvocations > 1 && !platform.concurrent) {\n return {\n ...base,\n kind: \"UNSUPPORTED\",\n cause: \"unsupported_bounds\",\n reason: `maxConcurrentInvocations above 1 is not supported on the ${platform.name} platform yet`,\n reached: done(),\n };\n }\n\n const leakCheckRuns = options.leakCheckRuns ?? 2;\n /** The first runs' schedules and digests, replayed in reverse order before BOUNDED. */\n const witnesses: { schedule: Schedule; digest: string }[] = [];\n\n let master: PrngState = seedPrng(options.seed);\n /** Eligible points of a run without faults, and the most any run has had: seeded fault positions. */\n let baseline = 0;\n let longest = 0;\n const exhaustive = options.exhaustive\n ? new ExhaustiveDriver(\n typeof options.exhaustive === \"object\" ? (options.exhaustive.reduction ?? true) : true,\n spec.bounds.maxFaultsPerRun,\n )\n : null;\n const doneNow = (): BoundsReached => ({\n ...done(),\n ...(exhaustive ? { exhaustive: exhaustive.reached } : {}),\n });\n while (\n (exhaustive?.hasMore ?? true) &&\n reached.runs < maxRuns &&\n now() - start < spec.bounds.budgetMs\n ) {\n const [runSeed, next] = nextU32(master);\n master = next;\n // Seeded runs fault positions drawn over the eligible points seen so far: none before any is.\n let faultPlan: readonly number[] = [];\n if (!exhaustive) {\n [faultPlan, master] = planFaults(\n master,\n baseline,\n longest,\n spec.bounds.maxFaultsPerRun,\n faultProbability,\n );\n }\n const run = new Run({\n bounds: spec.bounds,\n chooser: exhaustive\n ? exhaustive.next()\n : seededChooser(runSeed, {\n faultPlan,\n faultProbability,\n maxFaultsPerRun: spec.bounds.maxFaultsPerRun,\n }),\n });\n const log = await runOnce(spec, platform, run);\n reached.runs++;\n if (run.faultsInjected === 0) baseline = Math.max(baseline, run.eligiblePoints);\n longest = Math.max(longest, run.eligiblePoints);\n if (exhaustive) {\n if (exhaustive.mismatch) {\n return {\n ...base,\n kind: \"UNSUPPORTED\",\n cause: \"not_replayable\",\n reason: `exhaustive exploration needs deterministic runs: ${exhaustive.mismatch}`,\n reached: doneNow(),\n };\n }\n if (!exhaustive.ran(() => run.turnsMayNotCommute)) continue;\n }\n reached.effectPoints += run.effectPoints;\n reached.faultsInjected += run.faultsInjected;\n if (witnesses.length < leakCheckRuns)\n witnesses.push({ schedule: run.schedule, digest: digestLog(log) });\n\n if (run.unsupportedReasons.length > 0) {\n return {\n ...base,\n kind: \"UNSUPPORTED\",\n cause: \"unsupported_api\",\n reason: run.unsupportedReasons.join(\"; \"),\n reached: doneNow(),\n };\n }\n\n const violations = checkInvariants(log, spec.invariants);\n const violation = violations[0];\n if (violation) {\n const schedule = run.schedule;\n const replayedRun = await replayRun(spec, platform, schedule);\n const replayed = replayedRun.log;\n reached.runs++;\n if (replayedRun.unsupportedReasons.length > 0 || digestLog(replayed) !== digestLog(log)) {\n return {\n ...base,\n kind: \"UNSUPPORTED\",\n cause: \"not_replayable\",\n reason: `the violating run of seed ${schedule.seed} did not reproduce on replay`,\n reached: doneNow(),\n };\n }\n // Shrink within the scenario's budget (a second budget's worth at most), then report.\n const shrunk = await shrink(spec, platform, schedule, violation, replayed, {\n maxRuns: options.maxShrinkRuns ?? 200,\n deadline: now() + spec.bounds.budgetMs,\n now,\n });\n reached.runs += shrunk.runs;\n return {\n ...base,\n kind: \"VIOLATED\",\n violation: shrunk.violation,\n trace: shrunk.trace,\n schedule: shrunk.schedule,\n keptEvents: shrunk.keptEvents,\n shrunk: {\n faultsRemoved: shrunk.faultsRemoved,\n eventsRemoved: shrunk.eventsRemoved,\n runs: shrunk.runs,\n },\n reached: doneNow(),\n };\n }\n exhaustive?.checked();\n }\n // Module-state leak detection: the same schedules, in the opposite order, must give the same logs.\n for (const witness of [...witnesses].reverse()) {\n const again = await replayRun(spec, platform, witness.schedule);\n reached.runs++;\n if (again.unsupportedReasons.length > 0 || digestLog(again.log) !== witness.digest) {\n return {\n ...base,\n kind: \"UNSUPPORTED\",\n cause: \"module_state_leak\",\n 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)`,\n reached: doneNow(),\n };\n }\n }\n return { ...base, kind: \"BOUNDED\", bounds: spec.bounds, reached: doneNow() };\n}\n","/**\n * The platform-neutral half of a differential check: the same fault-free\n * scenario once through Eutaxy (this module) and once against the raw\n * bindings (each platform's own, sharing no proxy code), then a comparison\n * of what each attempt decided and of the final state. Any difference is a\n * bug in the proxies or the platform model, not in the handler.\n */\n\nimport {\n canonicalJson,\n type DeliveryResult,\n type EffectRecord,\n type EventRef,\n type JsonValue,\n type Platform,\n type ScenarioSpec,\n} from \"@eutaxy/core\";\nimport { replayChooser } from \"./chooser.ts\";\nimport { runOnce } from \"./explore.ts\";\nimport { Run } from \"./run.ts\";\n\n/** The raw side cannot abandon an invocation the way the engine does; a stuck handler ends the comparison. */\nexport class DifferentialStuck extends Error {\n override readonly name = \"DifferentialStuck\";\n constructor(\n message = \"raw side: the handler is waiting on something outside the run (no effect in flight, no timer due)\",\n ) {\n super(message);\n }\n}\n\n/**\n * The Eutaxy side: one run with no faults, one event at a time whatever the\n * scenario's bound (the raw side cannot interleave), with `attempt` given\n * each delivery's event, result and log entries.\n */\nexport async function proxiedSide<A>(\n spec: ScenarioSpec,\n platform: Platform,\n attempt: (event: EventRef, result: DeliveryResult, entries: readonly EffectRecord[]) => A,\n): Promise<{ readonly attempts: readonly A[]; readonly unsupported: readonly string[] }> {\n const run = new Run({\n bounds: { ...spec.bounds, maxConcurrentInvocations: 1 },\n chooser: replayChooser({ seed: 0, faults: [] }),\n });\n const attempts: A[] = [];\n // Every member forwarded to the platform itself, so a class's methods keep their `this`.\n const { finish, cleanup } = platform;\n const recording: Platform = {\n name: platform.name,\n assumptions: platform.assumptions,\n ...(platform.concurrent === undefined ? {} : { concurrent: platform.concurrent }),\n reset: (s) => platform.reset(s),\n initialEvents: (s) => platform.initialEvents(s),\n restrictEvents: (s, keep) => platform.restrictEvents(s, keep),\n async deliver(event, hooks, s) {\n const before = run.log.entries.length;\n const result = await platform.deliver(event, hooks, s);\n attempts.push(attempt(event, result, run.log.entries.slice(before)));\n return result;\n },\n ...(finish ? { finish: (s, hooks) => finish.call(platform, s, hooks) } : {}),\n ...(cleanup ? { cleanup: (s) => cleanup.call(platform, s) } : {}),\n };\n await runOnce(spec, recording, run);\n return { attempts, unsupported: run.unsupportedReasons };\n}\n\n/**\n * One side's outcome: per-attempt records, and the final state as rows per\n * name. Both are compared as they are, never summarized again, so a\n * difference however deep stays one.\n */\nexport interface ComparedSide {\n readonly attempts: readonly JsonValue[];\n readonly state: { readonly [name: string]: readonly JsonValue[] };\n}\n\n/** Every difference between the two sides, one readable entry each; none means they agree. */\nexport function compareSides(\n eutaxy: ComparedSide,\n raw: ComparedSide,\n unsupported: readonly string[],\n): readonly string[] {\n const differences: string[] = [];\n if (unsupported.length > 0)\n differences.push(`the proxied run touched unsupported APIs: ${unsupported.join(\"; \")}`);\n const a = canonicalJson(eutaxy.attempts);\n const b = canonicalJson(raw.attempts);\n if (a !== b) differences.push(`attempts differ:\\n eutaxy ${a}\\n raw ${b}`);\n const names = new Set([...Object.keys(eutaxy.state), ...Object.keys(raw.state)]);\n for (const name of [...names].sort()) {\n const x = canonicalJson(eutaxy.state[name] ?? []);\n const y = canonicalJson(raw.state[name] ?? []);\n if (x !== y) differences.push(`${name} differs:\\n eutaxy ${x}\\n raw ${y}`);\n }\n return differences;\n}\n","/**\n * Observe a module's pure core functions while runs are installed: each call\n * from outside the module is recorded with its arguments, for spec checks\n * on the inputs the simulator passed, and logged as a decision of the\n * invocation that made it (`Core:<function>`, payload `{ args, result }` or\n * `{ args, error }`), for `refines`. Calls the module makes to itself do not\n * go through its exports and are not seen.\n *\n * Observing replaces the export on the module's namespace object, which\n * works where a bundler or test runner gives modules a namespace with\n * configurable properties (Vite, so Vitest and the Cloudflare plugin); a\n * native ESM namespace is frozen, and the function is reported unobservable.\n */\n\nimport { type JsonValue, toJson } from \"@eutaxy/core\";\nimport { patchProperty } from \"./patch.ts\";\nimport { installedRun } from \"./run.ts\";\n\nexport interface ObservedCall {\n readonly function: string;\n /** The arguments as passed; primitives exactly, objects by reference. */\n readonly args: readonly unknown[];\n readonly threw: boolean;\n}\n\nexport interface CoreObserver {\n readonly calls: readonly ObservedCall[];\n /** Functions that could not be observed, with why. */\n readonly unobservable: { readonly [fn: string]: string };\n /** Put the original exports back. Safe to call twice. */\n restore(): void;\n}\n\nexport function observeCore(namespace: object, functions: readonly string[]): CoreObserver {\n const calls: ObservedCall[] = [];\n // No prototype: a function named __proto__ is an ordinary key.\n const unobservable: { [fn: string]: string } = Object.create(null);\n const undo: (() => void)[] = [];\n const target = namespace as Record<string, unknown>;\n for (const name of functions) {\n const original = target[name];\n if (typeof original !== \"function\") {\n unobservable[name] = `the module exports no function ${name}`;\n continue;\n }\n const wrapped = function (this: unknown, ...args: unknown[]): unknown {\n const run = installedRun();\n if (!run) return Reflect.apply(original, this, args);\n const record = (threw: boolean, payload: { result: JsonValue } | { error: string }) => {\n calls.push({ function: name, args: [...args], threw });\n run.decision(name, { args: toJson(args), ...payload });\n };\n let value: unknown;\n try {\n value = Reflect.apply(original, this, args);\n } catch (err) {\n record(true, { error: String(err) });\n throw err;\n }\n if (typeof (value as { then?: unknown } | null)?.then === \"function\") {\n // Not a decision of a pure core: what it decides is not known when the call returns.\n run.unsupported(\n `core function ${name} returned a promise; observed core functions must be synchronous and pure`,\n );\n return value;\n }\n record(false, { result: toJson(value) });\n return value;\n };\n let restore: () => void;\n try {\n restore = patchProperty(target, name, { get: () => wrapped });\n } catch (err) {\n unobservable[name] = `its module's namespace cannot be changed here (${String(err)})`;\n continue;\n }\n if (target[name] !== wrapped) {\n restore();\n unobservable[name] = \"its module's namespace did not take the observer\";\n continue;\n }\n undo.push(restore);\n }\n let restored = false;\n return {\n calls,\n unobservable,\n restore() {\n if (restored) return;\n restored = true;\n for (const u of undo.reverse()) u();\n },\n };\n}\n"],"mappings":";AAcA,SAAgB,cAAc,OAA0B;CACtD,IAAI,UAAU,MAAM,OAAO;CAC3B,QAAQ,OAAO,OAAf;EACE,KAAK,WACH,OAAO,QAAQ,SAAS;EAC1B,KAAK;GACH,IAAI,CAAC,OAAO,SAAS,KAAK,GAAG,MAAM,IAAI,UAA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