eutaxy 0.16.1 → 0.17.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.
- package/README.md +6 -6
- package/dist/aws.d.mts +2 -2
- package/dist/aws.mjs +2 -2
- package/dist/bin.mjs +1 -1
- package/dist/{cli-KACykdzJ.mjs → cli-dK6w25AU.mjs} +13 -9
- package/dist/{cli-KACykdzJ.mjs.map → cli-dK6w25AU.mjs.map} +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/cloudflare.d.mts +14 -3
- package/dist/cloudflare.d.mts.map +1 -1
- package/dist/cloudflare.mjs +2 -2
- package/dist/{delivery-invariants-BfRnb9yR.mjs → delivery-invariants-BXCuv43L.mjs} +2 -2
- package/dist/{delivery-invariants-BfRnb9yR.mjs.map → delivery-invariants-BXCuv43L.mjs.map} +1 -1
- package/dist/{delivery-invariants-B8ZZnCZg.d.mts → delivery-invariants-D7DI7i8x.d.mts} +2 -2
- package/dist/{delivery-invariants-B8ZZnCZg.d.mts.map → delivery-invariants-D7DI7i8x.d.mts.map} +1 -1
- package/dist/{explore-DlwIUowm.d.mts → explore-Ci-xVeKU.d.mts} +2 -2
- package/dist/{explore-DlwIUowm.d.mts.map → explore-Ci-xVeKU.d.mts.map} +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +2 -2
- package/dist/{platform-DPJTjpSr.d.mts → platform-D4hlJjm3.d.mts} +26 -1
- package/dist/{platform-DPJTjpSr.d.mts.map → platform-D4hlJjm3.d.mts.map} +1 -1
- package/dist/{src-dkn6Illb.mjs → src-BiX530QY.mjs} +179 -18
- package/dist/src-BiX530QY.mjs.map +1 -0
- package/dist/{src-DWRaG5aV.mjs → src-DVqL5Rk_.mjs} +2 -2
- package/dist/{src-DWRaG5aV.mjs.map → src-DVqL5Rk_.mjs.map} +1 -1
- package/dist/{workerd-9Tt0BV-3.mjs → workerd-b1sqOnVc.mjs} +3751 -3277
- package/dist/workerd-b1sqOnVc.mjs.map +1 -0
- package/package.json +1 -1
- package/dist/src-dkn6Illb.mjs.map +0 -1
- package/dist/workerd-9Tt0BV-3.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"src-dkn6Illb.mjs","names":["realSetTimeout"],"sources":["../../core/src/canonical-json.ts","../../core/src/delivery.ts","../../core/src/selectors.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","/**\n * The delivery conventions every platform shares, and the differential\n * runner's raw sides with them: how an attempt names its invocation, which\n * pending event is delivered next, and the redelivery rule, which applies\n * the same reading of a platform's limit without any of its proxy code.\n */\n\nimport type { EventRef } from \"./platform.ts\";\nimport type { Bounds } from \"./scenario.ts\";\n\n/** The invocation one attempt of an event runs as: `<event>#<attempt>`, so a schedule's faults stay keyed when other events are removed. */\nexport function invocationOf(event: EventRef): string {\n return `${event.id}#${event.attempt}`;\n}\n\n/**\n * The pending event to deliver next, as the engine and the raw sides pick\n * it: the earliest by `at` (an event without one is due now), and the first\n * queued among equals. The index into `pending`. Pure.\n */\nexport function earliestEvent(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/**\n * The next attempt of an event that was not handled (a message not\n * acknowledged or deleted, a request its caller resends, an alarm that\n * failed), or null when it is dropped (dead-lettered, given up on). It is\n * delivered again while both the platform's own limit on redeliveries\n * (Queues' `max_retries`, the caller's `retries`, SQS's `maxReceiveCount`\n * less the first delivery, an alarm's six retries) and the scenario's\n * `maxRedeliveries` leave room; the redeliveries so far are `attempt - 1`.\n * Pure.\n */\nexport function redelivery(\n event: EventRef,\n limit: number,\n bounds: Pick<Bounds, \"maxRedeliveries\">,\n): EventRef | null {\n const redeliveries = event.attempt - 1;\n if (redeliveries >= limit || redeliveries >= bounds.maxRedeliveries) return null;\n return { ...event, attempt: event.attempt + 1 };\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/** A dot path split once, so a selector applied to many records does not split it per record. */\ntype PathParts = readonly string[];\nconst partsOf = (path: string): PathParts => (path === \"\" ? [] : path.split(\".\"));\nconst indexPattern = /^(0|[1-9]\\d*)$/;\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 return readParts(value, partsOf(path));\n}\n\nfunction readParts(value: JsonValue, parts: PathParts): JsonValue | undefined {\n let cur: JsonValue | undefined = value;\n for (const part of parts) {\n if (cur === null || typeof cur !== \"object\") return undefined;\n if (Array.isArray(cur)) {\n // Only a plain index reads an array: \"\", \" 1\" or \"1e0\" would also convert to a number.\n if (!indexPattern.test(part)) return undefined;\n cur = cur[Number(part)];\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\n/** A selector prepared once (its paths split, its conditions listed) for the records it is tried on. */\nexport type EffectPredicate = (record: EffectRecord) => boolean;\n\nexport function compileSelector(sel: EffectSelector): EffectPredicate {\n const where = Object.entries(sel.where ?? {}).map(([p, want]) => [partsOf(p), want] as const);\n const atLeast = Object.entries(sel.atLeast ?? {}).map(([p, min]) => [partsOf(p), min] as const);\n return (record) => {\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 for (const [parts, want] of where)\n if (!jsonEqual(readParts(record.payload, parts), want)) return false;\n for (const [parts, min] of atLeast) {\n const v = readParts(record.payload, parts);\n if (typeof v !== \"number\" || v < min) return false;\n }\n return true;\n };\n}\n\nexport function selectEffects(log: EffectLog, sel: EffectSelector): readonly EffectRecord[] {\n return log.entries.filter(compileSelector(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 * 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\n/** One entry of the effect log: an effect's call, its result, an injected fault, or an end-of-run snapshot. */\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\n/** The ordered record of what a run did at its effect boundaries, which invariants are checked against. */\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\n/** One injected fault: which effect of which invocation it hit, and what kind of fault it was. */\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\n/** What decided one run: the seed it drew from, the faults injected, and the turns picked when they were picked. */\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 compileSelector,\n type EffectSelector,\n getPath,\n jsonEqual,\n keyOf,\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 entries = log.entries;\n // A run's log is dense (entry i has seq i), so a record's neighbours are found by index; a log that\n // is not (a slice) is scanned for the index instead. Either way the walk stays close to the effect.\n const lastBelow = (seq: number): number => {\n if (entries[seq - 1]?.seq === seq - 1) return seq - 1;\n let i = entries.length - 1;\n while (i >= 0 && (entries[i] as EffectRecord).seq >= seq) i--;\n return i;\n };\n const firstAbove = (seq: number): number => {\n if (entries[seq + 1]?.seq === seq + 1) return seq + 1;\n const i = entries.findIndex((e) => e.seq > seq);\n return i === -1 ? entries.length : i;\n };\n /** The last record before `seq` in `invocation` that `pick` accepts. */\n const before = (seq: number, invocation: string, pick: (e: EffectRecord) => boolean) => {\n for (let i = lastBelow(seq); i >= 0; i--) {\n const e = entries[i] as EffectRecord;\n if (e.invocation === invocation && pick(e)) return e;\n }\n return undefined;\n };\n const isRead = inv.state ? compileSelector(inv.state.read) : null;\n const isWrite = inv.state ? compileSelector(inv.state.write) : null;\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 || !isRead || !isWrite) continue;\n const read = before(decision.seq, effect.invocation, isRead);\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 let write: EffectRecord | undefined;\n for (let i = firstAbove(read.seq); i < entries.length; i++) {\n const e = entries[i] as EffectRecord;\n if (e.seq >= effect.seq) break;\n if (\n e.invocation !== effect.invocation &&\n isWrite(e) &&\n (state.key === undefined || keyOf(e, state.key) === key)\n ) {\n write = e;\n break;\n }\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 const e = findSnapshot(log, target);\n if (!e) return undefined;\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/** The last snapshot recorded for a target, found from the end of the log. */\nfunction findSnapshot(log: EffectLog, target: string): EffectRecord | 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) return e;\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 const last = findSnapshot(log, target);\n return last === undefined ? [] : [last.seq];\n}\n\n/** The violation a state invariant reports when the target it reads was never snapshotted. */\nfunction noSnapshot(invariant: string, target: string): Violation {\n return { invariant, message: `no snapshot of ${target} was recorded`, keys: [], evidence: [] };\n}\n\nexport function checkEveryRow(log: EffectLog, inv: EveryRow): Violation | null {\n const rows = queryRows(log, inv.query);\n if (rows === undefined) return noSnapshot(inv.name, inv.query.target);\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) return noSnapshot(inv.name, inv.query.target);\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) return noSnapshot(inv.name, inv.state.target);\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 = new Set<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 missing.add(k);\n evidence.push(e.seq);\n }\n if (missing.size === 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) return noSnapshot(inv.name, q.target);\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\n/** Anything a scenario says must hold after every run, over the effect log or the end-of-run state. */\nexport type Invariant =\n | AtMostOncePerKey\n | AtLeastOnce\n | EveryRow\n | Implies\n | Unique\n | References\n | Refines;\n\n/** An invariant that did not hold: its name, what went wrong, the keys involved and the effects that show it. */\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\n/** Check one invariant against a run's effect log; null when it holds. */\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\n/** Check every invariant against a run's effect log and return the violations, in the invariants' order. */\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\n/**\n * A scenario as plain data: the Worker, the drive, the setup, the externals, the invariants and the\n * bounds, which `defineScenario` (or a platform's equivalent) builds and validates.\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 else 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.platform !== undefined && !spec.platform)\n errors.push(\"platform must not be empty when given\");\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 else 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, then firing the earliest timer already\n * due when one may fire; 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 in due order and never race real I/O:\n * in a sequential run only while the invocation is idle (no effect in\n * flight); in a concurrent run one already due is a turn like a parked\n * effect, and one not yet due fires only when nothing else can move.\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 /** The host (`EffectOptions.host`) whose code scheduled it, when the run tells (`scopeNow`): whose work it is once its effect has ended. */\n readonly scope: unknown;\n /**\n * Run by a poller armed where it was scheduled, inside the host's code, not\n * by `fireNext`: workerd refuses to settle a Durable Object's promise from\n * outside it. How many times it has fired and not yet run.\n */\n readonly deferred: boolean;\n /**\n * The run's own deadline (`setTimeoutAs`): fires whenever time reaches it,\n * whoever's timers may fire then, since what it measures (a step attempt's\n * timeout) runs independently of the work in flight.\n */\n readonly deadline: boolean;\n fired: number;\n}\n\nexport class VirtualClock {\n private time = virtualEpoch;\n private timers: Timer[] = [];\n /** Deferred timers fired and not yet run by their pollers: work on its way, inside a host. */\n private readonly unrun = new Set<Timer>();\n /** Set by `stop`: the run is over, so no timer is pending and every deferred poller ends. */\n private stopped = false;\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 the run: the effect being performed by the code scheduling a timer, kept on the timer. */\n scopeNow: (() => unknown) | null = null;\n /** Set by the run: told whose timer fired (or was marked fired), whichever path fired it. */\n afterFire: ((owner: string | null) => void) | 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 owner?: string,\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: owner ?? (this.ownerNow ? this.ownerNow() : this.owner),\n // The run's own deadline is set from the run loop, outside any effect: never deferred.\n scope: owner === undefined ? this.scopeNow?.() : undefined,\n deferred: false,\n deadline: owner !== undefined,\n fired: 0,\n };\n if (this.stopped) return timer.id;\n // Inside a host's code in workerd, the timer must be run from inside it too: a poller armed here.\n if (timer.scope !== undefined && inWorkerd) {\n (timer as { deferred: boolean }).deferred = true;\n this.pollDeferred(timer);\n }\n this.timers.push(timer);\n return timer.id;\n }\n\n /**\n * Run a deferred timer's callback from where it was scheduled: a real zero\n * timer made here, inside the host's code, polls until `fireNext` has\n * fired it (as often as it fired, for an interval) or it was cleared.\n */\n private pollDeferred(timer: Timer): void {\n const tick = (): void => {\n while (timer.fired > 0) {\n timer.fired--;\n if (timer.fired === 0) this.unrun.delete(timer);\n try {\n timer.callback(...timer.args);\n } catch {\n // As for a timer `fireNext` runs: an exception in the callback does not stop the run.\n }\n }\n if (timer.fired > 0 || this.timers.includes(timer)) realSetTimeout(tick, 0);\n };\n realSetTimeout(tick, 0);\n }\n\n setTimeout(callback: (...args: unknown[]) => void, delay = 0, ...args: unknown[]): number {\n return this.schedule(callback, delay, args, null);\n }\n\n /**\n * A timer of `owner`'s set by the run itself, whoever is running (an\n * attempt's deadline): cancelled with the owner's others, and fired\n * whenever time reaches it, whoever's timers may fire then (an object\n * napping inside the attempt's call does not hold the engine's clock).\n */\n setTimeoutAs(owner: string, callback: () => void, delay: number): number {\n return this.schedule(callback, delay, [], null, owner);\n }\n\n setInterval(callback: (...args: unknown[]) => void, delay = 0, ...args: unknown[]): number {\n // Hosts run an interval with no usable delay (NaN, 0, negative) every millisecond.\n const every = Number.isFinite(delay) && delay >= 1 ? Math.floor(delay) : 1;\n return this.schedule(callback, delay, args, every);\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 /**\n * The run is over: drop every timer, fired or not, so the pollers armed\n * inside hosts' code end (one left polling would keep an object referenced\n * past the run) and nothing of the run's fires later.\n */\n stop(): void {\n this.stopped = true;\n for (const t of this.unrun) t.fired = 0;\n this.unrun.clear();\n this.timers = [];\n }\n\n /** Deferred timers fired and not yet run: what waits on nothing visible is still about to move. */\n firedPending(): number {\n return this.unrun.size;\n }\n\n /** Whether a timer scheduled inside the effect `scope` is still pending. */\n hasTimerIn(scope: unknown): boolean {\n return scope !== undefined && this.timers.some((t) => t.scope === scope);\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 for (const t of this.unrun)\n if (t.owner === owner) {\n t.fired = 0;\n this.unrun.delete(t);\n }\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 /** Advance to the earliest due timer whose owner `owned` accepts and run it. False when none is pending. */\n fireNextOwned(owned: (owner: string | null) => boolean): boolean {\n const earliest = this.earliestOwned(owned);\n if (!earliest) return false;\n return this.fire(earliest);\n }\n\n /**\n * When the earliest timer whose owner `owned` accepts is due, or undefined\n * when none is pending; a deadline (`setTimeoutAs`) counts, as it fires,\n * unless `deadlines` is false: whether an owner has a timer of its own to\n * advance to (an object sleeping before it answers) is asked without them.\n */\n nextDueOwned(owned: (owner: string | null) => boolean, deadlines = true): number | undefined {\n return this.earliestOwned(owned, deadlines)?.due;\n }\n\n private earliestOwned(\n owned: (owner: string | null) => boolean,\n deadlines = true,\n ): Timer | undefined {\n let earliest: Timer | undefined;\n for (const t of this.timers)\n if (\n ((deadlines && t.deadline) || owned(t.owner)) &&\n (!earliest || t.due < earliest.due || (t.due === earliest.due && t.id < earliest.id))\n )\n earliest = t;\n return earliest;\n }\n\n /** Who set the timer `fireNextOwned` would run for `owned`; undefined when none is pending. */\n nextOwnerOwned(owned: (owner: string | null) => boolean): string | null | undefined {\n return this.earliestOwned(owned)?.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 return this.fire(earliest);\n }\n\n private fire(earliest: Timer): boolean {\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 if (earliest.deferred) {\n // Its poller, inside the host's code, runs it on the next real tick: until then it is on its way.\n earliest.fired++;\n this.unrun.add(earliest);\n } else {\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 }\n this.afterFire?.(earliest.owner);\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: () => T): 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: () => T): T {\n return libraryScope ? libraryScope.run(false, work) : work();\n },\n restore() {\n if (restored) return;\n restored = true;\n clock.stop();\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 /**\n * What to reject with once `crashed` is true, seen on the wait's own tick\n * (a promise settled where the crash happened may never wake its waiters:\n * the object's task is being torn down); without it the wait hangs.\n */\n readonly crashError?: () => unknown;\n /** Called when nothing can make progress: no I/O, no timers, not done. */\n readonly stuck: () => void;\n /**\n * While I/O is in flight: whose timers may fire anyway, when everything in\n * flight is a hosting effect whose code is idle and so awaits a timer of\n * its own (an object sleeping before it answers); null otherwise.\n */\n readonly idle?: () => ((owner: string | null) => boolean) | null;\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 // After a timer fires, its callback's work is microtasks and more timers: the cheap turn of the\n // event loop is enough to see it, where a real zero timer would cost a millisecond per virtual\n // timer. While real I/O is in flight, and once before calling the wait stuck, the real tick stays.\n let afterTimer = false;\n // Whether the last tick too found only idle hosting effects in flight: code that waits on\n // nothing visible gets one real tick for work the run cannot see before its timer fires.\n let idleBefore = false;\n for (;;) {\n await Promise.race([tracked, afterTimer ? eventLoopTurn() : realTick()]);\n const cheap = afterTimer;\n afterTimer = false;\n if (done) {\n if (failed) throw error;\n return value as T;\n }\n if (ctx.crashed()) {\n if (ctx.crashError) throw ctx.crashError();\n return new Promise<T>(() => {});\n }\n if (ctx.inFlight() > 0) {\n const owned = ctx.idle?.() ?? null;\n if (owned && idleBefore && ctx.clock.fireNextOwned(owned)) {\n idleBefore = false;\n afterTimer = true;\n } else idleBefore = owned !== null;\n continue;\n }\n idleBefore = false;\n if (ctx.clock.fireNext()) {\n afterTimer = true;\n continue;\n }\n if (cheap) 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\n/**\n * The scripted reply as a `Response`. Its body is known, so `text()` and\n * `json()` answer from it within a microtask: the model assumes body reads\n * settle within one turn of the event loop, and a stream read inside a\n * Durable Object can take a turn or more, during which the object's code\n * looks idle to the run.\n */\nexport function toResponse(reply: Reply): Response {\n const response = new Response(reply.body === \"\" ? null : reply.body, {\n status: reply.status,\n headers: reply.headers,\n });\n const text = reply.body;\n Object.defineProperties(response, {\n text: { value: () => Promise.resolve(text), configurable: true, writable: true },\n json: {\n value: () => Promise.resolve().then(() => JSON.parse(text) as unknown),\n configurable: true,\n writable: true,\n },\n });\n return response;\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 // A body given as text is read as it is, without a turn of the event loop: the effect opens in\n // the same task as the call, so the run never sees the caller idle in between (a stream read\n // inside a Durable Object can take a turn or more). Other bodies are read as before.\n const given = init?.body;\n const text =\n typeof given === \"string\"\n ? given\n : given === null || (given === undefined && !(input instanceof Request))\n ? \"\"\n : await request.text();\n const body = parseBody(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, EffectPoint } 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 readonly target: string;\n readonly op: string;\n /** Whether the effect hosts user code that makes effects of its own (`hostsEffects`). */\n readonly hosts: boolean;\n /** Whose code the effect hosts, when it stays alive after the effect (`EffectOptions.host`). */\n readonly host: string | undefined;\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 /** Set by the run: told, after `onAbandon` reset the host, which host it was. */\n onHostAbandoned: ((host: string) => 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 /** Effects nested in this one (made inside its perform, not as turns) being performed now. */\n performing = 0;\n /** A host's effect whose call the host's code has started (`Frames.claimHost`). */\n claimed = false;\n /** The host's code this effect is the call of has started running (`Run.hostedCode`); until then the call is in transit. */\n entered = false;\n /** The host's code this effect is the call of has returned (`Frames.answered`): its answer is in transit. */\n answered = false;\n /**\n * The attempt (`RunHooks.attempt`) whose code made this effect, if any: what\n * the effect hosts is that attempt's code too, late once the attempt is.\n */\n attempt: { readonly late: boolean } | undefined;\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(\n point: Pick<EffectPoint, \"invocation\" | \"target\" | \"op\" | \"hostsEffects\">,\n options: EffectOptions,\n ) {\n this.invocation = point.invocation;\n this.target = point.target;\n this.op = point.op;\n this.hosts = point.hostsEffects === true;\n this.host = options.host;\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 /**\n * Whether it counts as real I/O pending: unless its hosted code is only\n * waiting on parked effects of its own; once that code has answered, the\n * answer is on its way whatever it left parked, so the effect counts again\n * until it ends.\n */\n inFlight(): boolean {\n return this.answered || !this.isWaiting();\n }\n\n crash(): void {\n this.wake();\n this.abandon();\n }\n\n /** Whether the effect was abandoned: a crash in its hosted code, or its I/O past the budget; the host was reset. */\n get isAbandoned(): boolean {\n return this.abandoned;\n }\n\n /**\n * The run's bookkeeping first, the platform's reset last: a Durable\n * Object's `abort()` tears down the task it is called in, so nothing after\n * it may be counted on to run.\n */\n abandon(): void {\n if (this.abandoned) return;\n this.abandoned = true;\n if (this.host !== undefined) this.onHostAbandoned?.(this.host);\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 /** Per host (`EffectOptions.host`), its effects being performed, innermost last. */\n private readonly byHost = new Map<string, Frame[]>();\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 /** The innermost effect of `host`'s being performed now, if any: code of the host's runs inside it. */\n liveHost(host: string): Frame | undefined {\n return this.byHost.get(host)?.at(-1);\n }\n\n /** The effects of `invocation`'s being performed now that host an object's code (`EffectOptions.host`). */\n hostingOf(invocation: string): Frame[] {\n return this.stack.filter((f) => f.invocation === invocation && f.host !== undefined);\n }\n\n /**\n * The oldest effect of `host`'s being performed, with `op` when given, whose\n * call the host's code has not started yet, now claimed: an object's input\n * gate delivers calls in the order they arrived, which is the order their\n * effects entered. Without one of that op, the oldest unclaimed of any.\n */\n claimHost(host: string, op?: string): Frame | undefined {\n const live = this.byHost.get(host) ?? [];\n const frame =\n (op === undefined ? undefined : live.find((f) => !f.claimed && f.op === op)) ??\n live.find((f) => !f.claimed);\n if (frame) frame.claimed = true;\n return frame;\n }\n\n /**\n * The hosts of the effects in flight, when every one of them is a hosting\n * effect whose hosted code is idle: running (entered, its answer not yet\n * on its way), with no effect of it performing or waiting for a turn,\n * nothing hosted inside it and no real work tracked. Such code can only\n * be awaiting a timer of its own (an object sleeping before it answers),\n * which the run may fire for it. Null while anything else is in flight,\n * or nothing is: a call still crossing into its object is on its way, and\n * waiting for it keeps the order in which calls enter the object the\n * schedule's, not real time's (two timers due together fire by the order\n * they were set).\n */\n idleHosts(): Set<string> | null {\n let counted = 0;\n const hosts = new Set<string>();\n for (const frame of this.stack) {\n if (frame.isWaiting()) continue;\n counted++;\n if (\n frame.host === undefined ||\n !frame.entered ||\n frame.answered ||\n frame.performing > 0 ||\n frame.children > 0\n )\n return null;\n hosts.add(frame.host);\n }\n return counted > 0 && counted === this.inFlight ? hosts : null;\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) or absent (workerd carries none\n * into an object's code): trust only a live frame of the same invocation\n * (the innermost); else, for code in a stale context or hosted code\n * (`hosted`: an object's, entered by the platform), the invocation's own\n * hosting effect. Code in no context at all that is not hosted is\n * outside every effect: a second strand of the invocation (a step\n * attempt the engine gave up on, see `Run.attempt`) running while a call\n * of the first strand is in flight.\n */\n enclosing(invocation: string, hosted = true): Frame | undefined {\n if (!effectScope) return this.stack.at(-1);\n const store = effectScope.getStore();\n if (store?.active && store.invocation === invocation) return store;\n return hosted || store !== undefined ? this.hosting.get(invocation)?.at(-1) : undefined;\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 if (frame.host !== undefined) {\n const frames = this.byHost.get(frame.host) ?? [];\n frames.push(frame);\n this.byHost.set(frame.host, frames);\n }\n }\n\n /**\n * The host's code `frame` is the call of has returned: its answer is in\n * transit, so the effect is in flight until it ends, whatever that code\n * left parked (the run waits for the answer before its next turn, so what\n * the code left outstanding is handed over before anything else moves).\n */\n answered(frame: Frame): void {\n if (frame.answered) return;\n const before = frame.inFlight();\n frame.answered = true;\n if (frame.active && !before) this.inFlight++;\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 if (frame.host !== undefined) {\n const frames = this.byHost.get(frame.host);\n frames?.splice(frames.lastIndexOf(frame), 1);\n }\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.inFlight()) this.inFlight--;\n if (frame.isWaiting() && 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 waitingBefore = frame.isWaiting();\n const inFlightBefore = frame.inFlight();\n change();\n const waiting = frame.isWaiting();\n if (frame.active && inFlightBefore !== frame.inFlight()) this.inFlight += waiting ? -1 : 1;\n if (waitingBefore === waiting) return;\n const parent = frame.parent;\n if (frame.active && parent)\n this.adjust(parent, () => (parent.waitingChildren += waiting ? 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 * whether a new event starts, or whether a virtual timer already due fires\n * (ready work like a parked effect; timers not yet due fire only when\n * nothing else can move). It also tracks whether turns told apart by their\n * parked effects' targets may not commute, which partial-order reduction\n * 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\n/** A virtual timer already due that may fire now, offered as a turn (see `Run.takeTurn`). */\nexport interface DueTimer {\n /** The invocation that set it, which its callback runs as. */\n readonly owner: string | null;\n /** Timers of that owner fired so far: names the turn the same in every run. */\n readonly fired: number;\n /** Fire it: the earliest due timer the run allows, as its owner. */\n readonly fire: () => void;\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 /**\n * The attempt whose code parked here, if any, read live: a late attempt's\n * turn is offered like any other, but holds nothing (see `takeTurn`).\n */\n readonly attempt: { readonly late: boolean } | undefined;\n /** The turn as a choice: its label and the target of the effect it performs. */\n readonly option: ChoiceOption;\n}\n\n/**\n * How often one run may let time pass over late turns before they must run:\n * a stray interval would otherwise be fired forever while late code waits.\n */\nexport const waitLimit = 100;\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 /** Work on its way that no frame counts: a host's timer fired and not yet run by its poller. */\n private readonly pending: () => number;\n /** Whether an object's work after an answer may be running: a wake could then come from inside it. */\n private readonly inObjects: () => boolean;\n /** Whether everything in flight is a hosting effect whose code is idle (see `Frames.idleHosts`). */\n private readonly idleHosted: () => boolean;\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 /** Times the run let time pass over late turns (see `takeTurn`). */\n private waits = 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 pending: () => number = () => 0,\n inObjects: () => boolean = () => false,\n idleHosted: () => boolean = () => false,\n ) {\n this.chooser = chooser;\n this.frames = frames;\n this.runAs = runAs;\n this.reads = reads;\n this.pending = pending;\n this.inObjects = inObjects;\n this.idleHosted = idleHosted;\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(\n inv: Turner,\n target: string,\n go: () => void,\n host?: Frame,\n attempt?: { readonly late: boolean },\n ): void {\n const option = { label: `${inv.id}@${inv.parks++}`, invocation: inv.id, target };\n this.parked.push({ inv, seq: this.parkSeq++, go, option, attempt, ...(host ? { host } : {}) });\n this.rested();\n }\n\n /**\n * The hosting effect `host` ended with effects of its hosted code parked:\n * they are `owner`'s turns now (the host's work after its answer), so the\n * caller's crash does not drop them and a fault in them is the owner's.\n */\n adopt(host: Frame, owner: Turner): void {\n this.parked = this.parked.map((p) =>\n p.host === host ? { ...p, inv: owner, option: { ...p.option, invocation: owner.id } } : p,\n );\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, or an object's work after its answer), a wake\n // could come from inside it (a park, an event queued), and the scheduler would resume in that\n // object's I/O context, where workerd refuses other calls (\"Cannot perform I/O on behalf of a\n // different Durable Object\") and counts what it then does against the object. The scheduler's\n // own zero timer polls for the move then instead (see quiesce).\n if (this.frames.hostingNow > 0 || this.inObjects()) 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 // A host's timer fired and not yet run is on its way.\n if (this.pending() > 0) continue;\n // Real I/O: its completion wakes the next wait, and hosted code's moves show at its end. When\n // only hosting effects whose code is idle are in flight and a wait saw nothing move, that\n // code awaits a timer of its own (an object sleeping before it answers): at rest, for the\n // run to fire it.\n if (this.frames.inFlight > 0) {\n if (!moved && this.idleHosted()) return;\n continue;\n }\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 /**\n * See `Run.takeTurn`. `canWait`: whether, with nothing else to do, the run\n * could let time pass (a timer is pending or a delayed event is due later).\n * While every parked turn is late (`RunHooks.attempt`) and nothing else is\n * on offer, waiting is an option too, so the late code's next move lands\n * before or after what the time brings; \"none\" then means the run should\n * let time pass as when nothing is parked.\n */\n takeTurn(\n canStart: boolean,\n timer?: DueTimer,\n canWait = false,\n ): \"turn\" | \"start\" | \"timer\" | \"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 waiting =\n canWait &&\n !canStart &&\n !timer &&\n this.waits < waitLimit &&\n this.parked.length > 0 &&\n this.parked.every((p) => p.attempt?.late === true);\n const offered = this.turnOptions(canStart, timer, waiting);\n const options = offered.length;\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\", offered);\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 // Past the parked turns, which were all late: time passes over them.\n if (waiting) {\n this.waits++;\n return \"none\";\n }\n // Past the parked turns: the due timer is the last option when there is one, else the start.\n if (timer && pick === options - 1) {\n // Like a start, a timer turn is ordered against every other (its option has no target), so\n // what its callback does is not a turn's own effect: turnTarget stays null.\n timer.fire();\n return \"timer\";\n }\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 /**\n * The turns on offer, as choices: the parked invocations in order, then\n * starting the next event, then the due timer (last, so a recorded pick\n * of the others means the same with or without it), or, when every parked\n * turn is late and nothing else is offered, letting time pass. A timer's\n * option names its owner and how many of that owner's timers have fired,\n * and has no target: the callback may do anything, and firing it reads\n * virtual time, so it commutes with nothing; so does waiting, which fires\n * the next timer.\n */\n private turnOptions(canStart: boolean, timer?: DueTimer, waiting = false): ChoiceOption[] {\n return [\n ...this.parked.map((p) => p.option),\n ...(canStart ? [{ label: `start:${this.starts}` }] : []),\n ...(timer\n ? [\n {\n label: `timer:${timer.owner ?? \"\"}@${timer.fired}`,\n ...(timer.owner !== null ? { invocation: timer.owner } : {}),\n },\n ]\n : []),\n ...(waiting ? [{ label: `wait:${this.waits}` }] : []),\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 type Attempt,\n type Bounds,\n decisionTarget,\n type EffectLog,\n type EffectOptions,\n type EffectPoint,\n type EffectRecord,\n type EventRef,\n type ExternalDecl,\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} from \"./clock.ts\";\nimport { asyncScope } from \"./context.ts\";\nimport { installScriptedFetch } from \"./fetch.ts\";\nimport { effectScope, Frame, Frames } from \"./frames.ts\";\n\n/** The host's own timer, captured before any patching: a host poller's ticks are real. */\nconst realSetTimeout = globalThis.setTimeout.bind(globalThis);\n\nimport { type DueTimer, 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: (inside?: Frame) => 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: (inside?: Frame) => 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 /** `inside`: the effect the crash happened inside of, when one did (a nested effect's fault). */\n crash(inside?: Frame): void {\n if (this.crashedFlag) return;\n this.crashedFlag = true;\n this.onCrash(inside);\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/**\n * The host (`EffectOptions.host`) whose code is running, set by `hostedCode`:\n * an object's, which the runtime enters without async context, and the\n * effect of the host's whose call that code is, when it is known.\n */\ninterface HostContext {\n readonly host: string;\n readonly frame: Frame | undefined;\n}\nconst hostScope = asyncScope<HostContext | undefined>();\n\n/** The attempt (`RunHooks.attempt`) whose code is running, and whether the platform has given up on it. */\ninterface AttemptCell {\n late: boolean;\n}\nconst attemptScope = asyncScope<AttemptCell>();\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/**\n * Timers an object's work may fire without the work settling before the run\n * is called UNSUPPORTED: a heartbeat (`setInterval`, a timeout that re-arms\n * itself) never settles, and the runtime would run it until the object is\n * evicted, which a run cannot wait for. The count starts over each time the\n * work settles, so an object that sleeps once per call is not a heartbeat.\n */\nexport const afterWorkTimerLimit = 100;\n\n/** Delivered invocations are `<event>#<attempt>`, so this id is never one of theirs. */\nconst bookkeepingId = \"platform\";\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\nexport class Run implements RunHooks {\n /** The records, appended in place. */\n private readonly entries: EffectRecord[] = [];\n /**\n * The log last handed out, a snapshot of the records then: what a run returned never changes\n * under its reader, however late an abandoned effect's I/O records its result. Rebuilt on the\n * next read after a record, so a run reads it once at its end and a differential once per event.\n */\n private logView: EffectLog | null = null;\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 /** Per host (`EffectOptions.host`), the invocation its work after an answer runs as; see `continuationOf`. */\n private readonly continuations = new Map<string, InvocationState>();\n /** Per host, how many such invocations it has had: one more after each reset of the object. */\n private readonly continuationCounts = new Map<string, number>();\n /** Per host, the last of its effects performed: its `onAbandon` resets the object when its later work crashes. */\n private readonly hostFrames = new Map<string, Frame>();\n /** Continuations with work that may still move: the run does not end while one is alive. */\n private readonly afterWork = new Set<InvocationState>();\n /** Per continuation, timers of its fired since its work last settled (see `afterWorkTimerLimit`). */\n private readonly afterWorkTimers = new Map<string, number>();\n /** Per owner, timers fired so far (any path): names a timer turn (see `dueTimer`). */\n private readonly timersFired = new Map<string | null, number>();\n /** Per host, real work its code started and the run tracks (Web Crypto) still running; see `leftHost`. */\n private readonly hostIo = new Map<string, number>();\n /**\n * Hosting effects that ended with effects of their hosted code outstanding\n * (parked or performing), and the host's work after its answer, which owns\n * those effects from then on; see `ownerOf`.\n */\n private readonly adopted = new WeakMap<Frame, InvocationState>();\n /** Per host, its poller (concurrent runs; see `pollHost`). */\n private readonly hostPollers = new Map<string, { waiters: (() => void)[] }>();\n /** Concurrent runs: settles waiting on invocations, released with a `CrashSignal` once theirs crashed; see `settle`. */\n private crashWatch: { readonly inv: InvocationState; readonly reject: (err: unknown) => void }[] =\n [];\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 private 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 () => this.firedPending(),\n () => this.hasAfterWork(),\n () => this.timersAllowed() !== null,\n );\n this.concurrent = options.bounds.maxConcurrentInvocations > 1;\n }\n\n get log(): EffectLog {\n this.logView ??= { entries: [...this.entries] };\n return this.logView;\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 // A host's code's is the host's: work of its own still pending once its effect has ended.\n trackIo: (work) => {\n this.frames.inFlight++;\n const host = hostScope?.getStore()?.host;\n if (host !== undefined) this.hostIo.set(host, (this.hostIo.get(host) ?? 0) + 1);\n return work.finally(() => {\n this.frames.inFlight--;\n if (host !== undefined) {\n const left = (this.hostIo.get(host) ?? 1) - 1;\n if (left > 0) this.hostIo.set(host, left);\n else this.hostIo.delete(host);\n }\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.timerOwner();\n // Whose code set a timer: a host's timers are the host's, pending work of its own once its effect ends.\n clock.scopeNow = () => hostScope?.getStore()?.host;\n // Whichever path fires a timer of an object's work counts it against the heartbeat bound.\n clock.afterFire = (owner) => {\n this.timersFired.set(owner, (this.timersFired.get(owner) ?? 0) + 1);\n if (owner !== null) this.timerFired(owner);\n };\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 // A host's code's timer runs as the host's code too (the runtime does that where it runs it).\n const inHostCtx = hostScope?.getStore();\n const inHost = (fn: () => void): void => {\n if (hostScope && inHostCtx !== undefined) hostScope.run(inHostCtx, fn);\n else fn();\n };\n // An attempt's timer callback is the attempt's code still (`RunHooks.attempt`).\n const inAttemptCell = attemptScope?.getStore();\n const inAttempt = (fn: () => void): void => {\n if (attemptScope && inAttemptCell !== undefined) attemptScope.run(inAttemptCell, fn);\n else fn();\n };\n return (...args) => scope.run(cell, () => inHost(() => inAttempt(() => 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 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 host's code running while none of its effects is performed: its work after an answer, its continuation's.\n const host = this.afterWorkHost();\n if (host !== undefined) return this.continuationOf(host).id;\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 hostedCode<T>(host: string, code: () => T, op?: string): T {\n // The host's code entering again (a method calling another of the object's): the same call.\n if (hostScope?.getStore()?.host === host) return code();\n if (this.concurrent) this.pollHost(host);\n // The call this code is: the host's effect being performed around it (an alarm, a WebSocket\n // message, run by the platform inside the effect), else the oldest of the host's effects with\n // this op whose call has not started (a stub call: the object's input gate delivers them in\n // arrival order).\n const current = this.frames.current();\n const frame =\n current?.host === host && current.active ? current : this.frames.claimHost(host, op);\n // The call has crossed into the object: its code runs from here.\n if (frame) frame.entered = true;\n // An object's code is handler code: its timers are virtual, inside a call's I/O or not.\n const run = (): T => (this.patched ? this.patched.handlerCode(code) : code());\n const result = hostScope ? hostScope.run({ host, frame }, run) : run();\n // Once the code has returned its answer is in transit: the call is no longer idle code that a\n // timer of the host's may wake (a timer it set and did not await fires after the answer), and\n // it is in flight until the answer has crossed, whatever the code left parked.\n if (frame) {\n const answered = (): void => this.frames.answered(frame);\n if (isThenable(result)) void Promise.resolve(result).then(answered, answered);\n else answered();\n }\n return result;\n }\n\n /**\n * Concurrent runs: the host's poller, a real zero timer armed here, inside\n * the host's code during its request, and re-armed from its own ticks while\n * the host may still move (an effect of its being performed, work of its\n * own alive, a wait pending). Each tick wakes the host's waits (`hostTick`):\n * the host's work after an answer waits for its turns on them, since a\n * timer that work armed itself, after its request completed, would keep the\n * object referenced in workerd.\n */\n private pollHost(host: string): void {\n if (this.hostPollers.has(host)) return;\n const poller = { waiters: [] as (() => void)[] };\n this.hostPollers.set(host, poller);\n const tick = (): void => {\n const waiters = poller.waiters;\n poller.waiters = [];\n for (const wake of waiters) wake();\n if (poller.waiters.length > 0 || this.hostMayMove(host)) realSetTimeout(tick, 0);\n else this.hostPollers.delete(host);\n };\n realSetTimeout(tick, 0);\n }\n\n private hostMayMove(host: string): boolean {\n const cont = this.continuations.get(host);\n const alive = cont !== undefined && !cont.isCrashed() && this.afterWork.has(cont);\n return alive || this.frames.liveHost(host) !== undefined;\n }\n\n /** One tick of the host's poller, from inside the host's code; a real tick where no poller is armed. */\n private hostTick(host: string): Promise<void> {\n const poller = this.hostPollers.get(host);\n if (!poller) return realTick();\n return new Promise((resolve) => poller.waiters.push(resolve));\n }\n\n /**\n * The invocation a timer set now belongs to: a host's timers are the\n * host's, its continuation's, inside a call or after it, so the caller's\n * crash does not cancel them and a crash of the host's work does.\n */\n private timerOwner(): string {\n const ctx = hostScope?.getStore();\n if (ctx !== undefined) return this.continuationOf(ctx.host).id;\n return this.running();\n }\n\n /**\n * The host whose code is running after the effect it was entered by has\n * ended (or, where that effect is not known, while none of its effects is\n * being performed), if any: work after an answer.\n */\n private afterWorkHost(): string | undefined {\n const ctx = hostScope?.getStore();\n if (ctx === undefined) return undefined;\n const inside = ctx.frame ? ctx.frame.active : this.frames.liveHost(ctx.host) !== undefined;\n return inside ? undefined : ctx.host;\n }\n\n /**\n * The invocation a host's work after an answer runs as, `<host>/after`\n * (`#<n>` once the object was reset: a new instance's work is a new\n * invocation's), started on first use and alive until `settleAfterWork`;\n * work woken later revives it.\n */\n private continuationOf(host: string): InvocationState {\n let cont = this.continuations.get(host);\n if (!cont) {\n const n = (this.continuationCounts.get(host) ?? 0) + 1;\n this.continuationCounts.set(host, n);\n cont = this.track(`${host}/after${n > 1 ? `#${n}` : \"\"}`);\n this.continuations.set(host, cont);\n if (this.concurrent) this.turns.started(cont.id);\n }\n if (!cont.isCrashed()) this.afterWork.add(cont);\n return cont;\n }\n\n hostReset(host: string): void {\n this.hostAbandoned(host);\n }\n\n /**\n * The host was reset (`onAbandon` ran: a crash inside its code, an effect\n * of its that hung; or the platform dropped the instance, `hostReset`): its\n * work after an answer is gone with the instance, timers included, and its\n * poller with it.\n */\n private hostAbandoned(host: string): void {\n this.hostPollers.delete(host);\n const cont = this.continuations.get(host);\n if (!cont) return;\n this.continuations.delete(host);\n this.afterWork.delete(cont);\n cont.crash();\n }\n\n /**\n * A host's effect ended: work its code left outstanding (effects parked or\n * performing, timers pending, real work tracked) is the host's own now,\n * its continuation's, which owns the outstanding effects from here on\n * (see `ownerOf`): the caller's crash does not end them, and a fault in\n * them is the object's.\n */\n private leftHost(frame: Frame): void {\n // An abandoned effect reset the object: what its code left outstanding died with the instance.\n if (frame.host === undefined || frame.isAbandoned) return;\n this.hostFrames.set(frame.host, frame);\n const effects = frame.children > 0 || frame.performing > 0;\n if (\n !effects &&\n !this.patched?.clock.hasTimerIn(frame.host) &&\n (this.hostIo.get(frame.host) ?? 0) === 0\n ) {\n // Nothing outstanding: the object's work has settled, so a heartbeat is counted from here (a\n // call that slept once is not one, however many such calls one handler makes).\n const cont = this.continuations.get(frame.host);\n if (cont) this.afterWorkTimers.delete(cont.id);\n return;\n }\n const cont = this.continuationOf(frame.host);\n if (!effects) return;\n this.adopted.set(frame, cont);\n if (this.concurrent) this.turns.adopt(frame, cont);\n }\n\n /**\n * Who owns an effect of `inv`'s made inside `enclosing`: `inv`, unless the\n * enclosing effect was a host's, ended while this one was outstanding and\n * handed it to the host's work after its answer (`leftHost`). The call's\n * invocation may be long finished or crashed then; the object goes on.\n */\n private ownerOf(inv: InvocationState, enclosing: Frame | undefined): InvocationState {\n const adopted = enclosing && this.adopted.get(enclosing);\n return adopted && enclosing.invocation === inv.id ? adopted : inv;\n }\n\n /**\n * A timer of a continuation's fired, by whichever path: its count against\n * `afterWorkTimerLimit` since its work last settled; past it the object's\n * work does not settle, so the run is UNSUPPORTED and the work ends (its\n * timers with it).\n */\n private timerFired(owner: string): void {\n let cont: InvocationState | undefined;\n for (const c of this.continuations.values()) if (c.id === owner) cont = c;\n if (!cont || cont.isCrashed()) return;\n const n = (this.afterWorkTimers.get(owner) ?? 0) + 1;\n this.afterWorkTimers.set(owner, n);\n if (n <= afterWorkTimerLimit) return;\n this.unsupported(\n `${owner}: the object's work after its answer fired its timers ${n} times and does not settle (an interval or a timer that re-arms itself); the model waits for such work only up to ${afterWorkTimerLimit} firings without it settling`,\n );\n this.afterWork.delete(cont);\n cont.crash();\n }\n\n /** A host's timers fired and not yet run by their pollers inside it: work on its way. */\n private firedPending(): number {\n return this.patched?.clock.firedPending() ?? 0;\n }\n\n /** Whether an object's work after an answer may still move; the run does not end while it may. */\n hasAfterWork(): boolean {\n for (const cont of this.afterWork) if (!cont.isCrashed()) return true;\n return false;\n }\n\n /**\n * Nothing can move (no effect in flight, no turn to take, no timer due):\n * every continuation alive has settled, as an object with nothing pending\n * goes idle. How many did; work of theirs woken later revives them.\n */\n settleAfterWork(): number {\n const n = this.afterWork.size;\n // Settled: a heartbeat is counted from here (an object that sleeps once per call is not one).\n for (const cont of this.afterWork) this.afterWorkTimers.delete(cont.id);\n this.afterWork.clear();\n return n;\n }\n\n /**\n * Sequential runs: between deliveries, let objects' work after their\n * answers run to rest, as it does in the runtime while nothing else comes\n * in: real I/O completes, timers fire in due order, and once nothing of it\n * can move it has settled.\n */\n async driveAfterWork(): Promise<void> {\n // Whether the last tick too found only idle hosting effects in flight (see `timersAllowed`).\n let idleBefore = false;\n while (this.hasAfterWork()) {\n if (this.firedPending() > 0) {\n idleBefore = false;\n await realTick();\n continue;\n }\n if (this.frames.inFlight > 0) {\n // The work called into an object that awaits a timer of its own before it answers: after a\n // tick for anything the run cannot see, the timer fires.\n const allowed = this.timersAllowed();\n if (allowed && idleBefore && this.fireOwned(allowed) !== undefined) {\n idleBefore = false;\n await eventLoopTurn();\n } else {\n idleBefore = allowed !== null;\n await realTick();\n }\n continue;\n }\n idleBefore = false;\n // Only the work's own timers: a finished handler's stray timer is not the object's to run.\n if (this.fireAfterWorkTimer()) {\n await eventLoopTurn();\n continue;\n }\n // One turn of the event loop for code that what just completed resumed; then it is at rest.\n await realTick();\n if (this.frames.inFlight > 0 || this.firedPending() > 0 || this.fireAfterWorkTimer())\n continue;\n this.settleAfterWork();\n }\n }\n\n /** Fire the next due timer of an object's work after an answer, as that work. False when none is pending. */\n fireAfterWorkTimer(): boolean {\n const alive = this.aliveAfterWork();\n if (alive.size === 0) return false;\n return this.fireOwned((owner) => owner !== null && alive.has(owner)) !== undefined;\n }\n\n /**\n * Whose timers may fire now: anyone's while nothing is in flight; while\n * only hosting effects whose hosted code is idle are, and one of those\n * hosts has a timer pending (an object awaiting a timer of its own before\n * it answers, see `Frames.idleHosts`), the timers of those hosts' work;\n * nobody's otherwise: a fired timer not yet run, or idle hosted code with\n * no timer, is work on its way that the run cannot see yet (a call\n * crossing into the object, storage I/O).\n */\n private timersAllowed(): ((owner: string | null) => boolean) | null {\n const clock = this.patched?.clock;\n if (!clock || this.firedPending() > 0) return null;\n if (this.frames.inFlight === 0) return () => true;\n const hosts = this.frames.idleHosts();\n if (!hosts) return null;\n const owners = new Set<string>();\n for (const host of hosts) {\n const cont = this.continuations.get(host);\n if (cont) owners.add(cont.id);\n }\n const allowed = (owner: string | null): boolean => owner !== null && owners.has(owner);\n // Only a timer of the hosts' own says the idle code is waiting for one; a pending deadline alone\n // does not (the code may be doing real I/O the run cannot see yet), though once timers may fire\n // the deadline fires with them.\n // A known limit: an object napping inside a late attempt's call holds the invocation's own\n // timers too (its retry waits for the object to wake), though the attempt's work holds nothing.\n return clock.nextDueOwned(allowed, false) === undefined ? null : allowed;\n }\n\n /**\n * Fire the earliest due timer whose owner `allowed` accepts, as that owner\n * (a step of a concurrent run). The owner it fired as (null for none);\n * undefined when no such timer is pending.\n */\n private fireOwned(allowed: (owner: string | null) => boolean): string | null | undefined {\n const clock = this.patched?.clock;\n if (!clock) return undefined;\n const owner = clock.nextOwnerOwned(allowed);\n if (owner === undefined) return undefined;\n this.runAs(owner);\n if (this.concurrent) this.turns.step();\n clock.fireNextOwned(allowed);\n return owner;\n }\n\n /**\n * Wait until what is running has come to rest: fired timers run and real\n * I/O done; or, two turns of the event loop running, only hosting effects\n * whose code is idle in flight (an object awaiting a timer of its own\n * before it answers), which the next timer to fire is for.\n */\n private async rest(): Promise<void> {\n let idleBefore = false;\n for (;;) {\n await eventLoopTurn();\n if (this.firedPending() > 0) {\n idleBefore = false;\n continue;\n }\n if (this.frames.inFlight === 0) return;\n const idle = this.timersAllowed() !== null;\n if (idle && idleBefore) return;\n idleBefore = idle;\n }\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, (inside) => {\n this.patched?.clock.cancelOwner(id);\n this.adoptInFlight(id, inside);\n });\n this.invocations.set(id, inv);\n return inv;\n }\n\n /**\n * The invocation crashed with calls into objects still in flight (a late\n * attempt's call while the retry's effect took the fault): the objects go\n * on, as the runtime's do, so what their code still does is their own work\n * (`ownerOf`), an answer to a caller that is gone. The call the crash\n * happened inside (`inside`) is abandoned by the crash instead and resets\n * its object.\n */\n private adoptInFlight(id: string, inside?: Frame): void {\n for (const frame of this.frames.hostingOf(id)) {\n if (frame === inside || frame.isAbandoned || frame.host === undefined) continue;\n if (this.adopted.has(frame)) continue;\n const cont = this.continuationOf(frame.host);\n this.adopted.set(frame, cont);\n if (this.concurrent) this.turns.adopt(frame, cont);\n }\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 /** Append one record, with the next sequence number: O(1), so a long run's log stays cheap. */\n private append(effect: Omit<EffectRecord, \"seq\">): void {\n this.entries.push({ ...effect, seq: this.entries.length });\n this.logView = 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.append({\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 ctx = hostScope?.getStore();\n if (ctx !== undefined) {\n const { host } = ctx;\n // The call this code is, while its effect is being performed; where the call is not known, the\n // innermost of the host's effects being performed.\n const live = ctx.frame\n ? ctx.frame.active\n ? ctx.frame\n : undefined\n : this.frames.liveHost(host);\n if (live) {\n // A host's code inside one of its effects: the effect is that one's, whatever invocation the\n // platform named (the runtime carries no context of the caller's into the host's code).\n if (live.invocation !== point.invocation)\n return this.effect(\n { ...point, invocation: live.invocation },\n perform,\n summarize,\n options,\n );\n } else {\n // The host's work after its answer: an effect of its continuation, a turn of its own, waited\n // for by polling as hosted code's effects are (the code runs inside the object); a crash in\n // it resets the object through the ended effect's onAbandon and ends the continuation.\n const cont = this.continuationOf(host);\n const own = { ...point, invocation: cont.id };\n if (cont.isCrashed()) return hang();\n const ended = ctx.frame ?? this.hostFrames.get(host);\n // Inside blockConcurrencyWhile nothing else enters the object and nothing it waits for gets\n // in, its poller's ticks included: the effect runs at once, as a call's would.\n if (this.concurrent && (ended?.mayPark() ?? true)) {\n let released = false;\n this.turns.park(cont, own.target, () => {\n released = true;\n });\n // Waited for on the host's poller's ticks: a real timer the host's code armed here, after\n // its request completed, would keep the object referenced (workerd), as the poller, armed\n // inside the request and re-armed from its own ticks, does not.\n while (!released && !cont.isCrashed()) await this.hostTick(host);\n if (!released) return hang();\n }\n return this.performEffect(own, perform, summarize, options, cont, ended);\n }\n }\n const inv = this.invocation(point.invocation);\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, hostScope?.getStore() !== undefined);\n // Whose effect it is (the object's own once its call was handed over, see `ownerOf`): a crashed\n // owner's effect hangs.\n if (this.ownerOf(inv, enclosing).isCrashed()) return hang();\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 return this.hostedTurn(\n point,\n perform,\n summarize,\n options,\n inv,\n undefined,\n host,\n (park) => new Promise<boolean>((go) => park(() => go(true))),\n );\n }\n await new Promise<void>((go) =>\n this.turns.park(inv, point.target, go, undefined, this.attemptNow()),\n );\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 return this.hostedTurn(\n point,\n perform,\n summarize,\n options,\n inv,\n enclosing,\n enclosing,\n async (park, crashed) => {\n // Wait by polling a flag from inside the hosted code: no promise is settled from outside\n // it (workerd refuses that for a Durable Object), and no event has to enter it (its input\n // gate may be closed, as in blockConcurrencyWhile). On the host's poller's ticks where the\n // code is a host's: a real timer of its own armed after its answer crossed would keep the\n // object referenced (see `pollHost`).\n let released = false;\n park(() => (released = true));\n const host = enclosing.host;\n while (!released && !crashed())\n await (host === undefined ? realTick() : this.hostTick(host));\n return released;\n },\n );\n }\n return this.performEffect(point, perform, summarize, options, inv, enclosing);\n }\n\n /**\n * An effect that is a turn under `host` (the effect hosting the invocation, or the hosted code's\n * own enclosing effect): the host waits on it until `wait` gives it the turn, and is in flight\n * again while it performs. `wait` parks the effect through `park` and answers whether the turn\n * came; when it did not (the invocation crashed meanwhile) the effect hangs.\n */\n private async hostedTurn<T>(\n point: EffectPoint,\n perform: () => Promise<T>,\n summarize: (value: T) => JsonValue,\n options: EffectOptions,\n inv: InvocationState,\n enclosing: Frame | undefined,\n host: Frame,\n wait: (park: (go: () => void) => void, crashed: () => boolean) => Promise<boolean>,\n ): Promise<T> {\n this.childWaits(host);\n // Whose turn it waits for: the host's work's once the hosting effect has answered or its caller\n // crashed (`ownerOf`); adoption while parked re-points the turn (`Turns.adopt`).\n const owner = this.ownerOf(inv, enclosing);\n const crashed = (): boolean => this.ownerOf(inv, enclosing).isCrashed();\n const attempt = this.attemptNow(enclosing, host);\n if (!(await wait((go) => this.turns.park(owner, point.target, go, host, attempt), crashed))) {\n this.childLeaves(host, true);\n return hang();\n }\n try {\n return await this.performEffect(point, perform, summarize, options, inv, enclosing, host);\n } finally {\n this.childLeaves(host, false);\n }\n }\n\n /** A child of `host` started and waits for its turn (the scheduler clears the wait when it comes). */\n private childWaits(host: Frame): void {\n this.frames.adjust(host, () => {\n host.children++;\n host.waitingChildren++;\n });\n }\n\n /** A child of `host` ended; `stillWaiting` when its turn never came. */\n private childLeaves(host: Frame, stillWaiting: boolean): void {\n this.frames.adjust(host, () => {\n host.children--;\n if (stillWaiting) host.waitingChildren--;\n });\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 made: 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 (a host's\n // that has ended resets the object).\n const dead = (): Promise<T> => {\n enclosing?.crash();\n return hang();\n };\n // Whose effect this is now: the object's code issued it during a call that has since answered,\n // it is the object's work (`ownerOf`), opened and recorded as such when it opens after the answer.\n const owner = (): InvocationState => this.ownerOf(inv, enclosing);\n const opener = owner();\n const point = opener === inv ? made : { ...made, invocation: opener.id };\n const fault = this.open(point, opener);\n const before = this.faultBefore(point, opener, fault, enclosing);\n if (before === \"crashed\") return dead();\n if (before) throw before;\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, options);\n frame.onHostAbandoned = (h) => this.hostAbandoned(h);\n frame.parent = host;\n frame.attempt = this.attemptNow(enclosing, host);\n this.frames.enter(frame);\n if (enclosing) enclosing.performing++;\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 if (enclosing) enclosing.performing--;\n this.frames.leave(frame);\n this.leftHost(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 owner().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 its owner was dying: nothing after it runs.\n if (owner().isCrashed()) return hang();\n const after = this.faultAfter(point, owner(), fault, enclosing);\n if (after === \"crashed\") return dead();\n if (after) throw after;\n return value;\n }\n\n /** A fault decided before the effect performs: the crash it is, the error to throw, or nothing. */\n /**\n * A fault decided before the effect performs: the crash it is, the error to\n * throw, or nothing. The crash names the effect the point is nested in\n * (an object's call the crash happened inside, which `dead` then abandons,\n * resetting the object), so it is not handed to the object (`adoptInFlight`).\n */\n private faultBefore(\n point: EffectPoint,\n inv: InvocationState,\n fault: FaultKind | null,\n enclosing?: Frame,\n ): \"crashed\" | InjectedEffectError | null {\n if (fault === \"crash_before\" || fault === \"cut_off\") {\n this.recordFault(point, fault);\n inv.crash(enclosing);\n return \"crashed\";\n }\n if (fault === \"error\") {\n this.recordFault(point, fault);\n return new InjectedEffectError(point, fault);\n }\n return null;\n }\n\n /** A fault decided after the effect committed: the crash it is, the error to throw, or nothing. */\n private faultAfter(\n point: EffectPoint,\n inv: InvocationState,\n fault: FaultKind | null,\n enclosing?: Frame,\n ): \"crashed\" | InjectedEffectError | null {\n if (fault === \"crash_after\") {\n this.recordFault(point, fault);\n inv.crash(enclosing);\n return \"crashed\";\n }\n if (fault === \"ambiguous\") {\n this.recordFault(point, fault);\n return new InjectedEffectError(point, fault);\n }\n return null;\n }\n\n private recordFault(point: EffectPoint, fault: FaultKind): void {\n this.record(point, \"fault\", { args: point.args, fault });\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 const before = this.faultBefore(point, inv, fault);\n if (before === \"crashed\") throw new CrashSignal(inv.id);\n if (before) throw before;\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 const after = this.faultAfter(point, inv, fault);\n if (after === \"crashed\") throw new CrashSignal(inv.id);\n if (after) throw after;\n return value;\n }\n\n unsupported(reason: string): void {\n this.reasons.push(reason);\n }\n\n attempt<T>(invocation: string, code: () => T, deadlineMs: number): Attempt<T> {\n const cell: AttemptCell = { late: deadlineMs <= 0 };\n let giveUp: () => void = () => {};\n const late = new Promise<void>((resolve) => {\n giveUp = () => {\n cell.late = true;\n resolve();\n };\n });\n if (cell.late) giveUp();\n const value = attemptScope ? attemptScope.run(cell, code) : code();\n // The deadline is a virtual timer of the invocation's set by the run, not through the patched\n // global: it is no read of the clock by the code (the partial-order reduction stays on), and it\n // is cleared once the code settles in time. Without a clock installed, the attempt is never late.\n const clock = this.patched?.clock;\n if (!cell.late && clock) {\n const timer = clock.setTimeoutAs(invocation, giveUp, deadlineMs);\n const clear = (): void => clock.clear(timer);\n if (isThenable(value)) void Promise.resolve(value).then(clear, clear);\n else clear();\n }\n return { value, late };\n }\n\n /**\n * The attempt whose code is running now, by its async context or, where the\n * runtime carries none (an object's code), by the effect it runs inside of.\n * Read live where it is kept: an attempt may become late after its effect\n * parked or entered an object.\n */\n private attemptNow(...frames: (Frame | undefined)[]): AttemptCell | undefined {\n return attemptScope?.getStore() ?? frames.find((f) => f?.attempt)?.attempt;\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`). A crash\n // is seen on the run's own step, not through a promise settled where it happened: an object's\n // task being torn down by its reset may never wake what it settled.\n if (this.concurrent)\n return Promise.race([\n promise,\n new Promise<T>((_, reject) => {\n if (inv.isCrashed()) reject(new CrashSignal(inv.id));\n else this.crashWatch.push({ inv, reject });\n }),\n ]);\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)) this.runAs(invocation);\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) + this.firedPending(),\n // While its own effect hosts an object awaiting a timer of its own, that timer fires; a hosted\n // invocation's settle is the one to fire timers while it runs.\n idle: () => (this.hostedBy(invocation) > 0 ? null : this.timersAllowed()),\n crashed: () => inv.isCrashed(),\n crashError: () => new CrashSignal(invocation),\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.childWaits(frame);\n try {\n return await work(inv);\n } finally {\n this.childLeaves(frame, true);\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 // A called Worker's code is its own, not the object's that may have called it.\n const unhosted = (): Promise<T> =>\n hostScope ? hostScope.run(undefined, asHandler) : asHandler();\n return deliveryScope.run({ id }, unhosted);\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 this.releaseCrashed();\n return this.turns.quiesce();\n }\n\n /**\n * Concurrent runs: settles waiting on invocations that have crashed since\n * are released, on the run's own step. Returns the invocations released.\n */\n private releaseCrashed(): Set<string> {\n const released = new Set<string>();\n if (this.crashWatch.length === 0) return released;\n const waiting = this.crashWatch;\n this.crashWatch = [];\n for (const w of waiting) {\n if (w.inv.isCrashed()) {\n w.reject(new CrashSignal(w.inv.id));\n released.add(w.inv.id);\n } else this.crashWatch.push(w);\n }\n return released;\n }\n\n /**\n * Concurrent runs: pick the next turn among the parked invocations, when\n * `canStart` starting the next event, and the earliest virtual timer\n * already due that may fire now (`timersAllowed`; with `afterWorkOnly`,\n * only an object's work after its answer's, as `fireAfterWorkTimer`).\n * Parked invocations are ordered by start, then by when they parked, so\n * the pick does not depend on real-time arrival; timers keep their due\n * order among themselves. `canWait`: whether the loop could let time pass\n * if nothing were parked; while only late turns are, it is an option\n * (`Turns.takeTurn`). Returns what was picked; \"turn\" has already\n * released it, \"timer\" fired it, and \"none\" leaves the loop to let time\n * pass or give up.\n */\n takeTurn(\n canStart: boolean,\n afterWorkOnly = false,\n canWait = false,\n ): \"turn\" | \"start\" | \"timer\" | \"none\" {\n return this.turns.takeTurn(canStart, this.dueTimer(afterWorkOnly), canWait);\n }\n\n /** The earliest timer already due (at or before the virtual now) that may fire now, as a turn. */\n private dueTimer(afterWorkOnly: boolean): DueTimer | undefined {\n const clock = this.patched?.clock;\n const allowed = this.timersAllowed();\n if (!clock || !allowed) return undefined;\n const alive = afterWorkOnly ? this.aliveAfterWork() : null;\n const owned = alive\n ? (owner: string | null) => owner !== null && alive.has(owner) && allowed(owner)\n : allowed;\n const due = clock.nextDueOwned(owned);\n if (due === undefined || due > clock.now()) return undefined;\n const owner = clock.nextOwnerOwned(owned) ?? null;\n return {\n owner,\n fired: this.timersFired.get(owner) ?? 0,\n fire: () => {\n this.fireOwned(owned);\n },\n };\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 (;;) {\n const allowed = this.timersAllowed();\n const due = allowed ? clock.nextDueOwned(allowed) : undefined;\n if (!allowed || due === undefined || due > at) break;\n this.fireOwned(allowed);\n fired = true;\n // What the timer set off runs at its own time, before the clock moves on.\n await this.rest();\n }\n clock.advance(at - clock.now());\n return fired;\n }\n\n /**\n * When the next virtual timer is due, or undefined when none is pending;\n * `afterWorkOnly` counts the timers of objects' work after answers alone,\n * the ones that fire while only such work is alive.\n */\n nextTimerDue(afterWorkOnly = false): number | undefined {\n const clock = this.patched?.clock;\n if (!clock) return undefined;\n if (!afterWorkOnly) {\n const allowed = this.timersAllowed();\n return allowed ? clock.nextDueOwned(allowed) : undefined;\n }\n const alive = this.aliveAfterWork();\n return clock.nextDueOwned((owner) => owner !== null && alive.has(owner));\n }\n\n /** The ids of continuations alive now. */\n private aliveAfterWork(): Set<string> {\n const alive = new Set<string>();\n for (const cont of this.afterWork) if (!cont.isCrashed()) alive.add(cont.id);\n return alive;\n }\n\n /**\n * Concurrent runs: fire the next due timer that may fire now\n * (`timersAllowed`) as the invocation that set it. False when none is.\n */\n fireTimer(): boolean {\n const allowed = this.timersAllowed();\n return allowed !== null && this.fireOwned(allowed) !== undefined;\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, or whose delivery\n * ends now: one that crashed inside an object (the object's reset tears\n * down the task the crash settled its promise in, so the delivery never\n * saw it) has its settle released here, on the run's own step.\n */\n abandon(ids: readonly string[]): number {\n let abandoned = 0;\n const released = this.releaseCrashed();\n for (const id of ids) {\n const inv = this.invocations.get(id);\n if (!inv) continue;\n if (inv.isCrashed()) {\n if (released.has(id)) abandoned++;\n continue;\n }\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.append({\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.append({\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 { EffectPoint, Invocation, JsonValue, 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`, an effect of its hung (the settle then rejects with the\n * signal, on the run's own tick), the invocation's `crashed` settled, or\n * the code returned or threw anything else after the crash (an object's\n * reset rejecting the call into it with an error of the runtime's); as\n * \"errored\" when it threw 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 crashed: Outcome<T> = { status: \"crashed\" };\n const outcome: Promise<Outcome<T>> = Promise.resolve()\n .then(work)\n .then(\n (value) => (inv.isCrashed() ? crashed : { status: \"completed\", value }),\n (error: unknown) =>\n error instanceof CrashSignal || inv.isCrashed() ? crashed : { status: \"errored\", error },\n );\n return Promise.race([\n hooks\n .settle(outcome, inv.id)\n .catch((error: unknown) =>\n error instanceof CrashSignal ? crashed : Promise.reject<Outcome<T>>(error),\n ),\n inv.crashed.then(() => 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/**\n * Record a platform action that performs nothing: a marker in the log (a\n * message dead-lettered, a caller that gave up, a Workflow step's result).\n * Under faults it can crash the invocation like any effect; most admit none.\n */\nexport function note(hooks: RunHooks, point: EffectPoint): void {\n hooks.effectSync(\n point,\n () => null,\n () => null,\n );\n}\n\n/**\n * Perform a decision of the platform's own (an implicit ack, a delete)\n * under the faults around a decision: it stands, or an injected crash\n * ended the invocation at that point.\n */\nexport function decide<T>(\n hooks: RunHooks,\n point: EffectPoint,\n perform: () => T,\n summarize: (value: T) => JsonValue,\n): \"decided\" | \"crashed\" {\n try {\n hooks.effectSync(point, perform, summarize);\n return \"decided\";\n } catch (err) {\n if (err instanceof CrashSignal) return \"crashed\";\n throw err;\n }\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 and\n * firing a timer already due are dependent on everything (their options\n * have no target), so what they run is never reordered. 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 canonicalJson,\n checkInvariants,\n type DeliveryResult,\n type EffectLog,\n type EffectRecord,\n type EventRef,\n earliestEvent,\n type JsonValue,\n nextU32,\n type Platform,\n type PrngState,\n planFaults,\n type ScenarioSpec,\n type ScenarioVerdict,\n type Schedule,\n seedPrng,\n serializeLog,\n type UnsupportedCause,\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\n/** How `explore` searches: the seed, a cap on runs, the time budget, the share of runs with faults, and exhaustive mode. */\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 in due order; one at a time, only while the invocation is idle (no effect in flight); with several in flight, as the concurrency assumption says; 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, starting a new event while a slot is free, and firing the earliest timer already due (at or before the virtual now, which effects advance), timers firing in due order among themselves, and a timer not yet due fires (virtual time passing to it) only when nothing else can move`;\n}\n\n/** Where two JSON values first differ, as a path into them (`.tables.audit[0].at`), with the two values there. */\nfunction firstDifference(\n a: JsonValue | undefined,\n b: JsonValue | undefined,\n path = \"\",\n): { path: string; a: JsonValue | undefined; b: JsonValue | undefined } | null {\n if (Array.isArray(a) && Array.isArray(b)) {\n for (let i = 0; i < Math.max(a.length, b.length); i++) {\n const d = firstDifference(a[i], b[i], `${path}[${i}]`);\n if (d) return d;\n }\n return null;\n }\n const record = (v: unknown): v is { readonly [key: string]: JsonValue } =>\n typeof v === \"object\" && v !== null && !Array.isArray(v);\n if (record(a) && record(b)) {\n for (const key of [...new Set([...Object.keys(a), ...Object.keys(b)])].sort()) {\n const d = firstDifference(a[key], b[key], `${path}.${key}`);\n if (d) return d;\n }\n return null;\n }\n const same = a === undefined || b === undefined ? a === b : canonicalJson(a) === canonicalJson(b);\n return same ? null : { path, a, b };\n}\n\n/**\n * The first record a replay recorded differently from the run, or how their\n * lengths differ; null when the logs match. Two records of the same effect\n * are told apart by the first value in their payloads that differs, with its\n * path: a snapshot of many tables that differs in one column says which.\n */\nfunction whatDiffered(run: EffectLog, replay: EffectLog): string | null {\n const short = (v: JsonValue | undefined): string => {\n if (v === undefined) return \"nothing\";\n const text = canonicalJson(v);\n return text.length > 120 ? `${text.slice(0, 117)}...` : text;\n };\n /** Two differing values, each cut to the stretch around where their texts part, so the excerpts differ too. */\n const apart = (x: JsonValue | undefined, y: JsonValue | undefined): [string, string] => {\n if (x === undefined || y === undefined) return [short(x), short(y)];\n const [s, t] = [canonicalJson(x), canonicalJson(y)];\n if (s.length <= 120 && t.length <= 120) return [s, t];\n let at = 0;\n while (at < s.length && at < t.length && s[at] === t[at]) at++;\n const from = Math.max(0, at - 40);\n const cut = (text: string): string =>\n `${from > 0 ? \"...\" : \"\"}${text.slice(from, from + 110)}${from + 110 < text.length ? \"...\" : \"\"}`;\n return [cut(s), cut(t)];\n };\n const head = (e: EffectRecord): string => `${e.kind} ${e.target} ${e.op} in ${e.invocation}`;\n const a = serializeLog(run).split(\"\\n\");\n const b = serializeLog(replay).split(\"\\n\");\n const n = Math.min(run.entries.length, replay.entries.length);\n for (let i = 0; i < n; i++) {\n if (a[i] === b[i]) continue;\n const ran = run.entries[i] as EffectRecord;\n const replayed = replay.entries[i] as EffectRecord;\n const within = head(ran) === head(replayed) && firstDifference(ran.payload, replayed.payload);\n if (within) {\n const [was, is] = apart(within.a, within.b);\n return `at seq ${i} the run recorded ${head(ran)} with ${was} at payload${within.path} and the replay with ${is}`;\n }\n return `at seq ${i} the run recorded ${head(ran)} ${short(ran.payload)} and the replay ${head(replayed)} ${short(replayed.payload)}`;\n }\n if (run.entries.length === replay.entries.length) return null;\n return `the run recorded ${run.entries.length} entries and the replay ${replay.entries.length}`;\n}\n\n/** Whether exhaustive exploration reduces by partial order (it does unless told not to). */\nfunction reductionOf(options: ExploreOptions): boolean {\n return typeof options.exhaustive === \"object\" ? (options.exhaustive.reduction ?? true) : true;\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 = reductionOf(options);\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(earliestEvent(pending), 1) as [EventRef];\n if (event.at !== undefined) await run.advanceTo(event.at);\n const result = await platform.deliver(event, run, spec);\n // An object's work after its answer runs to rest before the next event, one of the orders the\n // runtime allows (a concurrent run explores the others).\n await run.driveAfterWork();\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, while a slot is free the next event starts, or a timer\n * already due fires. When nothing is parked, no event can start and no\n * timer is due, the next timer fires (time passes to it), 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 && !run.hasAfterWork()) return;\n const next = pending.length > 0 ? earliestEvent(pending) : -1;\n const eventAt = pending[next]?.at ?? 0;\n const due = next >= 0 && eventAt <= run.now();\n const canStart = active.length < spec.bounds.maxConcurrentInvocations && due;\n // While only objects' work after their answers is alive, only its timers are ready work (see below).\n const afterWorkOnly = active.length === 0 && run.hasAfterWork();\n // What the loop does when nothing is parked: time passes to the next delayed event when nothing\n // can move before it, else the next timer fires. Offered as a turn while only late turns are parked.\n const timerDue = run.nextTimerDue(afterWorkOnly);\n const untilEvent =\n next >= 0 &&\n !due &&\n active.length < spec.bounds.maxConcurrentInvocations &&\n (timerDue ?? Number.POSITIVE_INFINITY) > eventAt;\n const turn = run.takeTurn(canStart, afterWorkOnly, untilEvent || timerDue !== undefined);\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 (turn === \"none\" && untilEvent) {\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(eventAt))) continue;\n } else if (\n turn === \"none\" &&\n !(active.length > 0 || !run.hasAfterWork() ? run.fireTimer() : run.fireAfterWorkTimer()) &&\n run.settleAfterWork() === 0\n ) {\n // Nothing can move: objects' work after their answers has settled; anything else is stuck. While\n // only such work is alive its own timers fire, not a finished handler's stray one, which would\n // keep it alive; with no such work, timers fire as before (a stray one until the next event is due).\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\n/**\n * Explore a scenario on a platform: run it under schedules drawn from the seed (or every schedule within\n * the bounds, when exhaustive), shrink the first violation found, and return the verdict. At most 100 runs\n * unless `maxRuns` says otherwise.\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 const exhaustive = options.exhaustive\n ? new ExhaustiveDriver(reductionOf(options), spec.bounds.maxFaultsPerRun)\n : null;\n const doneNow = (): BoundsReached => ({\n ...done(),\n ...(exhaustive ? { exhaustive: exhaustive.reached } : {}),\n });\n const unsupported = (cause: UnsupportedCause, reason: string): ScenarioVerdict => ({\n ...base,\n kind: \"UNSUPPORTED\",\n cause,\n reason,\n reached: doneNow(),\n });\n\n if (spec.bounds.maxConcurrentInvocations > 1 && !concurrencySupported)\n return unsupported(\n \"unsupported_bounds\",\n \"maxConcurrentInvocations above 1 needs AsyncLocalStorage (Node, or workerd with nodejs_compat or nodejs_als)\",\n );\n if (spec.bounds.maxConcurrentInvocations > 1 && !platform.concurrent)\n return unsupported(\n \"unsupported_bounds\",\n `maxConcurrentInvocations above 1 is not supported on the ${platform.name} platform yet`,\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; log: EffectLog }[] = [];\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 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 unsupported(\n \"not_replayable\",\n `exhaustive exploration needs deterministic runs: ${exhaustive.mismatch}`,\n );\n if (!exhaustive.ran(() => run.turnsMayNotCommute)) continue;\n }\n reached.effectPoints += run.effectPoints;\n reached.faultsInjected += run.faultsInjected;\n if (witnesses.length < leakCheckRuns) witnesses.push({ schedule: run.schedule, log });\n\n if (run.unsupportedReasons.length > 0)\n return unsupported(\"unsupported_api\", run.unsupportedReasons.join(\"; \"));\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 // A replay that reached something unsupported says so itself; one that differs says where.\n if (replayedRun.unsupportedReasons.length > 0)\n return unsupported(\"unsupported_api\", replayedRun.unsupportedReasons.join(\"; \"));\n const differed = whatDiffered(log, replayed);\n if (differed)\n return unsupported(\n \"not_replayable\",\n `the violating run of seed ${schedule.seed} did not reproduce on replay: ${differed}`,\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)\n return unsupported(\"unsupported_api\", again.unsupportedReasons.join(\"; \"));\n const differed = whatDiffered(witness.log, again.log);\n if (differed)\n return unsupported(\n \"module_state_leak\",\n `run seed ${witness.schedule.seed} produced a different log when replayed after other runs: state is leaking between runs (module-level variables, or a binding Eutaxy does not reset); ${differed}`,\n );\n }\n return { ...base, kind: \"BOUNDED\", bounds: spec.bounds, reached: doneNow() };\n}\n","/**\n * The platform-neutral part of a differential check: the same fault-free\n * scenario once through Eutaxy and once against the raw bindings, then a\n * comparison of what each attempt decided and of the final state. Any\n * difference is a bug in the proxies or the platform model, not in the\n * handler. The raw side's loop is here too (the same virtual globals and\n * scripted externals as the proxied side, the same pick of the next event\n * and the same redelivery rule); a platform writes only how one raw attempt\n * calls its handler, sharing no proxy code.\n */\n\nimport {\n canonicalJson,\n type DeliveryResult,\n type EffectRecord,\n type EventRef,\n earliestEvent,\n type JsonValue,\n type Platform,\n redelivery,\n type ScenarioSpec,\n} from \"@eutaxy/core\";\nimport { replayChooser } from \"./chooser.ts\";\nimport { effectLatencyMs, patchGlobals, settleOn, type VirtualClock } from \"./clock.ts\";\nimport type { Outcome } from \"./deliver.ts\";\nimport { runOnce } from \"./explore.ts\";\nimport { installScriptedFetch } from \"./fetch.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/** How raw handler code ended: it returned, or it threw. Nothing is injected on the raw side, so nothing crashes. */\nexport type RawOutcome<T> = Exclude<Outcome<T>, { readonly status: \"crashed\" }>;\n\n/** What one raw attempt runs under. */\nexport interface RawContext {\n /** The virtual clock the proxied side's run had, from the same seed; a wrapper advances it as the proxied effect would. */\n readonly clock: VirtualClock;\n /** Real I/O in flight: a wrapper around a real binding or SDK call counts it, so the wait knows the handler is not stuck. */\n readonly io: { n: number };\n /** Run a real call whose library schedules timers of its own with real timers, as the proxied side does. */\n readonly libraryIo: <T>(perform: () => Promise<T>) => Promise<T>;\n /** Report what the raw side could not control; the run ends `DifferentialStuck` with every reason once the attempts are done. */\n readonly unsupported: (reason: string) => void;\n /** Wait for a promise under the virtual clock: real I/O completes, timers fire while the handler is idle, a handler waiting on nothing ends the comparison. */\n readonly settle: <T>(promise: Promise<T>) => Promise<T>;\n /** Run handler code under `settle` to its outcome. */\n readonly call: <T>(code: () => T | Promise<T>) => Promise<RawOutcome<T>>;\n}\n\n/** One raw attempt's result: its record, and whether the event was handled (an unhandled one is delivered again while the limits leave room). */\nexport interface RawAttempt<A> {\n readonly record: A;\n readonly handled: boolean;\n}\n\n/** A platform's raw side: its events, its limit on redeliveries, and how one attempt calls the handler. */\nexport interface RawSide<A> {\n /** The drive's events, as the platform's `initialEvents` gives them. */\n readonly events: readonly EventRef[];\n /** The platform's own limit on redeliveries (Queues' `max_retries`, the caller's `retries`, SQS's `maxReceiveCount` less one). */\n readonly limit: number;\n /**\n * Put in place what the handler needs under the patched globals (the real\n * bindings with their calls counted, an SDK redirected to local clients) and\n * give the attempt; `restore` undoes it after the last attempt, before the\n * globals come back.\n */\n readonly install: (ctx: RawContext) => {\n readonly attempt: (event: EventRef) => Promise<RawAttempt<A>>;\n readonly restore?: () => void;\n };\n}\n\n/**\n * The raw side: every event delivered as the engine would deliver it with\n * no faults and one invocation at a time (the earliest due first, time\n * moved to a delayed one, an unhandled one delivered again under core's\n * redelivery rule), each attempt performed by the platform. The attempts'\n * records, in order.\n */\nexport async function rawRun<A>(spec: ScenarioSpec, side: RawSide<A>): Promise<readonly A[]> {\n // The same virtual globals as the proxied side, from the same seed, so Date.now and randomness agree,\n // and the same scripted externals, without recording.\n const patched = patchGlobals(0);\n const reasons: string[] = [];\n const unsupported = (reason: string): void => {\n reasons.push(reason);\n };\n const restoreFetch = installScriptedFetch(\n spec.externals,\n null,\n unsupported,\n () => patched.clock.advance(effectLatencyMs), // the proxied side advances per effect; match it\n );\n const io = { n: 0 };\n const settle = <T>(promise: Promise<T>): Promise<T> =>\n settleOn(promise, {\n clock: patched.clock,\n inFlight: () => io.n,\n crashed: () => false,\n stuck: () => {\n throw new DifferentialStuck();\n },\n });\n const call = async <T>(code: () => T | Promise<T>): Promise<RawOutcome<T>> => {\n try {\n return { status: \"completed\", value: await settle(Promise.resolve().then(code)) };\n } catch (error) {\n if (error instanceof DifferentialStuck) throw error;\n return { status: \"errored\", error };\n }\n };\n const attempts: A[] = [];\n const pending: EventRef[] = [...side.events];\n let restore: (() => void) | undefined;\n try {\n // Inside the cleanup: a platform that finds no handler to call throws here, under the patched globals.\n const installed = side.install({\n clock: patched.clock,\n io,\n libraryIo: (perform) => patched.libraryIo(perform),\n unsupported,\n settle,\n call,\n });\n restore = installed.restore;\n const { attempt } = installed;\n while (pending.length > 0) {\n const [event] = pending.splice(earliestEvent(pending), 1) as [EventRef];\n // The proxied side's clock moved to a delayed event's time; so does this one.\n if (event.at !== undefined && event.at > patched.clock.now())\n patched.clock.advance(event.at - patched.clock.now());\n const { record, handled } = await attempt(event);\n attempts.push(record);\n const next = handled ? null : redelivery(event, side.limit, spec.bounds);\n if (next) pending.push(next);\n }\n } finally {\n restore?.();\n restoreFetch();\n patched.restore();\n }\n if (reasons.length > 0) throw new DifferentialStuck(`raw side: ${reasons.join(\"; \")}`);\n return attempts;\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\n/** One call of an observed core function from outside its module: the function, its arguments, whether it threw. */\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\n/** The calls an `observeCore` has recorded, the functions it could not observe, and how to undo it. */\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\n/** Observe the named exports of a module's namespace while runs are installed; see the module comment. */\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,UAAU,sBAAsB,OAAO;GAC9E,OAAO,OAAO,GAAG,OAAO,EAAE,IAAI,MAAM,KAAK,UAAU,KAAK;EAC1D,KAAK,UACH,OAAO,KAAK,UAAU,KAAK;EAC7B,KAAK,UAAU;GACb,IAAI,MAAM,QAAQ,KAAK,GAAG;IACxB,MAAM,QAAkB,CAAC;IACzB,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;KACrC,MAAM,IAAI,MAAM;KAChB,IAAI,MAAM,KAAA,GAAW,MAAM,IAAI,UAAU,8BAA8B,GAAG;KAC1E,MAAM,KAAK,cAAc,CAAC,CAAC;IAC7B;IACA,OAAO,IAAI,MAAM,KAAK,GAAG,EAAE;GAC7B;GACA,MAAM,OAAO,OAAO,KAAK,KAAK,CAAC,CAAC,KAAK;GACrC,MAAM,QAAkB,CAAC;GACzB,KAAK,MAAM,KAAK,MAAM;IACpB,MAAM,IAAK,MAA4D;IACvE,IAAI,MAAM,KAAA,GAAW,MAAM,IAAI,UAAU,oBAAoB,KAAK,UAAU,CAAC,GAAG;IAChF,MAAM,KAAK,GAAG,KAAK,UAAU,CAAC,EAAE,GAAG,cAAc,CAAC,GAAG;GACvD;GACA,OAAO,IAAI,MAAM,KAAK,GAAG,EAAE;EAC7B;EACA,SACE,MAAM,IAAI,UAAU,kBAAkB,OAAO,OAAO;CACxD;AACF;;;ACnCA,SAAgB,aAAa,OAAyB;CACpD,OAAO,GAA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