From b3fe55313477e55982ca9e2e6da1ce98bc586f50 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:12:21 -0500 Subject: [PATCH 1/9] Qualify an unwired durable admission wait with a fixed cutoff --- .github/workflows/test.yml | 5 + .../packs/foundation/readPackAdmissionStep.ts | 23 +++ .../foundation/startPackAdmissionStep.ts | 7 + .../packs/foundation/waitForPackAdmission.ts | 10 ++ lib/content/packs/foundation/ADMISSION.md | 8 +- .../packs/foundation/ADMISSION_WAIT.md | 60 +++++++ .../__tests__/packAdmissionSteps.test.ts | 60 +++++++ .../__tests__/packAdmissionWait.test.ts | 168 ++++++++++++++++++ .../packs/foundation/packAdmissionTypes.ts | 34 ++++ .../packs/foundation/pollPackAdmission.ts | 64 +++++++ .../__tests__/assertOutcome.test.mjs | 83 +++++++++ .../assertOutcome.mjs | 53 ++++++ .../buildFixture.mjs | 85 +++++++++ .../pack-admission-workflow-fixture/run.mjs | 48 +++++ .../runScenario.mjs | 74 ++++++++ .../runWorker.mjs | 124 +++++++++++++ .../source/fixtureSchemas.ts.txt | 15 ++ .../source/runPackCommand.ts.txt | 33 ++++ .../source/workflow.ts.txt | 9 + 19 files changed, 961 insertions(+), 2 deletions(-) create mode 100644 app/workflows/packs/foundation/readPackAdmissionStep.ts create mode 100644 app/workflows/packs/foundation/startPackAdmissionStep.ts create mode 100644 app/workflows/packs/foundation/waitForPackAdmission.ts create mode 100644 lib/content/packs/foundation/ADMISSION_WAIT.md create mode 100644 lib/content/packs/foundation/__tests__/packAdmissionSteps.test.ts create mode 100644 lib/content/packs/foundation/__tests__/packAdmissionWait.test.ts create mode 100644 lib/content/packs/foundation/packAdmissionTypes.ts create mode 100644 lib/content/packs/foundation/pollPackAdmission.ts create mode 100644 scripts/pack-admission-workflow-fixture/__tests__/assertOutcome.test.mjs create mode 100644 scripts/pack-admission-workflow-fixture/assertOutcome.mjs create mode 100644 scripts/pack-admission-workflow-fixture/buildFixture.mjs create mode 100644 scripts/pack-admission-workflow-fixture/run.mjs create mode 100644 scripts/pack-admission-workflow-fixture/runScenario.mjs create mode 100644 scripts/pack-admission-workflow-fixture/runWorker.mjs create mode 100644 scripts/pack-admission-workflow-fixture/source/fixtureSchemas.ts.txt create mode 100644 scripts/pack-admission-workflow-fixture/source/runPackCommand.ts.txt create mode 100644 scripts/pack-admission-workflow-fixture/source/workflow.ts.txt diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index dcc5a332a..03bc60d4d 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -42,6 +42,11 @@ jobs: - name: Check unwired pack foundation with offline durable ports run: pnpm test:pack-foundation-workflow + - name: Check unwired pack admission wait and restart + run: | + node --test scripts/pack-admission-workflow-fixture/__tests__/*.test.mjs + node scripts/pack-admission-workflow-fixture/run.mjs + - name: Check actual unwired pack foundation port compilation run: | PACK_FOUNDATION_PORTS_COMPILE_OUTPUT=./pack-foundation-ports-compile.json node scripts/pack-foundation-durable-ports-compile.mjs diff --git a/app/workflows/packs/foundation/readPackAdmissionStep.ts b/app/workflows/packs/foundation/readPackAdmissionStep.ts new file mode 100644 index 000000000..e22026252 --- /dev/null +++ b/app/workflows/packs/foundation/readPackAdmissionStep.ts @@ -0,0 +1,23 @@ +import { getWorkflowMetadata } from "workflow"; +import { runPackCommand } from "@/lib/supabase/release_pack_jobs/runPackCommand"; +import type { PackActor } from "@/lib/content/packs/packTypes"; +import type { PackAdmissionObservation } from "@/lib/content/packs/foundation/packAdmissionTypes"; +export async function readPackAdmissionStep( + actor: PackActor, + jobId: string, +): Promise { + "use step"; + const { job } = await runPackCommand(actor, "read", jobId); + return { + workflowRunId: getWorkflowMetadata().workflowRunId, + observedAt: Date.now(), + job: { + id: job.id, + owner_id: job.owner_id, + status: job.status, + workflow_run_id: job.workflow_run_id, + hold_expires_at: job.hold_expires_at, + }, + }; +} +readPackAdmissionStep.maxRetries = 0; diff --git a/app/workflows/packs/foundation/startPackAdmissionStep.ts b/app/workflows/packs/foundation/startPackAdmissionStep.ts new file mode 100644 index 000000000..01711f020 --- /dev/null +++ b/app/workflows/packs/foundation/startPackAdmissionStep.ts @@ -0,0 +1,7 @@ +import { getWorkflowMetadata } from "workflow"; +/** Journal this start clock once; replay must never reset the candidate deadline. */ +export async function startPackAdmissionStep() { + "use step"; + return { workflowRunId: getWorkflowMetadata().workflowRunId, startedAt: Date.now() }; +} +startPackAdmissionStep.maxRetries = 0; diff --git a/app/workflows/packs/foundation/waitForPackAdmission.ts b/app/workflows/packs/foundation/waitForPackAdmission.ts new file mode 100644 index 000000000..6ff93724d --- /dev/null +++ b/app/workflows/packs/foundation/waitForPackAdmission.ts @@ -0,0 +1,10 @@ +import { sleep } from "workflow"; +import { pollPackAdmission } from "@/lib/content/packs/foundation/pollPackAdmission"; +import type { PackActor } from "@/lib/content/packs/packTypes"; +import { startPackAdmissionStep } from "./startPackAdmissionStep"; +import { readPackAdmissionStep } from "./readPackAdmissionStep"; +/** Unwired: no production caller, self-admission, dispatch, provider work or settlement. */ +export async function waitForPackAdmission(actor: PackActor, jobId: string) { + const start = await startPackAdmissionStep(); + return pollPackAdmission(actor, jobId, start, { read: readPackAdmissionStep, sleepUntil: sleep }); +} diff --git a/lib/content/packs/foundation/ADMISSION.md b/lib/content/packs/foundation/ADMISSION.md index f4ddd4a99..70d9987c2 100644 --- a/lib/content/packs/foundation/ADMISSION.md +++ b/lib/content/packs/foundation/ADMISSION.md @@ -36,8 +36,8 @@ non-running jobs and expired holds must fail closed. A cached step result must n be mistaken for a fresh read. Read reconciliation retains the database's existing expired-hold behavior; no hold extension or funding action is implied. -Before selecting this candidate, define a finite wait deadline and the observable -owner continuation when dispatch persistence or its acknowledgement is lost. Prove +Production use still requires selecting timeout policy and the observable owner +continuation when dispatch persistence or its acknowledgement is lost. Required evidence covers early execution, delayed persistence, restart during wait, wrong-run rejection, expiry, read failures, timeout and no second dispatch/provider attempt. A wait solves only the initial ordering gap; it does not solve cross-run takeover after admission. @@ -66,3 +66,7 @@ synthetic effects, not a hosted scheduling guarantee. Negative observer tests re outside-delivery reads, incomplete loads, unrelated failures, failed handlers and combining events from concurrent deliveries. Keep the original failed CI evidence; a passing deterministic fixture does not retroactively prove its complete event order. + +The separately qualified [finite admission candidate](./ADMISSION_WAIT.md) implements +an unwired 30-second admission cutoff with durable fresh reads. It does not select +production timeout policy, change dispatch or solve atomic ownership. diff --git a/lib/content/packs/foundation/ADMISSION_WAIT.md b/lib/content/packs/foundation/ADMISSION_WAIT.md new file mode 100644 index 000000000..02cf826a8 --- /dev/null +++ b/lib/content/packs/foundation/ADMISSION_WAIT.md @@ -0,0 +1,60 @@ +# Unwired finite admission candidate + +`waitForPackAdmission` is an unregistered composition helper. Nothing in production +calls it, and it does not call the foundation factory. The 30-second cutoff and +scheduled poll interval of at most one second are engineering qualification values, +not a selected production timeout or service-level guarantee. + +`startPackAdmissionStep` journals the executing Workflow ID and a server clock once. +`pollPackAdmission` derives one absolute deadline from that saved result. Every poll +invokes `readPackAdmissionStep` separately, producing a distinct durable step result. +Completed reads replay from their own journal entries; the next poll is a new read, +not reuse of a cached initial snapshot. Absolute durable sleeps stop at the earlier +of the next poll time, original hold expiry and admission deadline. Restart cannot +reset the start clock or extend the deadline. + +The read step calls only the existing owner/org-scoped read RPC. The loop tolerates +only an absent saved workflow ID on the same running, authorized job with a valid +future hold. It requires the current step's Workflow ID to remain the original ID. +A different saved ID, empty ID, wrong owner/job, non-running status, expired/invalid +hold or read/access failure returns `needs-reconciliation` without another poll. +Admission observed at or after the deadline returns reconciliation even if the ID +matches. A backward or invalid clock is also rejected. No step automatically retries. + +Results retain the original job/run IDs, absolute deadline and first authorized, +valid hold expiry. If the first read fails before an expiry is known, that field is +null; no expiry is invented. A later extension cannot extend this candidate's original +hold boundary. No `run`, `approve`, provider, context write, settlement or dispatch +operation is available through the coordinator's ports. The existing database read +may reconcile an already-expired hold under its existing policy; this candidate does +not add a hold release, renewal or funding action. + +The cutoff governs admission eligibility, not maximum wall-clock response time. +An in-flight RPC, stalled infrastructure or delayed Workflow delivery can return +later; cancellation and hosted scheduling have not been qualified. The next fresh +observation still cannot admit after the original cutoff. Reconciliation is an +explicit result, not permission to start another run or retry paid work. + +## Qualification + +Unit tests exercise exact deadline and hold boundaries, immediate/delayed/missing ID, +wrong identity/status, read failure and clock anomalies. Adapter tests use the actual +RPC wrapper with a mocked server client to verify exact account/org/job forwarding, +read-only calls and zero retry settings. + +The separate `scripts/pack-admission-workflow-fixture` compiles the actual composition, +coordinator and durable steps, replacing only the read RPC with a typed synthetic +boundary. It uses the unchanged shared local-world, network-denial, polling and +strict-type helpers. Scenarios cover immediate admission, delayed persistence across +process restart, deadline across restart, different ID, read/access failure and +expired hold. The fixture retains the decoded original journaled start-clock result +and checks the exact deadline, distinct read-step correlations, one original start, +no other step/effect, unchanged hold and no repeated reads after terminal replay. +The delayed case simulates persistence of the original dispatch ID outside the +workflow; it does not perform self-admission or start a second workflow. + +This is local compiled replay with synthetic database reads. It does not establish +SQL atomicity, authenticated hosting, provider execution, production timeout policy, +or owner-facing continuation. The existing unconditional `run` write, reused preparation +write and point-in-time authorization still do not fence cross-run takeover. Production +wiring and those authority/continuation contracts remain separate prerequisites. diff --git a/lib/content/packs/foundation/__tests__/packAdmissionSteps.test.ts b/lib/content/packs/foundation/__tests__/packAdmissionSteps.test.ts new file mode 100644 index 000000000..5a4a6ac8b --- /dev/null +++ b/lib/content/packs/foundation/__tests__/packAdmissionSteps.test.ts @@ -0,0 +1,60 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { startPackAdmissionStep } from "@/app/workflows/packs/foundation/startPackAdmissionStep"; +import { readPackAdmissionStep } from "@/app/workflows/packs/foundation/readPackAdmissionStep"; +const boundary = vi.hoisted(() => ({ rpc: vi.fn(), runId: "executing-run" })); +vi.mock("@/lib/supabase/serverClient", () => ({ default: { rpc: boundary.rpc } })); +vi.mock("workflow", () => ({ getWorkflowMetadata: () => ({ workflowRunId: boundary.runId }) })); +describe("actual admission durable steps at mocked RPC boundary", () => { + beforeEach(() => { + vi.clearAllMocks(); + boundary.runId = "executing-run"; + }); + it("journals a start clock and executing run without a database call", async () => { + const before = Date.now(); + const value = await startPackAdmissionStep(); + expect(value.workflowRunId).toBe("executing-run"); + expect(value.startedAt).toBeGreaterThanOrEqual(before); + expect(value.startedAt).toBeLessThanOrEqual(Date.now()); + expect(boundary.rpc).not.toHaveBeenCalled(); + expect(startPackAdmissionStep.maxRetries).toBe(0); + }); + it("forwards exact account/org/job authority through the existing read RPC", async () => { + const job = { + id: "job", + owner_id: "ORG", + status: "running", + workflow_run_id: null, + hold_expires_at: "2099-01-01T00:00:00Z", + unrelated: "not returned", + }; + boundary.rpc.mockResolvedValue({ data: { job, assets: [] }, error: null }); + const result = await readPackAdmissionStep( + { accountId: "member", organizationId: "ORG" }, + "job", + ); + expect(result.job).toEqual({ + id: "job", + owner_id: "ORG", + status: "running", + workflow_run_id: null, + hold_expires_at: job.hold_expires_at, + }); + expect(result.workflowRunId).toBe("executing-run"); + expect(Number.isFinite(result.observedAt)).toBe(true); + expect(boundary.rpc).toHaveBeenCalledExactlyOnceWith("release_pack_command", { + p_actor: "member", + p_org: "ORG", + p_action: "read", + p_job: "job", + p_input: {}, + }); + expect(readPackAdmissionStep.maxRetries).toBe(0); + }); + it("propagates denied reads without admission writes or local retries", async () => { + boundary.rpc.mockResolvedValue({ data: null, error: { message: "access denied" } }); + await expect(readPackAdmissionStep({ accountId: "member" }, "job")).rejects.toThrow( + "access denied", + ); + expect(boundary.rpc).toHaveBeenCalledTimes(1); + }); +}); diff --git a/lib/content/packs/foundation/__tests__/packAdmissionWait.test.ts b/lib/content/packs/foundation/__tests__/packAdmissionWait.test.ts new file mode 100644 index 000000000..53b6f6dbd --- /dev/null +++ b/lib/content/packs/foundation/__tests__/packAdmissionWait.test.ts @@ -0,0 +1,168 @@ +import { describe, expect, it, vi } from "vitest"; +import { pollPackAdmission } from "../pollPackAdmission"; +import type { PackAdmissionObservation } from "../packAdmissionTypes"; +const start = { workflowRunId: "run-original", startedAt: 1_000_000 }; +const actor = { accountId: "member", organizationId: "OWNER" }; +const expiry = new Date(start.startedAt + 120_000).toISOString(); +function fixture() { + let now = start.startedAt; + const observation: PackAdmissionObservation = { + workflowRunId: start.workflowRunId, + observedAt: now, + job: { + id: "job", + owner_id: "owner", + status: "running", + workflow_run_id: null, + hold_expires_at: expiry, + }, + }; + const read = vi.fn(async () => ({ ...structuredClone(observation), observedAt: now })); + const sleepUntil = vi.fn(async (date: Date) => { + now = date.getTime(); + }); + return { + observation, + read, + sleepUntil, + setNow: (value: number) => { + now = value; + }, + run: () => pollPackAdmission(actor, "job", start, { read, sleepUntil }), + }; +} +describe("unwired finite pack admission wait", () => { + it("admits matching saved ID on the first fresh read without waiting", async () => { + const f = fixture(); + f.observation.job.workflow_run_id = start.workflowRunId; + expect(await f.run()).toMatchObject({ + status: "admitted", + job_id: "job", + workflow_run_id: start.workflowRunId, + hold_expires_at: expiry, + deadline_at: start.startedAt + 30_000, + }); + expect(f.read).toHaveBeenCalledExactlyOnceWith(actor, "job"); + expect(f.sleepUntil).not.toHaveBeenCalled(); + }); + it("uses distinct fresh reads after durable waits and admits a delayed ID", async () => { + const f = fixture(); + const read = f.read.getMockImplementation()!; + f.read.mockImplementation(async () => { + if (f.read.mock.calls.length === 3) f.observation.job.workflow_run_id = start.workflowRunId; + return read(); + }); + expect(await f.run()).toMatchObject({ status: "admitted" }); + expect(f.read).toHaveBeenCalledTimes(3); + expect(f.sleepUntil.mock.calls.map(([d]) => d.getTime())).toEqual([ + start.startedAt + 1000, + start.startedAt + 2000, + ]); + }); + it("keeps the original 30 second deadline and IDs when admission never arrives", async () => { + const f = fixture(); + expect(await f.run()).toEqual({ + status: "needs-reconciliation", + reason: "deadline", + job_id: "job", + workflow_run_id: start.workflowRunId, + hold_expires_at: expiry, + deadline_at: start.startedAt + 30_000, + }); + expect(f.read).toHaveBeenCalledTimes(31); + expect(f.sleepUntil).toHaveBeenCalledTimes(30); + }); + it("does not reset a journaled start deadline after a delayed/restarted read", async () => { + const f = fixture(); + f.setNow(start.startedAt + 31_000); + f.observation.job.workflow_run_id = start.workflowRunId; + expect(await f.run()).toMatchObject({ + status: "needs-reconciliation", + reason: "deadline", + deadline_at: start.startedAt + 30_000, + }); + expect(f.read).toHaveBeenCalledTimes(1); + expect(f.sleepUntil).not.toHaveBeenCalled(); + }); + for (const [field, value, reason] of [ + ["workflow_run_id", "other-run", "different-run"], + ["workflow_run_id", "", "different-run"], + ["status", "completed", "not-running"], + ["id", "other-job", "scope"], + ["owner_id", "other-owner", "scope"], + ["hold_expires_at", null, "invalid-hold"], + ["hold_expires_at", "invalid", "invalid-hold"], + ["hold_expires_at", new Date(start.startedAt).toISOString(), "expired-hold"], + ] as const) + it(`rejects ${field}=${value} without another read or wait`, async () => { + const f = fixture(); + Object.assign(f.observation.job, { [field]: value }); + expect(await f.run()).toMatchObject({ status: "needs-reconciliation", reason }); + expect(f.read).toHaveBeenCalledTimes(1); + expect(f.sleepUntil).not.toHaveBeenCalled(); + }); + it("does not poll past hold expiry or renew the original hold", async () => { + const f = fixture(); + const short = new Date(start.startedAt + 350).toISOString(); + f.observation.job.hold_expires_at = short; + expect(await f.run()).toMatchObject({ reason: "expired-hold", hold_expires_at: short }); + expect(f.sleepUntil.mock.calls.map(([d]) => d.getTime())).toEqual([start.startedAt + 350]); + }); + it("reports read/access failure without a retry or invented hold expiry", async () => { + const f = fixture(); + f.read.mockRejectedValue(new Error("access denied")); + expect(await f.run()).toMatchObject({ + status: "needs-reconciliation", + reason: "read-failed", + hold_expires_at: null, + }); + expect(f.read).toHaveBeenCalledTimes(1); + expect(f.sleepUntil).not.toHaveBeenCalled(); + }); + it("rejects a changed executing run ID", async () => { + const f = fixture(); + f.observation.workflowRunId = "other-run"; + expect(await f.run()).toMatchObject({ + reason: "different-run", + workflow_run_id: start.workflowRunId, + }); + expect(f.sleepUntil).not.toHaveBeenCalled(); + }); + it("rejects a nonfinite or backwards clock", async () => { + for (const value of [NaN, start.startedAt - 1]) { + const f = fixture(); + f.setNow(value); + expect(await f.run()).toMatchObject({ reason: "invalid-clock" }); + expect(f.sleepUntil).not.toHaveBeenCalled(); + } + }); + it("keeps the original hold boundary when a later read shows an extension", async () => { + const f = fixture(); + const original = new Date(start.startedAt + 1500).toISOString(); + f.observation.job.hold_expires_at = original; + const read = f.read.getMockImplementation()!; + f.read.mockImplementation(async () => { + if (f.read.mock.calls.length > 1) f.observation.job.hold_expires_at = expiry; + return read(); + }); + expect(await f.run()).toMatchObject({ reason: "expired-hold", hold_expires_at: original }); + expect(f.sleepUntil.mock.calls.map(([d]) => d.getTime())).toEqual([ + start.startedAt + 1000, + start.startedAt + 1500, + ]); + }); + it("retains known hold identity on a later read failure without retry", async () => { + const f = fixture(); + const read = f.read.getMockImplementation()!; + f.read.mockImplementationOnce(read).mockRejectedValue(new Error("connection lost")); + expect(await f.run()).toMatchObject({ reason: "read-failed", hold_expires_at: expiry }); + expect(f.read).toHaveBeenCalledTimes(2); + expect(f.sleepUntil).toHaveBeenCalledTimes(1); + }); + it("returns reconciliation if durable waiting fails without polling again", async () => { + const f = fixture(); + f.sleepUntil.mockRejectedValue(new Error("wait failed")); + expect(await f.run()).toMatchObject({ reason: "wait-failed", hold_expires_at: expiry }); + expect(f.read).toHaveBeenCalledTimes(1); + }); +}); diff --git a/lib/content/packs/foundation/packAdmissionTypes.ts b/lib/content/packs/foundation/packAdmissionTypes.ts new file mode 100644 index 000000000..c2afb32d5 --- /dev/null +++ b/lib/content/packs/foundation/packAdmissionTypes.ts @@ -0,0 +1,34 @@ +import type { PackActor, PackJob } from "../packTypes"; +export type PackAdmissionStart = { workflowRunId: string; startedAt: number }; +export type PackAdmissionObservation = { + workflowRunId: string; + observedAt: number; + job: Pick & { + hold_expires_at: unknown; + }; +}; +export type PackAdmissionServices = { + read: (actor: PackActor, jobId: string) => Promise; + sleepUntil: (date: Date) => Promise; +}; +export type PackAdmissionResult = { + job_id: string; + workflow_run_id: string; + hold_expires_at: string | null; + deadline_at: number; +} & ( + | { status: "admitted" } + | { + status: "needs-reconciliation"; + reason: + | "scope" + | "different-run" + | "not-running" + | "invalid-hold" + | "expired-hold" + | "deadline" + | "read-failed" + | "wait-failed" + | "invalid-clock"; + } +); diff --git a/lib/content/packs/foundation/pollPackAdmission.ts b/lib/content/packs/foundation/pollPackAdmission.ts new file mode 100644 index 000000000..6c46a6f31 --- /dev/null +++ b/lib/content/packs/foundation/pollPackAdmission.ts @@ -0,0 +1,64 @@ +import type { PackActor } from "../packTypes"; +import type { + PackAdmissionResult, + PackAdmissionServices, + PackAdmissionStart, +} from "./packAdmissionTypes"; +/** Unwired engineering candidate: 30-second admission cutoff; scheduled poll interval at most 1 second. */ +export async function pollPackAdmission( + actor: PackActor, + jobId: string, + start: PackAdmissionStart, + services: PackAdmissionServices, +): Promise { + const { read, sleepUntil } = services; + const deadline = start.startedAt + 30_000; + let originalExpiry: string | null = null; + let previousTime = start.startedAt; + const identity = () => ({ + job_id: jobId, + workflow_run_id: start.workflowRunId, + hold_expires_at: originalExpiry, + deadline_at: deadline, + }); + const reconcile = ( + reason: Extract["reason"], + ): PackAdmissionResult => ({ ...identity(), status: "needs-reconciliation", reason }); + if (!Number.isFinite(start.startedAt) || !Number.isFinite(deadline)) + return reconcile("invalid-clock"); + if (!start.workflowRunId) return reconcile("different-run"); + while (true) { + let observed; + try { + observed = await read(actor, jobId); + } catch { + return reconcile("read-failed"); + } + const { job, observedAt, workflowRunId } = observed; + if (!Number.isFinite(observedAt) || observedAt < previousTime) + return reconcile("invalid-clock"); + previousTime = observedAt; + if ( + job.id !== jobId || + typeof job.owner_id !== "string" || + job.owner_id.toLowerCase() !== (actor.organizationId ?? actor.accountId).toLowerCase() + ) + return reconcile("scope"); + if (workflowRunId !== start.workflowRunId) return reconcile("different-run"); + if (job.status !== "running") return reconcile("not-running"); + const expiry = typeof job.hold_expires_at === "string" ? Date.parse(job.hold_expires_at) : NaN; + if (!Number.isFinite(expiry)) return reconcile("invalid-hold"); + originalExpiry ??= job.hold_expires_at as string; + const holdDeadline = Math.min(expiry, Date.parse(originalExpiry)); + if (holdDeadline <= observedAt) return reconcile("expired-hold"); + if (job.workflow_run_id != null && job.workflow_run_id !== start.workflowRunId) + return reconcile("different-run"); + if (observedAt >= deadline) return reconcile("deadline"); + if (job.workflow_run_id === start.workflowRunId) return { ...identity(), status: "admitted" }; + try { + await sleepUntil(new Date(Math.min(observedAt + 1000, deadline, holdDeadline))); + } catch { + return reconcile("wait-failed"); + } + } +} diff --git a/scripts/pack-admission-workflow-fixture/__tests__/assertOutcome.test.mjs b/scripts/pack-admission-workflow-fixture/__tests__/assertOutcome.test.mjs new file mode 100644 index 000000000..1da7cde00 --- /dev/null +++ b/scripts/pack-admission-workflow-fixture/__tests__/assertOutcome.test.mjs @@ -0,0 +1,83 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { assertOutcome } from "../assertOutcome.mjs"; +function specimen() { + const runId = "run"; + const clock = { workflowRunId: runId, startedAt: 1000 }; + const state = { holdExpiresAt: "2099-01-01T00:00:00Z" }; + const trace = [{ action: "read", runId, jobId: "immediate", at: 1001 }]; + const journal = [ + { eventType: "run_created" }, + ...["startPackAdmissionStep", "readPackAdmissionStep"].map((name, i) => ({ + eventType: "step_created", + correlationId: `step-${i}`, + eventData: { stepName: `step//./${name}//${name}` }, + })), + ]; + const value = { + status: "admitted", + job_id: "immediate", + workflow_run_id: runId, + hold_expires_at: state.holdExpiresAt, + deadline_at: 31000, + }; + return { runId, clock, state, trace, journal, value }; +} +const check = f => + assertOutcome("immediate", f.runId, f.state, f.trace, f.journal, f.value, f.clock); +test("accepts correctly bound immediate admission", () => check(specimen())); +for (const [name, mutate] of [ + [ + "reset deadline", + f => { + f.value.deadline_at++; + }, + ], + [ + "wrong run", + f => { + f.value.workflow_run_id = "other"; + }, + ], + [ + "changed hold", + f => { + f.value.hold_expires_at = "2100-01-01T00:00:00Z"; + }, + ], + [ + "provider effect", + f => { + f.trace[0].action = "provider"; + }, + ], + [ + "second start", + f => { + f.journal.push({ eventType: "run_created" }); + }, + ], + [ + "second clock", + f => { + f.journal.push(f.journal[1]); + }, + ], + [ + "cached poll", + f => { + f.trace.push(f.trace[0]); + }, + ], + [ + "unexpected step", + f => { + f.journal.push({ eventType: "step_created", eventData: { stepName: "step//provider" } }); + }, + ], +]) + test(`rejects ${name}`, () => { + const f = specimen(); + mutate(f); + assert.throws(() => check(f)); + }); diff --git a/scripts/pack-admission-workflow-fixture/assertOutcome.mjs b/scripts/pack-admission-workflow-fixture/assertOutcome.mjs new file mode 100644 index 000000000..a222d7f8b --- /dev/null +++ b/scripts/pack-admission-workflow-fixture/assertOutcome.mjs @@ -0,0 +1,53 @@ +import assert from "node:assert/strict"; +export function assertOutcome(scenario, runId, state, trace, journal, value, startClock) { + assert.equal(value.job_id, scenario); + assert.equal(value.workflow_run_id, runId); + assert( + trace.length > 0 && + trace.every(e => e.action === "read" && e.runId === runId && e.jobId === scenario), + ); + assert.equal( + journal.filter(e => e.eventType === "run_created").length, + 1, + "only the original dispatch may exist", + ); + const created = journal.filter(e => e.eventType === "step_created"); + const clocks = created.filter(e => e.eventData.stepName.endsWith("//startPackAdmissionStep")); + const reads = created.filter(e => e.eventData.stepName.endsWith("//readPackAdmissionStep")); + assert.equal(clocks.length, 1, "restart must replay the original journaled clock"); + assert.equal(reads.length, trace.length, "each poll must be a distinct durable invocation"); + assert.equal(new Set(reads.map(e => e.correlationId)).size, reads.length); + assert( + created.every(e => + ["startPackAdmissionStep", "readPackAdmissionStep"].some(name => + e.eventData.stepName.endsWith(`//${name}`), + ), + ), + ); + const waits = journal.filter(e => e.eventType === "wait_created"); + assert.equal(startClock.workflowRunId, runId); + assert.equal(value.deadline_at, startClock.startedAt + 30000); + if (["immediate", "delayed"].includes(scenario)) { + assert.equal(value.status, "admitted"); + assert.equal(value.hold_expires_at, state.holdExpiresAt); + if (scenario === "immediate") { + assert.equal(trace.length, 1); + assert.equal(waits.length, 0); + } else { + assert(trace.length >= 2); + assert(waits.length >= 1); + } + } else { + assert.equal(value.status, "needs-reconciliation"); + assert.equal(value.reason, scenario === "read-failure" ? "read-failed" : scenario); + assert.equal(value.hold_expires_at, scenario === "read-failure" ? null : state.holdExpiresAt); + if (scenario === "deadline") { + assert(trace.length >= 2 && trace.length <= 31); + assert(trace.at(-1).at >= value.deadline_at); + assert(waits.length >= 1); + } else { + assert.equal(trace.length, 1); + assert.equal(waits.length, 0); + } + } +} diff --git a/scripts/pack-admission-workflow-fixture/buildFixture.mjs b/scripts/pack-admission-workflow-fixture/buildFixture.mjs new file mode 100644 index 000000000..9aee4356b --- /dev/null +++ b/scripts/pack-admission-workflow-fixture/buildFixture.mjs @@ -0,0 +1,85 @@ +import { createRequire } from "node:module"; +import { mkdir, readFile, writeFile, symlink, readdir } from "node:fs/promises"; +import { join, resolve, relative } from "node:path"; +import { pathToFileURL } from "node:url"; +import { createHash } from "node:crypto"; +import { typecheckFixture } from "../pack-scheduler-workflow-fixture/typecheckFixture.mjs"; + +const require = createRequire(import.meta.url); +export async function buildFixture(root, here, temp) { + const source = join(temp, "source"); + await mkdir(source); + await symlink(join(root, "node_modules"), join(temp, "node_modules"), "dir"); + const bindings = []; + const paths = { "@/*": [join(root, "*")] }; + for (const file of await readdir(join(here, "source"))) { + if (file.endsWith(".ts.txt")) { + const bytes = await readFile(join(here, "source", file)); + await writeFile(join(source, file.slice(0, -4)), bytes); + bindings.push({ + path: `scripts/pack-admission-workflow-fixture/source/${file}`, + sha256: createHash("sha256").update(bytes).digest("hex"), + }); + } + } + paths["@/lib/supabase/release_pack_jobs/runPackCommand"] = [join(source, "runPackCommand.ts")]; + await writeFile( + join(source, "tsconfig.json"), + JSON.stringify({ + compilerOptions: { target: "ES2022", module: "ESNext", moduleResolution: "bundler", paths }, + }), + ); + + const typecheck = await typecheckFixture(root, source); + const builders = createRequire(require.resolve("workflow/next")); + const { StandaloneBuilder } = await import(pathToFileURL(builders.resolve("@workflow/builders"))); + const old = process.cwd(); + try { + process.chdir(source); + await new StandaloneBuilder({ + buildTarget: "standalone", + workingDir: source, + projectRoot: source, + dirs: ["."], + stepsBundlePath: "../generated/steps.cjs", + workflowsBundlePath: "../generated/workflows.cjs", + webhookBundlePath: "../generated/webhook.cjs", + clientBundlePath: join(temp, "generated/client.mjs"), + }).build(); + const { build } = require("esbuild"); + const graph = await build({ + entryPoints: [join(source, "workflow.ts")], + bundle: true, + platform: "node", + format: "cjs", + outdir: join(temp, "graph"), + write: false, + metafile: true, + tsconfig: join(source, "tsconfig.json"), + }); + for (const input of Object.keys(graph.metafile.inputs)) { + const full = resolve(source, input); + const path = relative(root, full); + if (path.startsWith("..") || path.includes("node_modules")) continue; + if (path.startsWith("lib/supabase/") || path.startsWith("lib/ai/")) + throw new Error(`Unexpected external effect dependency: ${path}`); + bindings.push({ + path, + sha256: createHash("sha256") + .update(await readFile(full)) + .digest("hex"), + }); + } + for (const path of ["pnpm-lock.yaml", "package.json"]) + bindings.push({ + path, + sha256: createHash("sha256") + .update(await readFile(join(root, path))) + .digest("hex"), + }); + process.chdir(old); + return { bindings, typecheck }; + } finally { + process.chdir(old); + } +} diff --git a/scripts/pack-admission-workflow-fixture/run.mjs b/scripts/pack-admission-workflow-fixture/run.mjs new file mode 100644 index 000000000..1cccfe08a --- /dev/null +++ b/scripts/pack-admission-workflow-fixture/run.mjs @@ -0,0 +1,48 @@ +import assert from "node:assert/strict"; +import { mkdtemp, realpath, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { denyNetwork } from "../pack-scheduler-workflow-fixture/denyNetwork.mjs"; +import { buildFixture } from "./buildFixture.mjs"; +import { runWorker } from "./runWorker.mjs"; +import { runScenario } from "./runScenario.mjs"; +const attempts = denyNetwork(); +const here = dirname(fileURLToPath(import.meta.url)); +const root = resolve(here, "../.."); +if (process.argv[2] === "worker") + await runWorker(process.argv[3], process.argv[4], process.argv[5], attempts); +else { + const temp = await realpath(await mkdtemp(join(tmpdir(), "pack-admission-workflow-"))); + try { + const build = await buildFixture(root, here, temp); + const results = []; + for (const scenario of [ + "immediate", + "delayed", + "deadline", + "different-run", + "read-failure", + "expired-hold", + ]) + results.push(await runScenario(root, here, temp, scenario)); + assert.equal(attempts(), 0); + if (process.env.PACK_ADMISSION_OUTPUT) + await writeFile( + process.env.PACK_ADMISSION_OUTPUT, + JSON.stringify( + { + ...build, + results, + networkAttempts: attempts(), + scope: + "Actual unwired admission coordinator and durable steps, synthetic read RPC. Local SIGKILL/restart and terminal replay; no hosted/database/provider execution or activation.", + }, + null, + 2, + ), + ); + } finally { + await rm(temp, { recursive: true, force: true }); + } +} diff --git a/scripts/pack-admission-workflow-fixture/runScenario.mjs b/scripts/pack-admission-workflow-fixture/runScenario.mjs new file mode 100644 index 000000000..4e8dae19a --- /dev/null +++ b/scripts/pack-admission-workflow-fixture/runScenario.mjs @@ -0,0 +1,74 @@ +import assert from "node:assert/strict"; +import { join } from "node:path"; +import { readJson } from "../pack-scheduler-workflow-fixture/readJson.mjs"; +import { waitFor } from "../pack-scheduler-workflow-fixture/waitFor.mjs"; +import { spawn } from "node:child_process"; +import { mkdir, writeFile } from "node:fs/promises"; +export async function runScenario(root, here, temp, scenario) { + const effects = join(temp, scenario); + await mkdir(effects); + await writeFile(join(effects, "events.jsonl"), ""); + await writeFile( + join(effects, "state.json"), + JSON.stringify({ + scenario, + savedRunId: + scenario === "immediate" ? "current" : scenario === "different-run" ? "other-run" : null, + holdExpiresAt: new Date(scenario === "expired-hold" ? 0 : Date.now() + 120000).toISOString(), + }), + ); + let child; + try { + const launch = phase => { + const c = spawn(process.execPath, [join(here, "run.mjs"), "worker", temp, scenario, phase], { + cwd: root, + stdio: ["ignore", "pipe", "pipe"], + }); + c.stdout.on("data", bytes => process.stdout.write(bytes)); + c.stderr.on("data", bytes => process.stderr.write(bytes)); + return c; + }; + child = launch("start"); + await waitFor(async () => { + if (child.exitCode !== null || child.signalCode !== null) + throw new Error(`Fixture child exited ${child.exitCode ?? child.signalCode}`); + try { + await readJson(join(effects, "ready.json")); + return true; + } catch (error) { + if (error.code !== "ENOENT") throw error; + return false; + } + }); + const startReceipt = await readJson(join(effects, "ready.json")); + assert.equal(startReceipt.networkAttempts, 0); + const killed = new Promise(resolve => + child.once("exit", (code, signal) => resolve({ code, signal })), + ); + child.kill("SIGKILL"); + assert.equal((await killed).signal, "SIGKILL"); + child = undefined; + if (scenario === "delayed") { + const state = await readJson(join(effects, "state.json")); + const { runId } = await readJson(join(effects, "run.json")); + // Simulate the original dispatcher persisting its returned ID, never another start. + await writeFile(join(effects, "state.json"), JSON.stringify({ ...state, savedRunId: runId })); + } + child = launch("resume"); + await waitFor(async () => child.exitCode !== null || child.signalCode !== null, 60000); + assert.equal(child.exitCode, 0); + child = undefined; + const result = await readJson(join(effects, "result.json")); + return { + ...result, + startNetworkAttempts: startReceipt.networkAttempts, + resumeNetworkAttempts: result.networkAttempts, + }; + } finally { + if (child && child.exitCode === null && child.signalCode === null) { + const exited = new Promise(resolve => child.once("exit", resolve)); + child.kill("SIGKILL"); + await exited; + } + } +} diff --git a/scripts/pack-admission-workflow-fixture/runWorker.mjs b/scripts/pack-admission-workflow-fixture/runWorker.mjs new file mode 100644 index 000000000..c2191b246 --- /dev/null +++ b/scripts/pack-admission-workflow-fixture/runWorker.mjs @@ -0,0 +1,124 @@ +import assert from "node:assert/strict"; +import { join } from "node:path"; +import { writeFile, rename } from "node:fs/promises"; +import { createFixtureWorld } from "../pack-scheduler-workflow-fixture/createFixtureWorld.mjs"; +import { readJson } from "../pack-scheduler-workflow-fixture/readJson.mjs"; +import { readEvents } from "../pack-scheduler-workflow-fixture/readEvents.mjs"; +import { waitFor } from "../pack-scheduler-workflow-fixture/waitFor.mjs"; +import { assertOutcome } from "./assertOutcome.mjs"; +export async function runWorker(temp, scenario, phase, attempts) { + const { hydrateStepReturnValue } = await import("@workflow/core/serialization"); + const effects = join(temp, scenario); + const ctx = await createFixtureWorld(temp, effects); + const keepAlive = setInterval(() => {}, 1000); + const idle = () => ctx.counts().deliveries > 0 && ctx.counts().activeDeliveries === 0; + const journal = async runId => { + const events = []; + let cursor; + do { + const page = await ctx.world.events.list({ runId, pagination: { sortOrder: "asc", cursor } }); + events.push(...page.data); + cursor = page.hasMore ? page.cursor : undefined; + } while (cursor); + return events; + }; + const readClock = async runId => { + const events = await journal(runId); + const created = events.find( + e => + e.eventType === "step_created" && e.eventData.stepName.endsWith("//startPackAdmissionStep"), + ); + const completed = events.find( + e => e.eventType === "step_completed" && e.correlationId === created?.correlationId, + ); + assert(completed, "start clock must be journaled before restart"); + return hydrateStepReturnValue(completed.eventData.result, runId, undefined); + }; + const finished = async () => { + try { + return Boolean(await ctx.getHookByToken(`${scenario}:finished`)); + } catch (error) { + if (!ctx.isHookNotFound(error)) throw error; + return false; + } + }; + try { + if (phase === "start") { + const run = await ctx.start(ctx.packSchedulerFixture, [scenario, 2]); + await writeFile(join(effects, "run.json"), JSON.stringify({ runId: run.runId })); + await waitFor( + async () => + idle() && + (["delayed", "deadline"].includes(scenario) + ? (await journal(run.runId)).some(e => e.eventType === "wait_created") + : await finished()), + ); + await writeFile( + join(effects, "start-clock.json"), + JSON.stringify(await readClock(run.runId)), + ); + const trace = await readEvents(effects); + assert(trace.length >= 1 && trace.every(e => e.action === "read")); + await writeFile(join(effects, "before-crash.json"), JSON.stringify(trace)); + await writeFile( + join(effects, "initial-state.json"), + JSON.stringify(await readJson(join(effects, "state.json"))), + ); + assert.equal(attempts(), 0); + await writeFile(join(effects, "ready.tmp"), JSON.stringify({ networkAttempts: attempts() })); + await rename(join(effects, "ready.tmp"), join(effects, "ready.json")); + await new Promise(() => {}); + } + const { runId } = await readJson(join(effects, "run.json")); + const run = ctx.getRun(runId); + await ctx.reenqueueRun(ctx.world, runId); + await waitFor(async () => idle() && (await finished()), 45000); + await ctx.resumeHook(`${scenario}:finished`, "continue"); + const value = await run.returnValue; + const trace = await readEvents(effects); + const state = await readJson(join(effects, "state.json")); + const initial = await readJson(join(effects, "initial-state.json")); + assert.deepEqual(state, { + ...initial, + ...(scenario === "delayed" ? { savedRunId: runId } : {}), + }); + const events = await journal(runId); + const startClock = await readJson(join(effects, "start-clock.json")); + assert.deepEqual(await readClock(runId), startClock); + assertOutcome(scenario, runId, state, trace, events, value, startClock); + const before = ctx.counts().deliveries; + await ctx.reenqueueRun(ctx.world, runId); + await waitFor(() => idle() && ctx.counts().deliveries > before); + assert.deepEqual(await readEvents(effects), trace); + assert.deepEqual(await readJson(join(effects, "state.json")), state); + assert.equal(attempts(), 0); + await writeFile( + join(effects, "result.json"), + JSON.stringify({ + scenario, + runId, + startClock, + value, + trace, + state, + journal: events.map(e => ({ + eventType: e.eventType, + eventId: e.eventId, + correlationId: e.correlationId, + stepName: e.eventData?.stepName, + resumeAt: e.eventData?.resumeAt, + })), + networkAttempts: attempts(), + startCount: 1, + replay: + "Original start clock, distinct fresh read steps, no repeated read effects on terminal replay", + }), + ); + console.log( + `PASS ${scenario}: ${value.status}, ${trace.length} read(s), restart and terminal replay`, + ); + } finally { + clearInterval(keepAlive); + await ctx.world.close(); + } +} diff --git a/scripts/pack-admission-workflow-fixture/source/fixtureSchemas.ts.txt b/scripts/pack-admission-workflow-fixture/source/fixtureSchemas.ts.txt new file mode 100644 index 000000000..3ef572a7f --- /dev/null +++ b/scripts/pack-admission-workflow-fixture/source/fixtureSchemas.ts.txt @@ -0,0 +1,15 @@ +import { z } from "zod"; +// Required by the unchanged shared strict-type negative control. +export type { PackAsset as FixtureAsset } from "@/lib/content/packs/packTypes"; +export const admissionStateSchema = z.object({ + scenario: z.enum([ + "immediate", + "delayed", + "deadline", + "different-run", + "read-failure", + "expired-hold", + ]), + savedRunId: z.string().nullable(), + holdExpiresAt: z.string(), +}); diff --git a/scripts/pack-admission-workflow-fixture/source/runPackCommand.ts.txt b/scripts/pack-admission-workflow-fixture/source/runPackCommand.ts.txt new file mode 100644 index 000000000..7a82f13ff --- /dev/null +++ b/scripts/pack-admission-workflow-fixture/source/runPackCommand.ts.txt @@ -0,0 +1,33 @@ +import { readFileSync, appendFileSync } from "node:fs"; +import { join } from "node:path"; +import { admissionStateSchema } from "./fixtureSchemas"; +import { getWorkflowMetadata } from "workflow"; +import type { PackActor } from "@/lib/content/packs/packTypes"; +import type { PackAdmissionObservation } from "@/lib/content/packs/foundation/packAdmissionTypes"; +export async function runPackCommand( + actor: PackActor, + action: string, + jobId: string, +): Promise<{ job: PackAdmissionObservation["job"] }> { + const path = process.env.PACK_SCHEDULER_EFFECTS!; + if (action !== "read" || actor.accountId !== "fixture-owner") + throw new Error("Forbidden fixture effect"); + const state = admissionStateSchema.parse( + JSON.parse(readFileSync(join(path, "state.json"), "utf8")), + ); + const runId = getWorkflowMetadata().workflowRunId; + appendFileSync( + join(path, "events.jsonl"), + JSON.stringify({ action, jobId, runId, at: Date.now() }) + "\n", + ); + if (state.scenario === "read-failure") throw new Error("Fixture access denied"); + return { + job: { + id: jobId, + owner_id: actor.accountId, + status: "running", + workflow_run_id: state.savedRunId === "current" ? runId : state.savedRunId, + hold_expires_at: state.holdExpiresAt, + }, + }; +} diff --git a/scripts/pack-admission-workflow-fixture/source/workflow.ts.txt b/scripts/pack-admission-workflow-fixture/source/workflow.ts.txt new file mode 100644 index 000000000..bf66a2891 --- /dev/null +++ b/scripts/pack-admission-workflow-fixture/source/workflow.ts.txt @@ -0,0 +1,9 @@ +import { createHook } from "workflow"; +import { waitForPackAdmission } from "@/app/workflows/packs/foundation/waitForPackAdmission"; +// Unregistered local fixture; actual coordinator and durable steps, synthetic read RPC only. +export async function packSchedulerFixture(jobId: string, _limit: number) { + "use workflow"; + const result = await waitForPackAdmission({ accountId: "fixture-owner" }, jobId); + await createHook({ token: `${jobId}:finished` }); + return result; +} From e64e31253798b9bc3386b1bcc766388714872537 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:19:16 -0500 Subject: [PATCH 2/9] Route admission fixture oracle tests through the Node runner --- vitest.config.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/vitest.config.ts b/vitest.config.ts index d4c4946b1..fdb8dd157 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -11,6 +11,7 @@ export default defineConfig({ // This fixture owns node:test lifecycle cases and a separate compiled runtime runner. "scripts/pack-scheduler-workflow-fixture/**", "scripts/pack-foundation-workflow-fixture/**", + "scripts/pack-admission-workflow-fixture/**", ], env: { PRIVY_PROJECT_SECRET: "test-secret", From 75010d5fc6dbbc25d38a10da8f675d716bd85db8 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:24:50 -0500 Subject: [PATCH 3/9] Bind admission replay proof to exact waits and read step identities --- .github/workflows/test.yml | 4 +- .../foundation/startPackAdmissionStep.ts | 2 +- .../packs/foundation/ADMISSION_WAIT.md | 12 ++- .../packs/foundation/packAdmissionTypes.ts | 4 +- .../packs/foundation/pollPackAdmission.ts | 3 +- package.json | 1 + .../__tests__/assertOutcome.test.mjs | 83 ++++++++++++++++++- .../assertOutcome.mjs | 56 ++++++++++++- .../buildFixture.mjs | 2 +- .../readAdmissionJournal.mjs | 10 +++ .../readAdmissionResults.mjs | 17 ++++ .../pack-admission-workflow-fixture/run.mjs | 1 + .../runScenario.mjs | 6 +- .../runWorker.mjs | 73 ++++++---------- .../source/fixtureSchemas.ts.txt | 1 + .../source/runPackCommand.ts.txt | 5 +- .../writeAdmissionReceipt.mjs | 20 +++++ 17 files changed, 229 insertions(+), 71 deletions(-) create mode 100644 scripts/pack-admission-workflow-fixture/readAdmissionJournal.mjs create mode 100644 scripts/pack-admission-workflow-fixture/readAdmissionResults.mjs create mode 100644 scripts/pack-admission-workflow-fixture/writeAdmissionReceipt.mjs diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 03bc60d4d..c5ae210e4 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -43,9 +43,7 @@ jobs: run: pnpm test:pack-foundation-workflow - name: Check unwired pack admission wait and restart - run: | - node --test scripts/pack-admission-workflow-fixture/__tests__/*.test.mjs - node scripts/pack-admission-workflow-fixture/run.mjs + run: pnpm test:pack-admission-workflow - name: Check actual unwired pack foundation port compilation run: | diff --git a/app/workflows/packs/foundation/startPackAdmissionStep.ts b/app/workflows/packs/foundation/startPackAdmissionStep.ts index 01711f020..68739973c 100644 --- a/app/workflows/packs/foundation/startPackAdmissionStep.ts +++ b/app/workflows/packs/foundation/startPackAdmissionStep.ts @@ -1,5 +1,5 @@ import { getWorkflowMetadata } from "workflow"; -/** Journal this start clock once; replay must never reset the candidate deadline. */ +/** After this result is durably completed, replay preserves its candidate deadline. */ export async function startPackAdmissionStep() { "use step"; return { workflowRunId: getWorkflowMetadata().workflowRunId, startedAt: Date.now() }; diff --git a/lib/content/packs/foundation/ADMISSION_WAIT.md b/lib/content/packs/foundation/ADMISSION_WAIT.md index 02cf826a8..cc80d8633 100644 --- a/lib/content/packs/foundation/ADMISSION_WAIT.md +++ b/lib/content/packs/foundation/ADMISSION_WAIT.md @@ -10,8 +10,9 @@ not a selected production timeout or service-level guarantee. invokes `readPackAdmissionStep` separately, producing a distinct durable step result. Completed reads replay from their own journal entries; the next poll is a new read, not reuse of a cached initial snapshot. Absolute durable sleeps stop at the earlier -of the next poll time, original hold expiry and admission deadline. Restart cannot -reset the start clock or extend the deadline. +of the next poll time, original hold expiry and admission deadline. Once the start-step result is durably completed, restart cannot reset that saved +clock or extend its deadline. A crash before completion can execute the clock step +again; the fixture does not qualify that pre-journal window. The read step calls only the existing owner/org-scoped read RPC. The loop tolerates only an absent saved workflow ID on the same running, authorized job with a valid @@ -47,9 +48,12 @@ coordinator and durable steps, replacing only the read RPC with a typed syntheti boundary. It uses the unchanged shared local-world, network-denial, polling and strict-type helpers. Scenarios cover immediate admission, delayed persistence across process restart, deadline across restart, different ID, read/access failure and -expired hold. The fixture retains the decoded original journaled start-clock result +expired hold, and expiry while waiting. The fixture retains the decoded original journaled start-clock result and checks the exact deadline, distinct read-step correlations, one original start, -no other step/effect, unchanged hold and no repeated reads after terminal replay. +no other step/effect, unchanged hold and exact scheduled wake times against every +decoded read result. Pre-crash trace entries must remain an unchanged prefix; each +effect carries its durable step ID and must occur exactly once across restart and +terminal replay. Fresh polls already due at restart are allowed distinct IDs. The delayed case simulates persistence of the original dispatch ID outside the workflow; it does not perform self-admission or start a second workflow. diff --git a/lib/content/packs/foundation/packAdmissionTypes.ts b/lib/content/packs/foundation/packAdmissionTypes.ts index c2afb32d5..237796ea3 100644 --- a/lib/content/packs/foundation/packAdmissionTypes.ts +++ b/lib/content/packs/foundation/packAdmissionTypes.ts @@ -14,12 +14,12 @@ export type PackAdmissionServices = { export type PackAdmissionResult = { job_id: string; workflow_run_id: string; - hold_expires_at: string | null; deadline_at: number; } & ( - | { status: "admitted" } + | { status: "admitted"; hold_expires_at: string } | { status: "needs-reconciliation"; + hold_expires_at: string | null; reason: | "scope" | "different-run" diff --git a/lib/content/packs/foundation/pollPackAdmission.ts b/lib/content/packs/foundation/pollPackAdmission.ts index 6c46a6f31..25d020d99 100644 --- a/lib/content/packs/foundation/pollPackAdmission.ts +++ b/lib/content/packs/foundation/pollPackAdmission.ts @@ -54,7 +54,8 @@ export async function pollPackAdmission( if (job.workflow_run_id != null && job.workflow_run_id !== start.workflowRunId) return reconcile("different-run"); if (observedAt >= deadline) return reconcile("deadline"); - if (job.workflow_run_id === start.workflowRunId) return { ...identity(), status: "admitted" }; + if (job.workflow_run_id === start.workflowRunId) + return { ...identity(), status: "admitted", hold_expires_at: originalExpiry }; try { await sleepUntil(new Date(Math.min(observedAt + 1000, deadline, holdDeadline))); } catch { diff --git a/package.json b/package.json index 7da5095c8..8cf4122df 100644 --- a/package.json +++ b/package.json @@ -28,6 +28,7 @@ "test:ingestion": "vitest run lib/ingestion/__tests__", "typecheck:ingestion": "tsc --noEmit --project tsconfig.ingestion-core.json && tsc --noEmit --project tsconfig.ingestion.json", "test:pack-scheduler-workflow": "node --test scripts/pack-scheduler-workflow-fixture/__tests__/*.test.mjs && node scripts/pack-scheduler-workflow-fixture/run.mjs", + "test:pack-admission-workflow": "node --test scripts/pack-admission-workflow-fixture/__tests__/*.test.mjs && node scripts/pack-admission-workflow-fixture/run.mjs", "test:pack-foundation-workflow": "node --test scripts/pack-foundation-workflow-fixture/__tests__/*.test.mjs && node scripts/pack-foundation-workflow-fixture/run.mjs" }, "dependencies": { diff --git a/scripts/pack-admission-workflow-fixture/__tests__/assertOutcome.test.mjs b/scripts/pack-admission-workflow-fixture/__tests__/assertOutcome.test.mjs index 1da7cde00..6cf7889f6 100644 --- a/scripts/pack-admission-workflow-fixture/__tests__/assertOutcome.test.mjs +++ b/scripts/pack-admission-workflow-fixture/__tests__/assertOutcome.test.mjs @@ -5,7 +5,7 @@ function specimen() { const runId = "run"; const clock = { workflowRunId: runId, startedAt: 1000 }; const state = { holdExpiresAt: "2099-01-01T00:00:00Z" }; - const trace = [{ action: "read", runId, jobId: "immediate", at: 1001 }]; + const trace = [{ action: "read", runId, jobId: "immediate", at: 1001, stepId: "step-1" }]; const journal = [ { eventType: "run_created" }, ...["startPackAdmissionStep", "readPackAdmissionStep"].map((name, i) => ({ @@ -21,10 +21,33 @@ function specimen() { hold_expires_at: state.holdExpiresAt, deadline_at: 31000, }; - return { runId, clock, state, trace, journal, value }; + return { + runId, + clock, + state, + trace, + journal, + value, + observations: [ + { + observedAt: 1001, + workflowRunId: runId, + job: { workflow_run_id: runId, hold_expires_at: state.holdExpiresAt }, + }, + ], + }; } const check = f => - assertOutcome("immediate", f.runId, f.state, f.trace, f.journal, f.value, f.clock); + assertOutcome( + "immediate", + f.runId, + f.state, + f.trace, + f.journal, + f.value, + f.clock, + f.observations, + ); test("accepts correctly bound immediate admission", () => check(specimen())); for (const [name, mutate] of [ [ @@ -81,3 +104,57 @@ for (const [name, mutate] of [ mutate(f); assert.throws(() => check(f)); }); + +function delayed() { + const f = specimen(); + f.value.job_id = "delayed"; + f.trace[0].jobId = "delayed"; + f.trace.push({ action: "read", runId: f.runId, jobId: "delayed", at: 2001, stepId: "step-2" }); + f.journal.push({ + eventType: "step_created", + correlationId: "step-2", + eventData: { stepName: "step//./readPackAdmissionStep//readPackAdmissionStep" }, + }); + f.journal.push({ eventType: "wait_created", eventData: { resumeAt: new Date(2001) } }); + f.observations[0].job.workflow_run_id = null; + f.observations.push({ + ...f.observations[0], + observedAt: 2001, + job: { ...f.observations[0].job, workflow_run_id: f.runId }, + }); + return f; +} +const checkDelayed = f => + assertOutcome("delayed", f.runId, f.state, f.trace, f.journal, f.value, f.clock, f.observations); +test("accepts exact scheduled wake boundary", () => checkDelayed(delayed())); +for (const [name, mutate] of [ + [ + "long poll", + f => { + f.journal.at(-1).eventData.resumeAt = new Date(2002); + }, + ], + [ + "missing wait", + f => { + f.journal.pop(); + }, + ], + [ + "extra wait", + f => { + f.journal.push(f.journal.at(-1)); + }, + ], + [ + "repeated pre-crash read", + f => { + f.trace[1].stepId = f.trace[0].stepId; + }, + ], +]) + test(`rejects ${name}`, () => { + const f = delayed(); + mutate(f); + assert.throws(() => checkDelayed(f)); + }); diff --git a/scripts/pack-admission-workflow-fixture/assertOutcome.mjs b/scripts/pack-admission-workflow-fixture/assertOutcome.mjs index a222d7f8b..4e2d4a665 100644 --- a/scripts/pack-admission-workflow-fixture/assertOutcome.mjs +++ b/scripts/pack-admission-workflow-fixture/assertOutcome.mjs @@ -1,5 +1,14 @@ import assert from "node:assert/strict"; -export function assertOutcome(scenario, runId, state, trace, journal, value, startClock) { +export function assertOutcome( + scenario, + runId, + state, + trace, + journal, + value, + startClock, + observations, +) { assert.equal(value.job_id, scenario); assert.equal(value.workflow_run_id, runId); assert( @@ -17,6 +26,11 @@ export function assertOutcome(scenario, runId, state, trace, journal, value, sta assert.equal(clocks.length, 1, "restart must replay the original journaled clock"); assert.equal(reads.length, trace.length, "each poll must be a distinct durable invocation"); assert.equal(new Set(reads.map(e => e.correlationId)).size, reads.length); + assert.deepEqual( + trace.map(e => e.stepId), + reads.map(e => e.correlationId), + "each durable read effect occurs once, including across restart", + ); assert( created.every(e => ["startPackAdmissionStep", "readPackAdmissionStep"].some(name => @@ -27,6 +41,30 @@ export function assertOutcome(scenario, runId, state, trace, journal, value, sta const waits = journal.filter(e => e.eventType === "wait_created"); assert.equal(startClock.workflowRunId, runId); assert.equal(value.deadline_at, startClock.startedAt + 30000); + const originalExpiry = observations.length + ? Date.parse(observations[0].job.hold_expires_at) + : NaN; + const expectedWakeTimes = observations + .filter( + o => + o.job.workflow_run_id == null && + o.observedAt < value.deadline_at && + Date.parse(o.job.hold_expires_at) > o.observedAt && + originalExpiry > o.observedAt, + ) + .map(o => + Math.min( + o.observedAt + 1000, + value.deadline_at, + originalExpiry, + Date.parse(o.job.hold_expires_at), + ), + ); + assert.deepEqual( + waits.map(e => new Date(e.eventData.resumeAt).getTime()), + expectedWakeTimes, + "exact earliest boundary for every scheduled wait; no extra waits", + ); if (["immediate", "delayed"].includes(scenario)) { assert.equal(value.status, "admitted"); assert.equal(value.hold_expires_at, state.holdExpiresAt); @@ -39,11 +77,21 @@ export function assertOutcome(scenario, runId, state, trace, journal, value, sta } } else { assert.equal(value.status, "needs-reconciliation"); - assert.equal(value.reason, scenario === "read-failure" ? "read-failed" : scenario); + assert.equal( + value.reason, + scenario === "read-failure" + ? "read-failed" + : scenario === "hold-expiry" + ? "expired-hold" + : scenario, + ); assert.equal(value.hold_expires_at, scenario === "read-failure" ? null : state.holdExpiresAt); - if (scenario === "deadline") { + if (scenario === "deadline" || scenario === "hold-expiry") { assert(trace.length >= 2 && trace.length <= 31); - assert(trace.at(-1).at >= value.deadline_at); + assert( + trace.at(-1).at >= + (scenario === "deadline" ? value.deadline_at : Date.parse(state.holdExpiresAt)), + ); assert(waits.length >= 1); } else { assert.equal(trace.length, 1); diff --git a/scripts/pack-admission-workflow-fixture/buildFixture.mjs b/scripts/pack-admission-workflow-fixture/buildFixture.mjs index 9aee4356b..2bb9a8ae1 100644 --- a/scripts/pack-admission-workflow-fixture/buildFixture.mjs +++ b/scripts/pack-admission-workflow-fixture/buildFixture.mjs @@ -59,7 +59,7 @@ export async function buildFixture(root, here, temp) { }); for (const input of Object.keys(graph.metafile.inputs)) { const full = resolve(source, input); - const path = relative(root, full); + const path = relative(root, full).replaceAll("\\", "/"); if (path.startsWith("..") || path.includes("node_modules")) continue; if (path.startsWith("lib/supabase/") || path.startsWith("lib/ai/")) throw new Error(`Unexpected external effect dependency: ${path}`); diff --git a/scripts/pack-admission-workflow-fixture/readAdmissionJournal.mjs b/scripts/pack-admission-workflow-fixture/readAdmissionJournal.mjs new file mode 100644 index 000000000..2496e4131 --- /dev/null +++ b/scripts/pack-admission-workflow-fixture/readAdmissionJournal.mjs @@ -0,0 +1,10 @@ +export async function readAdmissionJournal(world, runId) { + const events = []; + let cursor; + do { + const page = await world.events.list({ runId, pagination: { sortOrder: "asc", cursor } }); + events.push(...page.data); + cursor = page.hasMore ? page.cursor : undefined; + } while (cursor); + return events; +} diff --git a/scripts/pack-admission-workflow-fixture/readAdmissionResults.mjs b/scripts/pack-admission-workflow-fixture/readAdmissionResults.mjs new file mode 100644 index 000000000..d5dcf305a --- /dev/null +++ b/scripts/pack-admission-workflow-fixture/readAdmissionResults.mjs @@ -0,0 +1,17 @@ +import assert from "node:assert/strict"; +import { hydrateStepReturnValue } from "@workflow/core/serialization"; +export async function readAdmissionResults(events, runId) { + let startClock; + const observations = []; + for (const created of events.filter(e => e.eventType === "step_created")) { + const completed = events.find( + e => e.eventType === "step_completed" && e.correlationId === created.correlationId, + ); + if (!completed) continue; + const result = await hydrateStepReturnValue(completed.eventData.result, runId, undefined); + if (created.eventData.stepName.endsWith("//startPackAdmissionStep")) startClock = result; + if (created.eventData.stepName.endsWith("//readPackAdmissionStep")) observations.push(result); + } + assert(startClock, "start clock must be journaled before restart"); + return { startClock, observations }; +} diff --git a/scripts/pack-admission-workflow-fixture/run.mjs b/scripts/pack-admission-workflow-fixture/run.mjs index 1cccfe08a..32b5e2aca 100644 --- a/scripts/pack-admission-workflow-fixture/run.mjs +++ b/scripts/pack-admission-workflow-fixture/run.mjs @@ -24,6 +24,7 @@ else { "different-run", "read-failure", "expired-hold", + "hold-expiry", ]) results.push(await runScenario(root, here, temp, scenario)); assert.equal(attempts(), 0); diff --git a/scripts/pack-admission-workflow-fixture/runScenario.mjs b/scripts/pack-admission-workflow-fixture/runScenario.mjs index 4e8dae19a..b90cceeef 100644 --- a/scripts/pack-admission-workflow-fixture/runScenario.mjs +++ b/scripts/pack-admission-workflow-fixture/runScenario.mjs @@ -14,7 +14,11 @@ export async function runScenario(root, here, temp, scenario) { scenario, savedRunId: scenario === "immediate" ? "current" : scenario === "different-run" ? "other-run" : null, - holdExpiresAt: new Date(scenario === "expired-hold" ? 0 : Date.now() + 120000).toISOString(), + holdExpiresAt: new Date( + scenario === "expired-hold" + ? 0 + : Date.now() + (scenario === "hold-expiry" ? 10000 : 120000), + ).toISOString(), }), ); let child; diff --git a/scripts/pack-admission-workflow-fixture/runWorker.mjs b/scripts/pack-admission-workflow-fixture/runWorker.mjs index c2191b246..d2c44f53e 100644 --- a/scripts/pack-admission-workflow-fixture/runWorker.mjs +++ b/scripts/pack-admission-workflow-fixture/runWorker.mjs @@ -5,35 +5,17 @@ import { createFixtureWorld } from "../pack-scheduler-workflow-fixture/createFix import { readJson } from "../pack-scheduler-workflow-fixture/readJson.mjs"; import { readEvents } from "../pack-scheduler-workflow-fixture/readEvents.mjs"; import { waitFor } from "../pack-scheduler-workflow-fixture/waitFor.mjs"; +import { readAdmissionJournal } from "./readAdmissionJournal.mjs"; +import { readAdmissionResults } from "./readAdmissionResults.mjs"; +import { writeAdmissionReceipt } from "./writeAdmissionReceipt.mjs"; import { assertOutcome } from "./assertOutcome.mjs"; export async function runWorker(temp, scenario, phase, attempts) { - const { hydrateStepReturnValue } = await import("@workflow/core/serialization"); const effects = join(temp, scenario); const ctx = await createFixtureWorld(temp, effects); const keepAlive = setInterval(() => {}, 1000); const idle = () => ctx.counts().deliveries > 0 && ctx.counts().activeDeliveries === 0; - const journal = async runId => { - const events = []; - let cursor; - do { - const page = await ctx.world.events.list({ runId, pagination: { sortOrder: "asc", cursor } }); - events.push(...page.data); - cursor = page.hasMore ? page.cursor : undefined; - } while (cursor); - return events; - }; - const readClock = async runId => { - const events = await journal(runId); - const created = events.find( - e => - e.eventType === "step_created" && e.eventData.stepName.endsWith("//startPackAdmissionStep"), - ); - const completed = events.find( - e => e.eventType === "step_completed" && e.correlationId === created?.correlationId, - ); - assert(completed, "start clock must be journaled before restart"); - return hydrateStepReturnValue(completed.eventData.result, runId, undefined); - }; + const journal = runId => readAdmissionJournal(ctx.world, runId); + const results = async runId => readAdmissionResults(await journal(runId), runId); const finished = async () => { try { return Boolean(await ctx.getHookByToken(`${scenario}:finished`)); @@ -49,13 +31,13 @@ export async function runWorker(temp, scenario, phase, attempts) { await waitFor( async () => idle() && - (["delayed", "deadline"].includes(scenario) + (["delayed", "deadline", "hold-expiry"].includes(scenario) ? (await journal(run.runId)).some(e => e.eventType === "wait_created") : await finished()), ); await writeFile( join(effects, "start-clock.json"), - JSON.stringify(await readClock(run.runId)), + JSON.stringify((await results(run.runId)).startClock), ); const trace = await readEvents(effects); assert(trace.length >= 1 && trace.every(e => e.action === "read")); @@ -84,36 +66,29 @@ export async function runWorker(temp, scenario, phase, attempts) { }); const events = await journal(runId); const startClock = await readJson(join(effects, "start-clock.json")); - assert.deepEqual(await readClock(runId), startClock); - assertOutcome(scenario, runId, state, trace, events, value, startClock); + const decoded = await readAdmissionResults(events, runId); + assert.deepEqual(decoded.startClock, startClock); + const beforeCrash = await readJson(join(effects, "before-crash.json")); + assert.deepEqual(trace.slice(0, beforeCrash.length), beforeCrash); + // Fresh polls may already be due at restart. Exact step IDs distinguish them from replayed effects. + assertOutcome(scenario, runId, state, trace, events, value, startClock, decoded.observations); const before = ctx.counts().deliveries; await ctx.reenqueueRun(ctx.world, runId); await waitFor(() => idle() && ctx.counts().deliveries > before); assert.deepEqual(await readEvents(effects), trace); assert.deepEqual(await readJson(join(effects, "state.json")), state); assert.equal(attempts(), 0); - await writeFile( - join(effects, "result.json"), - JSON.stringify({ - scenario, - runId, - startClock, - value, - trace, - state, - journal: events.map(e => ({ - eventType: e.eventType, - eventId: e.eventId, - correlationId: e.correlationId, - stepName: e.eventData?.stepName, - resumeAt: e.eventData?.resumeAt, - })), - networkAttempts: attempts(), - startCount: 1, - replay: - "Original start clock, distinct fresh read steps, no repeated read effects on terminal replay", - }), - ); + await writeAdmissionReceipt(effects, { + scenario, + runId, + startClock, + observations: decoded.observations, + value, + trace, + state, + journal: events, + networkAttempts: attempts(), + }); console.log( `PASS ${scenario}: ${value.status}, ${trace.length} read(s), restart and terminal replay`, ); diff --git a/scripts/pack-admission-workflow-fixture/source/fixtureSchemas.ts.txt b/scripts/pack-admission-workflow-fixture/source/fixtureSchemas.ts.txt index 3ef572a7f..347bcb25f 100644 --- a/scripts/pack-admission-workflow-fixture/source/fixtureSchemas.ts.txt +++ b/scripts/pack-admission-workflow-fixture/source/fixtureSchemas.ts.txt @@ -9,6 +9,7 @@ export const admissionStateSchema = z.object({ "different-run", "read-failure", "expired-hold", + "hold-expiry", ]), savedRunId: z.string().nullable(), holdExpiresAt: z.string(), diff --git a/scripts/pack-admission-workflow-fixture/source/runPackCommand.ts.txt b/scripts/pack-admission-workflow-fixture/source/runPackCommand.ts.txt index 7a82f13ff..c3502bdc5 100644 --- a/scripts/pack-admission-workflow-fixture/source/runPackCommand.ts.txt +++ b/scripts/pack-admission-workflow-fixture/source/runPackCommand.ts.txt @@ -1,7 +1,7 @@ import { readFileSync, appendFileSync } from "node:fs"; import { join } from "node:path"; import { admissionStateSchema } from "./fixtureSchemas"; -import { getWorkflowMetadata } from "workflow"; +import { getStepMetadata, getWorkflowMetadata } from "workflow"; import type { PackActor } from "@/lib/content/packs/packTypes"; import type { PackAdmissionObservation } from "@/lib/content/packs/foundation/packAdmissionTypes"; export async function runPackCommand( @@ -18,7 +18,8 @@ export async function runPackCommand( const runId = getWorkflowMetadata().workflowRunId; appendFileSync( join(path, "events.jsonl"), - JSON.stringify({ action, jobId, runId, at: Date.now() }) + "\n", + JSON.stringify({ action, jobId, runId, at: Date.now(), stepId: getStepMetadata().stepId }) + + "\n", ); if (state.scenario === "read-failure") throw new Error("Fixture access denied"); return { diff --git a/scripts/pack-admission-workflow-fixture/writeAdmissionReceipt.mjs b/scripts/pack-admission-workflow-fixture/writeAdmissionReceipt.mjs new file mode 100644 index 000000000..03ea9ef51 --- /dev/null +++ b/scripts/pack-admission-workflow-fixture/writeAdmissionReceipt.mjs @@ -0,0 +1,20 @@ +import { writeFile } from "node:fs/promises"; +import { join } from "node:path"; +export async function writeAdmissionReceipt(effects, result) { + await writeFile( + join(effects, "result.json"), + JSON.stringify({ + ...result, + journal: result.journal.map(e => ({ + eventType: e.eventType, + eventId: e.eventId, + correlationId: e.correlationId, + stepName: e.eventData?.stepName, + resumeAt: e.eventData?.resumeAt, + })), + startCount: 1, + replay: + "Completed start clock preserved; distinct read step IDs exactly once across restart and terminal replay", + }), + ); +} From 6f969292d3080234ad7d52848a3d3de22bf70078 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:49:23 -0500 Subject: [PATCH 4/9] test(packs): use observation clock for admission boundaries --- .../__tests__/assertOutcome.test.mjs | 36 +++++++++++++++++++ .../assertOutcome.mjs | 2 +- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/scripts/pack-admission-workflow-fixture/__tests__/assertOutcome.test.mjs b/scripts/pack-admission-workflow-fixture/__tests__/assertOutcome.test.mjs index 6cf7889f6..60391f044 100644 --- a/scripts/pack-admission-workflow-fixture/__tests__/assertOutcome.test.mjs +++ b/scripts/pack-admission-workflow-fixture/__tests__/assertOutcome.test.mjs @@ -158,3 +158,39 @@ for (const [name, mutate] of [ mutate(f); assert.throws(() => checkDelayed(f)); }); + +for (const scenario of ["hold-expiry", "deadline"]) { + test(`accepts ${scenario} crossed during the final read`, () => { + const f = delayed(); + const boundary = scenario === "deadline" ? f.value.deadline_at : 2002; + if (scenario === "hold-expiry") f.state.holdExpiresAt = new Date(boundary).toISOString(); + f.value = { + ...f.value, + job_id: scenario, + status: "needs-reconciliation", + reason: scenario === "hold-expiry" ? "expired-hold" : "deadline", + hold_expires_at: f.state.holdExpiresAt, + }; + for (const entry of f.trace) entry.jobId = scenario; + f.trace.at(-1).at = boundary - 1; + for (const observation of f.observations) { + observation.job.workflow_run_id = null; + observation.job.hold_expires_at = f.state.holdExpiresAt; + } + f.observations.at(-1).observedAt = boundary; + const verify = () => + assertOutcome( + scenario, + f.runId, + f.state, + f.trace, + f.journal, + f.value, + f.clock, + f.observations, + ); + verify(); + f.observations.at(-1).observedAt = boundary - 1; + assert.throws(verify, "must reject reconciliation before the observation reaches its boundary"); + }); +} diff --git a/scripts/pack-admission-workflow-fixture/assertOutcome.mjs b/scripts/pack-admission-workflow-fixture/assertOutcome.mjs index 4e2d4a665..d1469c245 100644 --- a/scripts/pack-admission-workflow-fixture/assertOutcome.mjs +++ b/scripts/pack-admission-workflow-fixture/assertOutcome.mjs @@ -89,7 +89,7 @@ export function assertOutcome( if (scenario === "deadline" || scenario === "hold-expiry") { assert(trace.length >= 2 && trace.length <= 31); assert( - trace.at(-1).at >= + observations.at(-1).observedAt >= (scenario === "deadline" ? value.deadline_at : Date.parse(state.holdExpiresAt)), ); assert(waits.length >= 1); From e60cbb518bc8a7547c70b02400a1450e58ea1a9d Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:08:45 -0500 Subject: [PATCH 5/9] test(packs): retain admission assertion failure evidence --- .../packs/foundation/ADMISSION_WAIT.md | 6 ++ .../__tests__/assertOutcome.test.mjs | 72 +++++++++++++++++++ .../assertOutcomeWithDiagnostics.mjs | 31 ++++++++ .../runWorker.mjs | 13 +++- 4 files changed, 120 insertions(+), 2 deletions(-) create mode 100644 scripts/pack-admission-workflow-fixture/assertOutcomeWithDiagnostics.mjs diff --git a/lib/content/packs/foundation/ADMISSION_WAIT.md b/lib/content/packs/foundation/ADMISSION_WAIT.md index cc80d8633..e59b01b0c 100644 --- a/lib/content/packs/foundation/ADMISSION_WAIT.md +++ b/lib/content/packs/foundation/ADMISSION_WAIT.md @@ -57,6 +57,12 @@ terminal replay. Fresh polls already due at restart are allowed distinct IDs. The delayed case simulates persistence of the original dispatch ID outside the workflow; it does not perform self-admission or start a second workflow. +On an outcome assertion failure, `PACK_ADMISSION_ASSERTION_FAILURE` in the CI log +retains the synthetic read trace, decoded observations and journal event IDs, +correlations, timestamps and wait lifecycle before temporary files are removed. +This distinguishes repeated storage events from distinct logical waits. No events +or wake timestamps are deduplicated; extra, early and late waits still fail. + This is local compiled replay with synthetic database reads. It does not establish SQL atomicity, authenticated hosting, provider execution, production timeout policy, or owner-facing continuation. The existing unconditional `run` write, reused preparation diff --git a/scripts/pack-admission-workflow-fixture/__tests__/assertOutcome.test.mjs b/scripts/pack-admission-workflow-fixture/__tests__/assertOutcome.test.mjs index 60391f044..18f518188 100644 --- a/scripts/pack-admission-workflow-fixture/__tests__/assertOutcome.test.mjs +++ b/scripts/pack-admission-workflow-fixture/__tests__/assertOutcome.test.mjs @@ -1,5 +1,6 @@ import assert from "node:assert/strict"; import { test } from "node:test"; +import { assertOutcomeWithDiagnostics } from "../assertOutcomeWithDiagnostics.mjs"; import { assertOutcome } from "../assertOutcome.mjs"; function specimen() { const runId = "run"; @@ -194,3 +195,74 @@ for (const scenario of ["hold-expiry", "deadline"]) { assert.throws(verify, "must reject reconciliation before the observation reaches its boundary"); }); } + +for (const [name, mutate] of [ + [ + "early logical wait", + f => { + f.journal.at(-1).eventData.resumeAt = new Date(2000); + }, + ], + [ + "late logical wait", + f => { + f.journal.at(-1).eventData.resumeAt = new Date(2002); + }, + ], + [ + "extra distinct logical wait", + f => { + f.journal.push({ ...f.journal.at(-1), eventId: "event-extra", correlationId: "wait-extra" }); + }, + ], + [ + "repeated storage event", + f => { + f.journal.push(f.journal.at(-1)); + }, + ], +]) { + test(`retains raw diagnostic evidence and rejects ${name}`, t => { + const f = delayed(); + f.journal.at(-1).eventId = "event-wait"; + f.journal.at(-1).correlationId = "wait-original"; + f.journal.push({ + eventType: "wait_completed", + eventId: "event-completed", + correlationId: "wait-original", + }); + const completion = f.journal.pop(); + mutate(f); + f.journal.push(completion); + const emitted = []; + t.mock.method(console, "error", (...args) => emitted.push(args)); + assert.throws( + () => + assertOutcomeWithDiagnostics({ + scenario: "delayed", + runId: f.runId, + state: f.state, + trace: f.trace, + journal: f.journal, + value: f.value, + startClock: f.clock, + observations: f.observations, + }), + { code: "ERR_ASSERTION" }, + ); + assert.equal(emitted.length, 1); + assert.equal(emitted[0][0], "PACK_ADMISSION_ASSERTION_FAILURE"); + const saved = JSON.parse(emitted[0][1]); + assert.deepEqual(saved.observations, f.observations); + assert.deepEqual(saved.trace, f.trace); + assert.deepEqual( + saved.journal.map(e => e.eventId), + f.journal.map(e => e.eventId), + ); + assert.deepEqual( + saved.journal.map(e => e.correlationId), + f.journal.map(e => e.correlationId), + ); + assert.equal(saved.journal.at(-1).eventType, "wait_completed"); + }); +} diff --git a/scripts/pack-admission-workflow-fixture/assertOutcomeWithDiagnostics.mjs b/scripts/pack-admission-workflow-fixture/assertOutcomeWithDiagnostics.mjs new file mode 100644 index 000000000..74bb432b2 --- /dev/null +++ b/scripts/pack-admission-workflow-fixture/assertOutcomeWithDiagnostics.mjs @@ -0,0 +1,31 @@ +import { assertOutcome } from "./assertOutcome.mjs"; +/** Preserve synthetic evidence in CI output before the parent removes its temporary world. */ +export function assertOutcomeWithDiagnostics(evidence) { + const { scenario, runId, state, trace, journal, value, startClock, observations } = evidence; + try { + assertOutcome(scenario, runId, state, trace, journal, value, startClock, observations); + } catch (error) { + console.error( + "PACK_ADMISSION_ASSERTION_FAILURE", + JSON.stringify({ + schema: 1, + scenario, + runId, + state, + trace, + value, + startClock, + observations, + journal: journal.map(event => ({ + eventId: event.eventId, + eventType: event.eventType, + correlationId: event.correlationId, + createdAt: event.createdAt, + stepName: event.eventData?.stepName, + resumeAt: event.eventData?.resumeAt, + })), + }), + ); + throw error; + } +} diff --git a/scripts/pack-admission-workflow-fixture/runWorker.mjs b/scripts/pack-admission-workflow-fixture/runWorker.mjs index d2c44f53e..38032c2b8 100644 --- a/scripts/pack-admission-workflow-fixture/runWorker.mjs +++ b/scripts/pack-admission-workflow-fixture/runWorker.mjs @@ -8,7 +8,7 @@ import { waitFor } from "../pack-scheduler-workflow-fixture/waitFor.mjs"; import { readAdmissionJournal } from "./readAdmissionJournal.mjs"; import { readAdmissionResults } from "./readAdmissionResults.mjs"; import { writeAdmissionReceipt } from "./writeAdmissionReceipt.mjs"; -import { assertOutcome } from "./assertOutcome.mjs"; +import { assertOutcomeWithDiagnostics } from "./assertOutcomeWithDiagnostics.mjs"; export async function runWorker(temp, scenario, phase, attempts) { const effects = join(temp, scenario); const ctx = await createFixtureWorld(temp, effects); @@ -71,7 +71,16 @@ export async function runWorker(temp, scenario, phase, attempts) { const beforeCrash = await readJson(join(effects, "before-crash.json")); assert.deepEqual(trace.slice(0, beforeCrash.length), beforeCrash); // Fresh polls may already be due at restart. Exact step IDs distinguish them from replayed effects. - assertOutcome(scenario, runId, state, trace, events, value, startClock, decoded.observations); + assertOutcomeWithDiagnostics({ + scenario, + runId, + state, + trace, + journal: events, + value, + startClock, + observations: decoded.observations, + }); const before = ctx.counts().deliveries; await ctx.reenqueueRun(ctx.world, runId); await waitFor(() => idle() && ctx.counts().deliveries > before); From b46a6efb99d616ffbb9991a479a8d880407c2cb9 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:12:09 -0500 Subject: [PATCH 6/9] test(packs): save restart evidence before admission assertions --- .../packs/foundation/ADMISSION_WAIT.md | 6 +++- .../__tests__/assertOutcome.test.mjs | 8 +++++ .../assertOutcomeWithDiagnostics.mjs | 4 +++ .../runScenario.mjs | 10 +++++++ .../runWorker.mjs | 29 ++++++++++++------- 5 files changed, 46 insertions(+), 11 deletions(-) diff --git a/lib/content/packs/foundation/ADMISSION_WAIT.md b/lib/content/packs/foundation/ADMISSION_WAIT.md index e59b01b0c..8667db560 100644 --- a/lib/content/packs/foundation/ADMISSION_WAIT.md +++ b/lib/content/packs/foundation/ADMISSION_WAIT.md @@ -60,7 +60,11 @@ workflow; it does not perform self-admission or start a second workflow. On an outcome assertion failure, `PACK_ADMISSION_ASSERTION_FAILURE` in the CI log retains the synthetic read trace, decoded observations and journal event IDs, correlations, timestamps and wait lifecycle before temporary files are removed. -This distinguishes repeated storage events from distinct logical waits. No events +The resumed worker also saves raw events, delivery counts and the pre-crash trace +before decoding or assertions, then adds decoded observations before validation. +On child failure, the parent emits `PACK_ADMISSION_SAVED_FAILURE` before cleanup; +missing capture is reported explicitly. This distinguishes repeated storage events +from distinct logical waits. No events or wake timestamps are deduplicated; extra, early and late waits still fail. This is local compiled replay with synthetic database reads. It does not establish diff --git a/scripts/pack-admission-workflow-fixture/__tests__/assertOutcome.test.mjs b/scripts/pack-admission-workflow-fixture/__tests__/assertOutcome.test.mjs index 18f518188..958ed74e1 100644 --- a/scripts/pack-admission-workflow-fixture/__tests__/assertOutcome.test.mjs +++ b/scripts/pack-admission-workflow-fixture/__tests__/assertOutcome.test.mjs @@ -247,6 +247,8 @@ for (const [name, mutate] of [ value: f.value, startClock: f.clock, observations: f.observations, + beforeCrash: f.trace.slice(0, 1), + deliveryContext: { phase: "resume", deliveries: 5, activeDeliveries: 0 }, }), { code: "ERR_ASSERTION" }, ); @@ -254,6 +256,12 @@ for (const [name, mutate] of [ assert.equal(emitted[0][0], "PACK_ADMISSION_ASSERTION_FAILURE"); const saved = JSON.parse(emitted[0][1]); assert.deepEqual(saved.observations, f.observations); + assert.deepEqual(saved.beforeCrash, f.trace.slice(0, 1)); + assert.deepEqual(saved.deliveryContext, { + phase: "resume", + deliveries: 5, + activeDeliveries: 0, + }); assert.deepEqual(saved.trace, f.trace); assert.deepEqual( saved.journal.map(e => e.eventId), diff --git a/scripts/pack-admission-workflow-fixture/assertOutcomeWithDiagnostics.mjs b/scripts/pack-admission-workflow-fixture/assertOutcomeWithDiagnostics.mjs index 74bb432b2..2972adb28 100644 --- a/scripts/pack-admission-workflow-fixture/assertOutcomeWithDiagnostics.mjs +++ b/scripts/pack-admission-workflow-fixture/assertOutcomeWithDiagnostics.mjs @@ -16,6 +16,10 @@ export function assertOutcomeWithDiagnostics(evidence) { value, startClock, observations, + initialState: evidence.initialState, + beforeCrash: evidence.beforeCrash, + deliveryContext: evidence.deliveryContext, + decodedStartClock: evidence.decodedStartClock, journal: journal.map(event => ({ eventId: event.eventId, eventType: event.eventType, diff --git a/scripts/pack-admission-workflow-fixture/runScenario.mjs b/scripts/pack-admission-workflow-fixture/runScenario.mjs index b90cceeef..fc45451eb 100644 --- a/scripts/pack-admission-workflow-fixture/runScenario.mjs +++ b/scripts/pack-admission-workflow-fixture/runScenario.mjs @@ -60,6 +60,16 @@ export async function runScenario(root, here, temp, scenario) { } child = launch("resume"); await waitFor(async () => child.exitCode !== null || child.signalCode !== null, 60000); + if (child.exitCode !== 0) { + try { + console.error( + "PACK_ADMISSION_SAVED_FAILURE", + JSON.stringify(await readJson(join(effects, "assertion-evidence.json"))), + ); + } catch (error) { + console.error("PACK_ADMISSION_CAPTURE_UNAVAILABLE", error.message); + } + } assert.equal(child.exitCode, 0); child = undefined; const result = await readJson(join(effects, "result.json")); diff --git a/scripts/pack-admission-workflow-fixture/runWorker.mjs b/scripts/pack-admission-workflow-fixture/runWorker.mjs index 38032c2b8..2a4d8d5d3 100644 --- a/scripts/pack-admission-workflow-fixture/runWorker.mjs +++ b/scripts/pack-admission-workflow-fixture/runWorker.mjs @@ -60,27 +60,36 @@ export async function runWorker(temp, scenario, phase, attempts) { const trace = await readEvents(effects); const state = await readJson(join(effects, "state.json")); const initial = await readJson(join(effects, "initial-state.json")); - assert.deepEqual(state, { - ...initial, - ...(scenario === "delayed" ? { savedRunId: runId } : {}), - }); const events = await journal(runId); const startClock = await readJson(join(effects, "start-clock.json")); - const decoded = await readAdmissionResults(events, runId); - assert.deepEqual(decoded.startClock, startClock); const beforeCrash = await readJson(join(effects, "before-crash.json")); - assert.deepEqual(trace.slice(0, beforeCrash.length), beforeCrash); - // Fresh polls may already be due at restart. Exact step IDs distinguish them from replayed effects. - assertOutcomeWithDiagnostics({ + const evidence = { scenario, runId, state, + initialState: initial, trace, journal: events, value, startClock, - observations: decoded.observations, + beforeCrash, + deliveryContext: { phase, ...ctx.counts() }, + }; + // Save raw IDs/lifecycle before decoding or assertions; the parent retains failures in CI output. + const diagnostic = join(effects, "assertion-evidence.json"); + await writeFile(diagnostic, JSON.stringify(evidence)); + const decoded = await readAdmissionResults(events, runId); + evidence.observations = decoded.observations; + evidence.decodedStartClock = decoded.startClock; + await writeFile(diagnostic, JSON.stringify(evidence)); + assert.deepEqual(state, { + ...initial, + ...(scenario === "delayed" ? { savedRunId: runId } : {}), }); + assert.deepEqual(decoded.startClock, startClock); + assert.deepEqual(trace.slice(0, beforeCrash.length), beforeCrash); + // Fresh polls may already be due at restart. Exact step IDs distinguish them from replayed effects. + assertOutcomeWithDiagnostics(evidence); const before = ctx.counts().deliveries; await ctx.reenqueueRun(ctx.world, runId); await waitFor(() => idle() && ctx.counts().deliveries > before); From 496e9bd72b27a40e12fb18b3ca597782e369ddce Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:32:13 -0500 Subject: [PATCH 7/9] test(packs): trace SDK deliveries and remove duplicate recovery enqueue --- .../packs/foundation/ADMISSION_WAIT.md | 44 ++++- .../captureAdmissionFailure.test.mjs | 72 ++++++++ .../__tests__/observeAdmissionWorld.test.mjs | 145 ++++++++++++++++ .../assertRecoveryTrace.mjs | 24 +++ .../captureAdmissionFailure.mjs | 85 ++++++++++ .../createAdmissionWorld.mjs | 58 +++++++ .../installAdmissionObserver.mjs | 40 +++++ .../observeAdmissionWorld.mjs | 147 ++++++++++++++++ .../probeRecoveryEnqueues.mjs | 120 +++++++++++++ .../probeWaitCreation.mjs | 159 ++++++++++++++++++ .../readAdmissionJournal.mjs | 13 +- .../pack-admission-workflow-fixture/run.mjs | 5 + .../runScenario.mjs | 45 +++-- .../runWorker.mjs | 43 ++++- 14 files changed, 975 insertions(+), 25 deletions(-) create mode 100644 scripts/pack-admission-workflow-fixture/__tests__/captureAdmissionFailure.test.mjs create mode 100644 scripts/pack-admission-workflow-fixture/__tests__/observeAdmissionWorld.test.mjs create mode 100644 scripts/pack-admission-workflow-fixture/assertRecoveryTrace.mjs create mode 100644 scripts/pack-admission-workflow-fixture/captureAdmissionFailure.mjs create mode 100644 scripts/pack-admission-workflow-fixture/createAdmissionWorld.mjs create mode 100644 scripts/pack-admission-workflow-fixture/installAdmissionObserver.mjs create mode 100644 scripts/pack-admission-workflow-fixture/observeAdmissionWorld.mjs create mode 100644 scripts/pack-admission-workflow-fixture/probeRecoveryEnqueues.mjs create mode 100644 scripts/pack-admission-workflow-fixture/probeWaitCreation.mjs diff --git a/lib/content/packs/foundation/ADMISSION_WAIT.md b/lib/content/packs/foundation/ADMISSION_WAIT.md index 8667db560..c53cf66dc 100644 --- a/lib/content/packs/foundation/ADMISSION_WAIT.md +++ b/lib/content/packs/foundation/ADMISSION_WAIT.md @@ -45,8 +45,8 @@ read-only calls and zero retry settings. The separate `scripts/pack-admission-workflow-fixture` compiles the actual composition, coordinator and durable steps, replacing only the read RPC with a typed synthetic -boundary. It uses the unchanged shared local-world, network-denial, polling and -strict-type helpers. Scenarios cover immediate admission, delayed persistence across +boundary. It uses a fixture-local adapter around the installed SDK, plus unchanged shared +network-denial, failure-delivery, polling and strict-type helpers. Scenarios cover immediate admission, delayed persistence across process restart, deadline across restart, different ID, read/access failure and expired hold, and expiry while waiting. The fixture retains the decoded original journaled start-clock result and checks the exact deadline, distinct read-step correlations, one original start, @@ -72,3 +72,43 @@ SQL atomicity, authenticated hosting, provider execution, production timeout pol or owner-facing continuation. The existing unconditional `run` write, reused preparation write and point-in-time authorization still do not fence cross-run takeover. Production wiring and those authority/continuation contracts remain separate prerequisites. + + +## Local SDK concurrency boundary and fixture recovery + +The local fixture resumes its saved run through `world.start()` recovery exactly +once. It does not also enqueue that active run explicitly. The separate explicit +terminal replay remains mandatory. A passive observer records SDK queue message +IDs, attempts, per-handler AsyncLocalStorage context, event create requests/results, +list cursors and returned event IDs. The queue observer is installed before startup +through an isolated loader with an exact SDK source hash; installed files are not +changed. It returns original SDK promises/results and adds no locks, retries or +serialization. JSONL persistence is asynchronous and bounded; dropped entries or +persistence errors fail successful recovery-trace qualification. + +`probeRecoveryEnqueues.mjs` uses identical saved-run bytes and the actual SDK queue +with a bounded synthetic receiver. Startup-only and explicit-only each produce one +message; combining them produces two distinct messages. This probes enqueue +provenance, not generated workflow replay. `probeWaitCreation.mjs` separately gates +the actual installed filesystem writer after both wait-path absence checks, through +a byte-verified isolated loader seam. Serial duplicate creation conflicts; controlled +overlap can store distinct event IDs for the same correlation, including conflicting +wake times. The write logic and installed files remain unchanged. These deterministic +controls reproduce an SDK mechanism; they cannot retrospectively classify the earlier +CI failure whose log lacked event IDs. Removing a redundant fixture enqueue does not +establish general SDK concurrency fencing or production safety. + +Run either bounded probe with `node --import +./scripts/pack-admission-workflow-fixture/installAdmissionObserver.mjs` followed by +its script path. Receipts distinguish scope, actual requests, returned IDs, raw +records, the seam and source hashes. The exact scheduled-wake and read-effect +oracles remain strict; repeated records are retained, and contradictory payloads +for one event ID fail. Distinct waits at the same timestamp are not deduplicated. + +Failure capture now also covers parent timeout, signal and early child exit. The +parent requests a bounded live snapshot, drains incremental operation records and +reads raw journal/wait files before owned-child cleanup. It preserves the original +error and explicitly marks unavailable or truncated evidence. Snapshots from these +sources are not an atomic view of a live process. Tests force these paths and verify +retained evidence and child cleanup; they do not claim a hung event loop can answer +an IPC request. diff --git a/scripts/pack-admission-workflow-fixture/__tests__/captureAdmissionFailure.test.mjs b/scripts/pack-admission-workflow-fixture/__tests__/captureAdmissionFailure.test.mjs new file mode 100644 index 000000000..4fc639efa --- /dev/null +++ b/scripts/pack-admission-workflow-fixture/__tests__/captureAdmissionFailure.test.mjs @@ -0,0 +1,72 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { mkdtemp, writeFile, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { runScenario } from "../runScenario.mjs"; +import { readAdmissionJournal } from "../readAdmissionJournal.mjs"; +for (const scenario of ["timeout", "signal", "decoder", "assertion"]) { + test(`parent retains ${scenario} evidence and cleans up the owned child`, async t => { + const root = await mkdtemp(join(tmpdir(), "admission-capture-test-")); + t.after(() => rm(root, { recursive: true, force: true })); + await writeFile(join(root, "installAdmissionObserver.mjs"), ""); + await writeFile( + join(root, "run.mjs"), + ` + import { writeFile } from "node:fs/promises"; + import { join } from "node:path"; + const [, , , temp, scenario, phase] = process.argv; + const dir = join(temp, scenario); + const trace = { operationId: 1, stage: "call", delivery: { messageId: "real-child-message" } }; + await writeFile(join(dir, phase + "-world-trace.jsonl"), JSON.stringify(trace) + "\\n"); + if (phase === "start") { + await writeFile(join(dir, "before-crash.json"), JSON.stringify([{stepId:"original"}])); + await writeFile(join(dir, "ready.json"), JSON.stringify({ networkAttempts: 0 })); + } else { + await writeFile(join(dir, "child-pid"), String(process.pid)); + await writeFile(join(dir, "assertion-evidence.json"), JSON.stringify({ stage: scenario, journal: [{eventId:"retained-event"}] })); + if (scenario === "signal") process.kill(process.pid, "SIGKILL"); + if (scenario === "decoder" || scenario === "assertion") process.exit(17); + } + process.on("message", message => process.send({ type: "admission-snapshot", requestId: message.requestId, evidence: { trace, pid: process.pid } })); + setInterval(() => {}, 1000); + `, + ); + const output = []; + t.mock.method(console, "error", (...args) => output.push(args)); + await assert.rejects( + runScenario(root, root, root, scenario, { resumeTimeoutMs: 1000 }), + error => + scenario === "timeout" + ? error.message === "Offline fixture deadline exceeded" + : error.code === "ERR_ASSERTION", + ); + const record = output.find(args => args[0] === "PACK_ADMISSION_SAVED_FAILURE"); + assert(record); + const evidence = JSON.parse(record[1]); + assert.equal(evidence.saved.journal[0].eventId, "retained-event"); + assert.equal(evidence.resumeOperationTrace[0].delivery.messageId, "real-child-message"); + assert.equal(evidence["before-crash.json"][0].stepId, "original"); + if (scenario === "timeout") + assert.equal(evidence.live.trace.delivery.messageId, "real-child-message"); + const pid = Number(await readFile(join(root, scenario, "child-pid"), "utf8")); + assert.throws(() => process.kill(pid, 0), { code: "ESRCH" }); + }); +} +test("contradictory same-ID pages fail, while identical duplicates remain visible", async () => { + const first = { eventId: "same", correlationId: "one" }; + const world = { + events: { + list: async ({ pagination }) => + pagination.cursor + ? { data: [first], hasMore: false } + : { data: [first], cursor: "next", hasMore: true }, + }, + }; + assert.equal((await readAdmissionJournal(world, "run")).length, 2); + world.events.list = async ({ pagination }) => + pagination.cursor + ? { data: [{ ...first, correlationId: "other" }], hasMore: false } + : { data: [first], cursor: "next", hasMore: true }; + await assert.rejects(readAdmissionJournal(world, "run"), /contradictory/); +}); diff --git a/scripts/pack-admission-workflow-fixture/__tests__/observeAdmissionWorld.test.mjs b/scripts/pack-admission-workflow-fixture/__tests__/observeAdmissionWorld.test.mjs new file mode 100644 index 000000000..0ccf0d30d --- /dev/null +++ b/scripts/pack-admission-workflow-fixture/__tests__/observeAdmissionWorld.test.mjs @@ -0,0 +1,145 @@ +import { assertRecoveryTrace } from "../assertRecoveryTrace.mjs"; +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { observeAdmissionWorld } from "../observeAdmissionWorld.mjs"; +function fixture() { + const handlers = new Map(); + const world = { + registerHandler(prefix, handler) { + handlers.set(prefix, handler); + }, + events: { + create: async (_runId, data) => ({ + event: { ...data, eventId: `event-${data.correlationId}` }, + }), + list: async () => ({ + data: [{ eventId: "page-event", correlationId: "wait" }], + cursor: "next", + hasMore: true, + }), + }, + }; + return { world, handlers, observer: observeAdmissionWorld(world) }; +} +const request = id => + new Request("http://fixture", { + headers: { + "x-vqs-message-id": id, + "x-vqs-message-attempt": "1", + "x-vqs-queue-name": "__wkf_workflow_test", + }, + }); +test("interleaved deliveries preserve async identity without serialization", async () => { + const { world, handlers, observer } = fixture(); + const gates = []; + world.registerHandler("flow", async req => { + await new Promise(resolve => gates.push(resolve)); + await world.events.create("run", { + eventType: "wait_created", + correlationId: req.headers.get("x-vqs-message-id"), + }); + await world.events.list({ runId: "run", pagination: { cursor: "previous" } }); + return new Response(); + }); + const first = handlers.get("flow")(request("one")); + const second = handlers.get("flow")(request("two")); + assert.equal(gates.length, 2, "both handlers enter before either is released"); + gates[1](); + await second; + gates[0](); + await first; + const calls = observer + .snapshot() + .entries.filter(e => e.operation === "events.create" && e.stage === "call"); + assert.deepEqual( + calls.map(e => [e.delivery.messageId, e.input.event.correlationId]), + [ + ["two", "two"], + ["one", "one"], + ], + ); + const pages = observer.snapshot().entries.filter(e => e.operation === "events.list"); + assert.equal(pages[0].input.pagination.cursor, "previous"); + assert.deepEqual(pages[1].output, { + cursor: "next", + hasMore: true, + events: [ + { + eventId: "page-event", + eventType: undefined, + correlationId: "wait", + createdAt: undefined, + resumeAt: undefined, + stepName: undefined, + }, + ], + }); +}); +test("preserves exact promises, receiver, arguments and rejection", async () => { + const failure = new Error("actual SDK failure"); + const promise = Promise.reject(failure); + const args = ["run", { eventType: "wait_created", correlationId: "wait" }]; + const world = { + registerHandler() {}, + events: { + create(...actual) { + assert.equal(this, world.events); + assert.deepEqual(actual, args); + return promise; + }, + }, + }; + const observer = observeAdmissionWorld(world); + assert.equal(world.events.create(...args), promise); + await assert.rejects(promise, error => error === failure); + const entries = observer.snapshot().entries.filter(e => e.operation === "events.create"); + assert.equal(entries[0].delivery, null); + assert.equal(entries[1].stage, "reject"); + assert.equal(entries[1].error.message, failure.message); +}); +test("retains duplicate and contradictory event IDs without collapsing them", async () => { + const world = { + registerHandler() {}, + events: { + list: async () => ({ + data: [ + { eventId: "same", correlationId: "a" }, + { eventId: "same", correlationId: "b" }, + ], + hasMore: false, + }), + }, + }; + const observer = observeAdmissionWorld(world); + const page = await world.events.list({ runId: "run" }); + assert.equal(page.data.length, 2); + const events = observer.snapshot().entries.at(-1).output.events; + assert.deepEqual( + events.map(e => [e.eventId, e.correlationId]), + [ + ["same", "a"], + ["same", "b"], + ], + ); +}); + +test("rejects redundant recovery, missing terminal replay and unknown delivery IDs", () => { + const make = () => ({ + droppedEntries: 0, + entries: ["world.start", "finish-hook", "terminal-replay"].flatMap((source, i) => [ + { operation: "queue", stage: "call", source, delivery: null, input: { runId: "run" } }, + { operation: "queue", stage: "return", output: { messageId: String(i) } }, + { operation: "handler", stage: "call", delivery: { messageId: String(i) } }, + ]), + }); + assertRecoveryTrace(make(), "run"); + const redundant = make(); + redundant.entries.push(redundant.entries[0]); + assert.throws(() => assertRecoveryTrace(redundant, "run")); + const missing = make(); + missing.entries.splice(6); + assert.throws(() => assertRecoveryTrace(missing, "run")); + const unknown = make(); + unknown.entries[2].delivery.messageId = "unknown"; + assert.throws(() => assertRecoveryTrace(unknown, "run")); +}); diff --git a/scripts/pack-admission-workflow-fixture/assertRecoveryTrace.mjs b/scripts/pack-admission-workflow-fixture/assertRecoveryTrace.mjs new file mode 100644 index 000000000..06c9c2eda --- /dev/null +++ b/scripts/pack-admission-workflow-fixture/assertRecoveryTrace.mjs @@ -0,0 +1,24 @@ +import assert from "node:assert/strict"; +/** One startup recovery, one explicit terminal replay; no second startup dispatch. */ +export function assertRecoveryTrace(trace, runId) { + assert.equal(trace.droppedEntries, 0); + assert.equal(trace.persistenceError, undefined); + const calls = trace.entries.filter( + e => + e.operation === "queue" && + e.stage === "call" && + e.input.runId === runId && + e.delivery === null, + ); + assert.deepEqual( + calls.map(e => e.source), + ["world.start", "finish-hook", "terminal-replay"], + ); + const messages = new Set( + trace.entries + .filter(e => e.operation === "queue" && e.stage === "return") + .map(e => e.output.messageId), + ); + for (const handler of trace.entries.filter(e => e.operation === "handler" && e.stage === "call")) + assert(messages.has(handler.delivery.messageId), "every delivery has an observed SDK enqueue"); +} diff --git a/scripts/pack-admission-workflow-fixture/captureAdmissionFailure.mjs b/scripts/pack-admission-workflow-fixture/captureAdmissionFailure.mjs new file mode 100644 index 000000000..9de40d411 --- /dev/null +++ b/scripts/pack-admission-workflow-fixture/captureAdmissionFailure.mjs @@ -0,0 +1,85 @@ +import { readJson } from "../pack-scheduler-workflow-fixture/readJson.mjs"; +import { join } from "node:path"; +import { readFile, readdir } from "node:fs/promises"; +/** Capture is bounded and best-effort; it must never replace the original failure. */ +export async function captureAdmissionFailure(child, effects, error) { + const evidence = { error: { name: error.name, message: error.message } }; + try { + evidence.saved = await readJson(join(effects, "assertion-evidence.json")); + } catch (captureError) { + evidence.savedUnavailable = captureError.message; + } + if (child?.connected && child.exitCode === null && child.signalCode === null) { + evidence.live = await new Promise(resolve => { + const requestId = "failure-snapshot"; + const finish = value => { + clearTimeout(timer); + child.off("message", onMessage); + resolve(value); + }; + const onMessage = message => { + if (message?.type === "admission-snapshot" && message.requestId === requestId) + finish(message.evidence); + }; + const timer = setTimeout( + () => finish({ unavailable: "snapshot timed out after 1000ms" }), + 1000, + ); + child.on("message", onMessage); + try { + child.send({ type: "admission-snapshot", requestId }, sendError => { + if (sendError) finish({ unavailable: sendError.message }); + }); + } catch (sendError) { + finish({ unavailable: sendError.message }); + } + }); + } + for (const name of ["before-crash.json", "before-crash-world-trace.json", "start-clock.json"]) { + try { + evidence[name] = await readJson(join(effects, name)); + } catch (captureError) { + evidence[name] = { unavailable: captureError.message }; + } + } + for (const phase of ["start", "resume"]) { + try { + evidence[`${phase}OperationTrace`] = ( + await readFile(join(effects, `${phase}-world-trace.jsonl`), "utf8") + ) + .split("\n") + .filter(Boolean) + .map(line => { + try { + return JSON.parse(line); + } catch { + return { incompleteRawLine: line }; + } + }); + } catch (captureError) { + evidence[`${phase}OperationTrace`] = { unavailable: captureError.message }; + } + } + for (const kind of ["events", "waits"]) { + try { + const directory = join(effects, "journal", kind); + const names = (await readdir(directory)).filter(name => name.endsWith(".json")).sort(); + evidence[`raw${kind}`] = { + truncated: names.length > 2048, + files: await Promise.all( + names.slice(0, 2048).map(async name => { + try { + return { name, data: await readJson(join(directory, name)) }; + } catch (readError) { + return { name, unavailable: readError.message }; + } + }), + ), + }; + } catch (captureError) { + evidence[`raw${kind}`] = { unavailable: captureError.message }; + } + } + console.error("PACK_ADMISSION_SAVED_FAILURE", JSON.stringify(evidence, null, 2)); + return evidence; +} diff --git a/scripts/pack-admission-workflow-fixture/createAdmissionWorld.mjs b/scripts/pack-admission-workflow-fixture/createAdmissionWorld.mjs new file mode 100644 index 000000000..9a70403bc --- /dev/null +++ b/scripts/pack-admission-workflow-fixture/createAdmissionWorld.mjs @@ -0,0 +1,58 @@ +import { observeFailureDelivery } from "../pack-scheduler-workflow-fixture/observeFailureDelivery.mjs"; +import { createRequire } from "node:module"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; +import { observeAdmissionWorld } from "./observeAdmissionWorld.mjs"; +const require = createRequire(import.meta.url); +export async function createAdmissionWorld(temp, effects, phase) { + process.env.PACK_SCHEDULER_EFFECTS = effects; + const { createLocalWorld } = await import( + pathToFileURL(createRequire(require.resolve("@workflow/core")).resolve("@workflow/world-local")) + ); + const { HookNotFoundError } = await import( + pathToFileURL(createRequire(require.resolve("@workflow/core")).resolve("@workflow/errors")) + ); + const { setWorld, reenqueueRun } = await import("@workflow/core/runtime"); + const { start, getRun, resumeHook, getHookByToken } = await import("workflow/api"); + const world = createLocalWorld({ dataDir: join(effects, "journal") }); + const observer = observeAdmissionWorld(world, { + phase, + outputPath: join(effects, `${phase}-world-trace.jsonl`), + }); + const observers = globalThis[Symbol.for("pack.admission.queue.observers")]; + if (!observers) throw new Error("Admission queue observer preload is required"); + observers.set(join(effects, "journal"), observer.observeQueue); + const failureDelivery = observeFailureDelivery(world); + setWorld(world); + const steps = await import(pathToFileURL(join(temp, "generated/steps.cjs"))); + const workflows = await import(pathToFileURL(join(temp, "generated/workflows.cjs"))); + let deliveries = 0; + let activeDeliveries = 0; + world.registerHandler("__wkf_step_", steps.POST); + world.registerHandler("__wkf_workflow_", async req => { + activeDeliveries++; + try { + const response = await failureDelivery.deliver(workflows.POST, req); + deliveries++; + return response; + } finally { + activeDeliveries--; + } + }); + await observer.source("world.start", () => world.start()); + const { packSchedulerFixture } = await import(pathToFileURL(join(temp, "generated/client.mjs"))); + return { + world, + observer, + isHookNotFound: HookNotFoundError.is, + start, + getRun, + resumeHook, + getHookByToken, + reenqueueRun, + packSchedulerFixture, + hasObservedFailure: failureDelivery.hasObservedFailure, + failureEvidence: failureDelivery.failureEvidence, + counts: () => ({ deliveries, activeDeliveries }), + }; +} diff --git a/scripts/pack-admission-workflow-fixture/installAdmissionObserver.mjs b/scripts/pack-admission-workflow-fixture/installAdmissionObserver.mjs new file mode 100644 index 000000000..7428c2346 --- /dev/null +++ b/scripts/pack-admission-workflow-fixture/installAdmissionObserver.mjs @@ -0,0 +1,40 @@ +import { readFileSync } from "node:fs"; +import assert from "node:assert/strict"; +import { createRequire, registerHooks } from "node:module"; +import { dirname, join } from "node:path"; +import { pathToFileURL } from "node:url"; +import { createHash } from "node:crypto"; +const require = createRequire(import.meta.url); +const local = createRequire(require.resolve("@workflow/core")).resolve("@workflow/world-local"); +const sdk = JSON.parse(readFileSync(join(dirname(local), "../package.json"), "utf8")); +assert.equal(sdk.version, "4.1.1"); +globalThis[Symbol.for("pack.admission.sdk")] = { + worldLocal: sdk.version, + queueSha256: "0a22ec456650db6acfaf877856520eafa835b149759295aa9c8736396e67a012", +}; +const queueUrl = pathToFileURL(join(dirname(local), "queue.js")).href; +const key = Symbol.for("pack.admission.queue.observers"); +globalThis[key] ??= new Map(); +registerHooks({ + load(url, context, nextLoad) { + const loaded = nextLoad(url, context); + if (url !== queueUrl) return loaded; + const source = String(loaded.source); + assert.equal( + createHash("sha256").update(source).digest("hex"), + "0a22ec456650db6acfaf877856520eafa835b149759295aa9c8736396e67a012", + ); + const needle = " queue,\n"; + assert.equal(source.split(needle).length, 2); + return { + ...loaded, + source: source.replace( + needle, + ` queue: (...args) => { + const observer = globalThis[Symbol.for("pack.admission.queue.observers")]?.get(config.dataDir); + return observer ? observer(queue, args) : queue(...args); + },\n`, + ), + }; + }, +}); diff --git a/scripts/pack-admission-workflow-fixture/observeAdmissionWorld.mjs b/scripts/pack-admission-workflow-fixture/observeAdmissionWorld.mjs new file mode 100644 index 000000000..eddf6e54b --- /dev/null +++ b/scripts/pack-admission-workflow-fixture/observeAdmissionWorld.mjs @@ -0,0 +1,147 @@ +import { AsyncLocalStorage } from "node:async_hooks"; +import { appendFile } from "node:fs/promises"; +/** Passive, in-memory tracing: no sleeps, locks, retries, body reads or altered SDK results. */ +export function observeAdmissionWorld(world, options = {}) { + const deliveries = new AsyncLocalStorage(); + const sources = new AsyncLocalStorage(); + let pending = Promise.resolve(); + let persistenceError; + let droppedEntries = 0; + const trace = []; + let nextOperation = 0; + let nextDelivery = 0; + const record = entry => { + if (trace.length >= 20000) { + droppedEntries++; + return; + } + const item = { + sequence: trace.length, + at: Date.now(), + pid: process.pid, + phase: options.phase, + source: sources.getStore() ?? "external", + ...entry, + }; + trace.push(item); + if (options.outputPath) + pending = pending + .then(() => appendFile(options.outputPath, JSON.stringify(item) + "\n")) + .catch(error => { + persistenceError = error.message; + }); + }; + const event = e => + e && { + eventId: e.eventId, + eventType: e.eventType, + correlationId: e.correlationId, + createdAt: e.createdAt, + resumeAt: e.eventData?.resumeAt, + stepName: e.eventData?.stepName, + }; + const observe = (operation, input, invoke, project) => { + const operationId = ++nextOperation; + const delivery = deliveries.getStore() ?? null; + record({ operationId, delivery, operation, stage: "call", input }); + try { + const result = invoke(); + result + .then( + value => + record({ operationId, delivery, operation, stage: "return", output: project(value) }), + error => + record({ + operationId, + delivery, + operation, + stage: "reject", + error: { name: error.name, message: error.message }, + }), + ) + .catch(error => + record({ operationId, operation, stage: "observer-error", error: error.message }), + ); + return result; + } catch (error) { + record({ + operationId, + delivery, + operation, + stage: "throw", + error: { name: error.name, message: error.message }, + }); + throw error; + } + }; + const register = world.registerHandler; + world.registerHandler = function (prefix, handler) { + return register.call(this, prefix, function (...args) { + const req = args[0]; + const delivery = { + deliveryId: ++nextDelivery, + source: sources.getStore() ?? "external", + prefix, + queueName: req.headers.get("x-vqs-queue-name"), + messageId: req.headers.get("x-vqs-message-id"), + attempt: req.headers.get("x-vqs-message-attempt"), + }; + return deliveries.run(delivery, () => + observe( + "handler", + { prefix }, + () => handler.apply(this, args), + response => ({ status: response.status }), + ), + ); + }); + }; + for (const method of ["create", "list", "listByCorrelationId"]) { + const original = world.events[method]; + if (!original) continue; + world.events[method] = function (...args) { + const input = + method === "create" + ? { runId: args[0], event: event(args[1]) } + : { ...args[0], pagination: args[0]?.pagination && { ...args[0].pagination } }; + return observe( + `events.${method}`, + input, + () => original.apply(this, args), + result => + method === "create" + ? { + event: event(result.event), + waitId: result.wait?.waitId, + preloadedEvents: result.events?.map(event), + } + : { cursor: result.cursor, hasMore: result.hasMore, events: result.data.map(event) }, + ); + }; + } + const observeQueue = (queue, args) => + observe( + "queue", + { + queueName: args[0], + runId: args[1]?.runId ?? args[1]?.workflowRunId, + stepId: args[1]?.stepId, + idempotencyKey: args[2]?.idempotencyKey, + }, + () => queue(...args), + value => ({ messageId: value.messageId }), + ); + record({ + operation: "observer", + stage: "installed", + schema: 1, + sdk: globalThis[Symbol.for("pack.admission.sdk")], + sourceHead: process.env.PACK_ADMISSION_SOURCE_HEAD ?? "unbound", + }); + return { + snapshot: () => ({ entries: structuredClone(trace), droppedEntries, persistenceError }), + flush: () => pending, + observeQueue, + source: (label, invoke) => sources.run(label, () => observe(label, {}, invoke, () => ({}))), + }; +} diff --git a/scripts/pack-admission-workflow-fixture/probeRecoveryEnqueues.mjs b/scripts/pack-admission-workflow-fixture/probeRecoveryEnqueues.mjs new file mode 100644 index 000000000..70def394f --- /dev/null +++ b/scripts/pack-admission-workflow-fixture/probeRecoveryEnqueues.mjs @@ -0,0 +1,120 @@ +import assert from "node:assert/strict"; +import { createRequire } from "node:module"; +import { dirname, join } from "node:path"; +import { pathToFileURL } from "node:url"; +import { mkdtemp, cp, rm, writeFile, readFile } from "node:fs/promises"; +import { createHash } from "node:crypto"; +import { tmpdir } from "node:os"; +import { observeAdmissionWorld } from "./observeAdmissionWorld.mjs"; +import { denyNetwork } from "../pack-scheduler-workflow-fixture/denyNetwork.mjs"; +const network = denyNetwork(); +const require = createRequire(import.meta.url); +const core = require.resolve("@workflow/core"); +const local = createRequire(core).resolve("@workflow/world-local"); +const { createLocalWorld } = await import(pathToFileURL(local)); +const { reenqueueRun } = await import("@workflow/core/runtime"); +const root = await mkdtemp(join(tmpdir(), "admission-enqueue-probe-")); +const seedPath = join(root, "seed"); +const seed = createLocalWorld({ dataDir: seedPath }); +const cases = []; +try { + await seed.start(); + const created = await seed.events.create(null, { + eventType: "run_created", + eventData: { + deploymentId: "probe", + workflowName: "workflow//./probe//probe", + input: new Uint8Array(), + }, + }); + const runId = created.run.runId; + await seed.events.create(runId, { eventType: "run_started" }); + const seedBytes = await readFile(join(seedPath, "runs", `${runId}.json`)); + const seedSha256 = createHash("sha256").update(seedBytes).digest("hex"); + for (const kind of ["startup-only", "explicit-only", "startup-plus-explicit"]) { + const dataDir = join(root, kind); + await cp(seedPath, dataDir, { recursive: true }); + assert.deepEqual(await readFile(join(dataDir, "runs", `${runId}.json`)), seedBytes); + const world = createLocalWorld({ dataDir }); + const observer = observeAdmissionWorld(world, { phase: kind }); + globalThis[Symbol.for("pack.admission.queue.observers")].set(dataDir, observer.observeQueue); + const expected = kind === "startup-plus-explicit" ? 2 : 1; + const deliveries = []; + let release; + const barrier = new Promise(resolve => { + release = resolve; + }); + let resolveDone, rejectDone; + const done = new Promise((resolve, reject) => { + resolveDone = resolve; + rejectDone = reject; + }); + const timer = setTimeout(() => { + release(); + rejectDone(new Error("Bounded delivery barrier timed out")); + }, 3000); + world.registerHandler("__wkf_workflow_", async request => { + deliveries.push({ + messageId: request.headers.get("x-vqs-message-id"), + attempt: request.headers.get("x-vqs-message-attempt"), + }); + if (deliveries.length === expected) release(); + await barrier; + setImmediate(resolveDone); + return Response.json({}); + }); + try { + if (kind !== "explicit-only") await observer.source("world.start", () => world.start()); + if (kind !== "startup-only") + await observer.source("explicit-reenqueue", () => reenqueueRun(world, runId)); + await done; + assert.equal(deliveries.length, expected); + assert.equal(new Set(deliveries.map(delivery => delivery.messageId)).size, expected); + const operations = observer.snapshot(); + const enqueues = operations.entries.filter( + entry => entry.operation === "queue" && entry.stage === "return", + ); + assert.equal(enqueues.length, expected); + assert.deepEqual( + enqueues.map(entry => entry.output.messageId).sort(), + deliveries.map(delivery => delivery.messageId).sort(), + ); + cases.push({ kind, runId, seedSha256, deliveries, operations }); + } finally { + clearTimeout(timer); + release(); + await world.close(); + } + } + assert.equal(network(), 0); + const sdkBindings = await Promise.all( + [local, join(dirname(local), "queue.js"), join(dirname(core), "runtime/runs.js")].map( + async path => ({ + path, + sha256: createHash("sha256") + .update(await readFile(path)) + .digest("hex"), + }), + ), + ); + await writeFile( + process.env.PACK_ADMISSION_PROBE_OUTPUT ?? "/tmp/pack-admission-enqueue-probe.json", + JSON.stringify( + { + scope: + "Actual SDK enqueue/recovery with bounded synthetic receiver; not generated workflow replay or historical failure attribution", + sdkBindings, + cases, + networkAttempts: network(), + }, + null, + 2, + ), + ); + console.log( + "PASS fixed-snapshot startup1 / explicit1 / startup-plus-explicit2 distinct queued deliveries", + ); +} finally { + await seed.close(); + await rm(root, { recursive: true, force: true }); +} diff --git a/scripts/pack-admission-workflow-fixture/probeWaitCreation.mjs b/scripts/pack-admission-workflow-fixture/probeWaitCreation.mjs new file mode 100644 index 000000000..5b16daf5f --- /dev/null +++ b/scripts/pack-admission-workflow-fixture/probeWaitCreation.mjs @@ -0,0 +1,159 @@ +import assert from "node:assert/strict"; +import { createRequire, registerHooks } from "node:module"; +import { dirname, join } from "node:path"; +import { pathToFileURL } from "node:url"; +import { createHash } from "node:crypto"; +import { mkdtemp, rm, readFile, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { observeAdmissionWorld } from "./observeAdmissionWorld.mjs"; +import { readAdmissionJournal } from "./readAdmissionJournal.mjs"; +import { denyNetwork } from "../pack-scheduler-workflow-fixture/denyNetwork.mjs"; +const network = denyNetwork(); +const require = createRequire(import.meta.url); +const local = createRequire(require.resolve("@workflow/core")).resolve("@workflow/world-local"); +const fsUrl = pathToFileURL(join(dirname(local), "fs.js")).href; +const fsHash = "7e754ee442b71cc09281c5646fb44f5034e3642f4f65383b3b93db1ccbea34f6"; +const gateKey = Symbol.for("pack.admission.probe.after-absent-check"); +const needle = " const tempPath = `${filePath}.tmp.${ulid()}`;"; +const insertion = ` if (globalThis[Symbol.for("pack.admission.probe.after-absent-check")]) + await globalThis[Symbol.for("pack.admission.probe.after-absent-check")](filePath, Boolean(opts?.overwrite));\n`; +registerHooks({ + load(url, context, nextLoad) { + const loaded = nextLoad(url, context); + if (url !== fsUrl) return loaded; + const source = String(loaded.source); + assert.equal(createHash("sha256").update(source).digest("hex"), fsHash); + assert.equal(source.split(needle).length, 2); + return { ...loaded, source: source.replace(needle, insertion + needle) }; + }, +}); +const { createLocalWorld } = await import(pathToFileURL(local)); +const root = await mkdtemp(join(tmpdir(), "admission-storage-probe-")); +const cases = []; +try { + for (const kind of [ + "serial", + "same-correlation-same-wake", + "different-correlations-same-wake", + "same-correlation-conflicting-wake", + ]) { + const dataDir = join(root, kind); + const world = createLocalWorld({ dataDir }); + const observer = observeAdmissionWorld(world, { phase: kind }); + await world.start(); + try { + const created = await world.events.create(null, { + eventType: "run_created", + eventData: { deploymentId: "probe", workflowName: "probe", input: new Uint8Array() }, + }); + const runId = created.run.runId; + await world.events.create(runId, { eventType: "run_started" }); + const wake = new Date(Date.now() + 60000); + const inputs = [0, 1].map(i => ({ + eventType: "wait_created", + correlationId: + kind === "different-correlations-same-wake" ? `wait_probe_${i}` : "wait_probe", + eventData: { + resumeAt: new Date( + wake.getTime() + (kind === "same-correlation-conflicting-wake" ? i : 0), + ), + }, + })); + const absences = []; + let release; + const barrier = new Promise(resolve => { + release = resolve; + }); + let timeout; + if (kind !== "serial") { + timeout = setTimeout(() => release(), 2000); + globalThis[gateKey] = async (filePath, overwrite) => { + if ( + overwrite || + !inputs.some( + input => filePath === join(dataDir, "waits", `${runId}-${input.correlationId}.json`), + ) + ) + return; + absences.push({ filePath, overwrite, stage: "actual-fs.access-observed-ENOENT" }); + if (absences.length === 2) release(); + await barrier; + }; + } + let results; + try { + if (kind === "serial") { + const first = await world.events.create(runId, inputs[0]); + results = [ + { status: "fulfilled", value: first }, + ...(await Promise.allSettled([world.events.create(runId, inputs[1])])), + ]; + } else + results = await Promise.allSettled( + inputs.map(input => world.events.create(runId, input)), + ); + } finally { + clearTimeout(timeout); + delete globalThis[gateKey]; + } + const journal = await readAdmissionJournal(world, runId); + const waits = journal.filter(event => event.eventType === "wait_created"); + if (kind === "serial") { + assert.equal(results[1].status, "rejected"); + assert.equal(results[1].reason.name, "EntityConflictError"); + assert.equal(waits.length, 1); + } else { + assert.equal(absences.length, 2); + assert(results.every(result => result.status === "fulfilled")); + assert.equal(waits.length, 2); + assert.notEqual(waits[0].eventId, waits[1].eventId); + } + const files = await Promise.all( + [...new Set(inputs.map(input => input.correlationId))].map(async correlationId => ({ + correlationId, + data: JSON.parse( + await readFile(join(dataDir, "waits", `${runId}-${correlationId}.json`), "utf8"), + ), + })), + ); + cases.push({ + kind, + runId, + absences, + inputs, + results: results.map(result => + result.status === "fulfilled" + ? { status: result.status, eventId: result.value.event.eventId } + : { + status: result.status, + error: { name: result.reason.name, message: result.reason.message }, + }, + ), + journal, + waitFiles: files, + operations: observer.snapshot(), + }); + } finally { + await world.close(); + } + } + assert.equal(network(), 0); + const receipt = { + scope: + "Deterministic installed SDK storage mechanism probe; not attribution of historical CI failure or production fencing", + fsHash, + seam: insertion, + cases, + networkAttempts: network(), + }; + await writeFile( + process.env.PACK_ADMISSION_PROBE_OUTPUT ?? "/tmp/pack-admission-storage-probe.json", + JSON.stringify(receipt, null, 2), + ); + console.log( + "PASS serial conflict and three controlled absent-check overlaps; distinct stored event IDs retained", + ); +} finally { + delete globalThis[gateKey]; + await rm(root, { recursive: true, force: true }); +} diff --git a/scripts/pack-admission-workflow-fixture/readAdmissionJournal.mjs b/scripts/pack-admission-workflow-fixture/readAdmissionJournal.mjs index 2496e4131..24e8007bf 100644 --- a/scripts/pack-admission-workflow-fixture/readAdmissionJournal.mjs +++ b/scripts/pack-admission-workflow-fixture/readAdmissionJournal.mjs @@ -1,9 +1,20 @@ +import assert from "node:assert/strict"; export async function readAdmissionJournal(world, runId) { const events = []; + const seen = new Map(); let cursor; do { const page = await world.events.list({ runId, pagination: { sortOrder: "asc", cursor } }); - events.push(...page.data); + for (const event of page.data) { + if (seen.has(event.eventId)) + assert.deepEqual( + event, + seen.get(event.eventId), + "Same event ID has contradictory payloads", + ); + seen.set(event.eventId, event); + events.push(event); // Preserve repeated records; never hide them through deduplication. + } cursor = page.hasMore ? page.cursor : undefined; } while (cursor); return events; diff --git a/scripts/pack-admission-workflow-fixture/run.mjs b/scripts/pack-admission-workflow-fixture/run.mjs index 32b5e2aca..d845229fc 100644 --- a/scripts/pack-admission-workflow-fixture/run.mjs +++ b/scripts/pack-admission-workflow-fixture/run.mjs @@ -1,3 +1,4 @@ +import { execFileSync } from "node:child_process"; import assert from "node:assert/strict"; import { mkdtemp, realpath, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; @@ -10,6 +11,10 @@ import { runScenario } from "./runScenario.mjs"; const attempts = denyNetwork(); const here = dirname(fileURLToPath(import.meta.url)); const root = resolve(here, "../.."); +process.env.PACK_ADMISSION_SOURCE_HEAD ??= execFileSync("git", ["rev-parse", "HEAD"], { + cwd: root, + encoding: "utf8", +}).trim(); if (process.argv[2] === "worker") await runWorker(process.argv[3], process.argv[4], process.argv[5], attempts); else { diff --git a/scripts/pack-admission-workflow-fixture/runScenario.mjs b/scripts/pack-admission-workflow-fixture/runScenario.mjs index fc45451eb..8b94790f6 100644 --- a/scripts/pack-admission-workflow-fixture/runScenario.mjs +++ b/scripts/pack-admission-workflow-fixture/runScenario.mjs @@ -1,10 +1,11 @@ import assert from "node:assert/strict"; +import { captureAdmissionFailure } from "./captureAdmissionFailure.mjs"; import { join } from "node:path"; import { readJson } from "../pack-scheduler-workflow-fixture/readJson.mjs"; import { waitFor } from "../pack-scheduler-workflow-fixture/waitFor.mjs"; import { spawn } from "node:child_process"; import { mkdir, writeFile } from "node:fs/promises"; -export async function runScenario(root, here, temp, scenario) { +export async function runScenario(root, here, temp, scenario, { resumeTimeoutMs = 60000 } = {}) { const effects = join(temp, scenario); await mkdir(effects); await writeFile(join(effects, "events.jsonl"), ""); @@ -24,10 +25,22 @@ export async function runScenario(root, here, temp, scenario) { let child; try { const launch = phase => { - const c = spawn(process.execPath, [join(here, "run.mjs"), "worker", temp, scenario, phase], { - cwd: root, - stdio: ["ignore", "pipe", "pipe"], - }); + const c = spawn( + process.execPath, + [ + "--import", + join(here, "installAdmissionObserver.mjs"), + join(here, "run.mjs"), + "worker", + temp, + scenario, + phase, + ], + { + cwd: root, + stdio: ["ignore", "pipe", "pipe", "ipc"], + }, + ); c.stdout.on("data", bytes => process.stdout.write(bytes)); c.stderr.on("data", bytes => process.stderr.write(bytes)); return c; @@ -59,17 +72,10 @@ export async function runScenario(root, here, temp, scenario) { await writeFile(join(effects, "state.json"), JSON.stringify({ ...state, savedRunId: runId })); } child = launch("resume"); - await waitFor(async () => child.exitCode !== null || child.signalCode !== null, 60000); - if (child.exitCode !== 0) { - try { - console.error( - "PACK_ADMISSION_SAVED_FAILURE", - JSON.stringify(await readJson(join(effects, "assertion-evidence.json"))), - ); - } catch (error) { - console.error("PACK_ADMISSION_CAPTURE_UNAVAILABLE", error.message); - } - } + await waitFor( + async () => child.exitCode !== null || child.signalCode !== null, + resumeTimeoutMs, + ); assert.equal(child.exitCode, 0); child = undefined; const result = await readJson(join(effects, "result.json")); @@ -78,6 +84,13 @@ export async function runScenario(root, here, temp, scenario) { startNetworkAttempts: startReceipt.networkAttempts, resumeNetworkAttempts: result.networkAttempts, }; + } catch (error) { + try { + await captureAdmissionFailure(child, effects, error); + } catch (captureError) { + console.error("PACK_ADMISSION_CAPTURE_UNAVAILABLE", captureError.message); + } + throw error; } finally { if (child && child.exitCode === null && child.signalCode === null) { const exited = new Promise(resolve => child.once("exit", resolve)); diff --git a/scripts/pack-admission-workflow-fixture/runWorker.mjs b/scripts/pack-admission-workflow-fixture/runWorker.mjs index 2a4d8d5d3..4b5ae79b4 100644 --- a/scripts/pack-admission-workflow-fixture/runWorker.mjs +++ b/scripts/pack-admission-workflow-fixture/runWorker.mjs @@ -1,7 +1,8 @@ import assert from "node:assert/strict"; +import { assertRecoveryTrace } from "./assertRecoveryTrace.mjs"; import { join } from "node:path"; import { writeFile, rename } from "node:fs/promises"; -import { createFixtureWorld } from "../pack-scheduler-workflow-fixture/createFixtureWorld.mjs"; +import { createAdmissionWorld } from "./createAdmissionWorld.mjs"; import { readJson } from "../pack-scheduler-workflow-fixture/readJson.mjs"; import { readEvents } from "../pack-scheduler-workflow-fixture/readEvents.mjs"; import { waitFor } from "../pack-scheduler-workflow-fixture/waitFor.mjs"; @@ -11,7 +12,21 @@ import { writeAdmissionReceipt } from "./writeAdmissionReceipt.mjs"; import { assertOutcomeWithDiagnostics } from "./assertOutcomeWithDiagnostics.mjs"; export async function runWorker(temp, scenario, phase, attempts) { const effects = join(temp, scenario); - const ctx = await createFixtureWorld(temp, effects); + const ctx = await createAdmissionWorld(temp, effects, phase); + const onSnapshotRequest = message => { + if (message?.type === "admission-snapshot") + process.send?.({ + type: "admission-snapshot", + requestId: message.requestId, + evidence: { + scenario, + phase, + deliveryContext: ctx.counts(), + worldTrace: ctx.observer.snapshot(), + }, + }); + }; + process.on("message", onSnapshotRequest); const keepAlive = setInterval(() => {}, 1000); const idle = () => ctx.counts().deliveries > 0 && ctx.counts().activeDeliveries === 0; const journal = runId => readAdmissionJournal(ctx.world, runId); @@ -26,7 +41,9 @@ export async function runWorker(temp, scenario, phase, attempts) { }; try { if (phase === "start") { - const run = await ctx.start(ctx.packSchedulerFixture, [scenario, 2]); + const run = await ctx.observer.source("original-dispatch", () => + ctx.start(ctx.packSchedulerFixture, [scenario, 2]), + ); await writeFile(join(effects, "run.json"), JSON.stringify({ runId: run.runId })); await waitFor( async () => @@ -47,15 +64,22 @@ export async function runWorker(temp, scenario, phase, attempts) { JSON.stringify(await readJson(join(effects, "state.json"))), ); assert.equal(attempts(), 0); + await writeFile( + join(effects, "before-crash-world-trace.json"), + JSON.stringify(ctx.observer.snapshot()), + ); + await ctx.observer.flush(); await writeFile(join(effects, "ready.tmp"), JSON.stringify({ networkAttempts: attempts() })); await rename(join(effects, "ready.tmp"), join(effects, "ready.json")); await new Promise(() => {}); } const { runId } = await readJson(join(effects, "run.json")); const run = ctx.getRun(runId); - await ctx.reenqueueRun(ctx.world, runId); + // createAdmissionWorld already starts SDK recovery for this persisted run. await waitFor(async () => idle() && (await finished()), 45000); - await ctx.resumeHook(`${scenario}:finished`, "continue"); + await ctx.observer.source("finish-hook", () => + ctx.resumeHook(`${scenario}:finished`, "continue"), + ); const value = await run.returnValue; const trace = await readEvents(effects); const state = await readJson(join(effects, "state.json")); @@ -74,6 +98,8 @@ export async function runWorker(temp, scenario, phase, attempts) { startClock, beforeCrash, deliveryContext: { phase, ...ctx.counts() }, + worldTrace: ctx.observer.snapshot(), + beforeCrashWorldTrace: await readJson(join(effects, "before-crash-world-trace.json")), }; // Save raw IDs/lifecycle before decoding or assertions; the parent retains failures in CI output. const diagnostic = join(effects, "assertion-evidence.json"); @@ -91,11 +117,12 @@ export async function runWorker(temp, scenario, phase, attempts) { // Fresh polls may already be due at restart. Exact step IDs distinguish them from replayed effects. assertOutcomeWithDiagnostics(evidence); const before = ctx.counts().deliveries; - await ctx.reenqueueRun(ctx.world, runId); + await ctx.observer.source("terminal-replay", () => ctx.reenqueueRun(ctx.world, runId)); await waitFor(() => idle() && ctx.counts().deliveries > before); assert.deepEqual(await readEvents(effects), trace); assert.deepEqual(await readJson(join(effects, "state.json")), state); assert.equal(attempts(), 0); + assertRecoveryTrace(ctx.observer.snapshot(), runId); await writeAdmissionReceipt(effects, { scenario, runId, @@ -106,12 +133,16 @@ export async function runWorker(temp, scenario, phase, attempts) { state, journal: events, networkAttempts: attempts(), + worldTrace: ctx.observer.snapshot(), + beforeCrashWorldTrace: evidence.beforeCrashWorldTrace, }); console.log( `PASS ${scenario}: ${value.status}, ${trace.length} read(s), restart and terminal replay`, ); } finally { + process.off("message", onSnapshotRequest); clearInterval(keepAlive); await ctx.world.close(); + await ctx.observer.flush(); } } From bc86faf8406e9580ccd4e4cc45bc29de88f76951 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:35:09 -0500 Subject: [PATCH 8/9] test(packs): verify complete diagnostic lifecycle payload --- .../__tests__/assertOutcome.test.mjs | 23 +++++++++++++------ 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/scripts/pack-admission-workflow-fixture/__tests__/assertOutcome.test.mjs b/scripts/pack-admission-workflow-fixture/__tests__/assertOutcome.test.mjs index 958ed74e1..7fb1d54e9 100644 --- a/scripts/pack-admission-workflow-fixture/__tests__/assertOutcome.test.mjs +++ b/scripts/pack-admission-workflow-fixture/__tests__/assertOutcome.test.mjs @@ -234,6 +234,9 @@ for (const [name, mutate] of [ const completion = f.journal.pop(); mutate(f); f.journal.push(completion); + f.journal.forEach((event, index) => { + event.createdAt = new Date(1000 + index); + }); const emitted = []; t.mock.method(console, "error", (...args) => emitted.push(args)); assert.throws( @@ -264,13 +267,19 @@ for (const [name, mutate] of [ }); assert.deepEqual(saved.trace, f.trace); assert.deepEqual( - saved.journal.map(e => e.eventId), - f.journal.map(e => e.eventId), - ); - assert.deepEqual( - saved.journal.map(e => e.correlationId), - f.journal.map(e => e.correlationId), + saved.journal, + JSON.parse( + JSON.stringify( + f.journal.map(event => ({ + eventId: event.eventId, + eventType: event.eventType, + correlationId: event.correlationId, + createdAt: event.createdAt, + stepName: event.eventData?.stepName, + resumeAt: event.eventData?.resumeAt, + })), + ), + ), ); - assert.equal(saved.journal.at(-1).eventType, "wait_completed"); }); } From 58d73dc3b3a2ad5a0f4f12404b4c8432c3821e93 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:47:34 -0500 Subject: [PATCH 9/9] test(packs): qualify drained diagnostics at both success boundaries --- .../packs/foundation/ADMISSION_WAIT.md | 18 ++- .../captureAdmissionFailure.test.mjs | 6 +- .../__tests__/diagnosticBounds.test.mjs | 135 ++++++++++++++++++ .../captureAdmissionFailure.mjs | 53 +++---- .../denyAdmissionNetwork.mjs | 16 +++ .../drainAdmissionTrace.mjs | 12 ++ .../finalizeAdmissionWorld.mjs | 24 ++++ .../observeAdmissionWorld.mjs | 26 +++- .../probeRecoveryEnqueues.mjs | 4 +- .../probeWaitCreation.mjs | 4 +- .../readAdmissionDiagnosticFile.mjs | 40 ++++++ .../pack-admission-workflow-fixture/run.mjs | 4 +- .../runWorker.mjs | 38 ++--- 13 files changed, 322 insertions(+), 58 deletions(-) create mode 100644 scripts/pack-admission-workflow-fixture/__tests__/diagnosticBounds.test.mjs create mode 100644 scripts/pack-admission-workflow-fixture/denyAdmissionNetwork.mjs create mode 100644 scripts/pack-admission-workflow-fixture/drainAdmissionTrace.mjs create mode 100644 scripts/pack-admission-workflow-fixture/finalizeAdmissionWorld.mjs create mode 100644 scripts/pack-admission-workflow-fixture/readAdmissionDiagnosticFile.mjs diff --git a/lib/content/packs/foundation/ADMISSION_WAIT.md b/lib/content/packs/foundation/ADMISSION_WAIT.md index c53cf66dc..112b47a1c 100644 --- a/lib/content/packs/foundation/ADMISSION_WAIT.md +++ b/lib/content/packs/foundation/ADMISSION_WAIT.md @@ -46,7 +46,8 @@ read-only calls and zero retry settings. The separate `scripts/pack-admission-workflow-fixture` compiles the actual composition, coordinator and durable steps, replacing only the read RPC with a typed synthetic boundary. It uses a fixture-local adapter around the installed SDK, plus unchanged shared -network-denial, failure-delivery, polling and strict-type helpers. Scenarios cover immediate admission, delayed persistence across +failure-delivery, polling and strict-type helpers. Its local network guard extends +the unchanged shared guard to reject WebSocket construction and HTTP/2 connections. Scenarios cover immediate admission, delayed persistence across process restart, deadline across restart, different ID, read/access failure and expired hold, and expiry while waiting. The fixture retains the decoded original journaled start-clock result and checks the exact deadline, distinct read-step correlations, one original start, @@ -83,8 +84,14 @@ IDs, attempts, per-handler AsyncLocalStorage context, event create requests/resu list cursors and returned event IDs. The queue observer is installed before startup through an isolated loader with an exact SDK source hash; installed files are not changed. It returns original SDK promises/results and adds no locks, retries or -serialization. JSONL persistence is asynchronous and bounded; dropped entries or -persistence errors fail successful recovery-trace qualification. +serialization. JSONL persistence is asynchronous and capped at20,000 entries/2MiB. Successful +qualification closes the SDK, drains late log writes, checks a fresh snapshot for +dropped entries/persistence errors, then writes the receipt. A last-append failure +cannot produce a success receipt; an earlier operation error remains primary. +The start phase likewise drains and checks its snapshot before writing the +pre-crash trace or ready receipt, without closing the SDK before intentional SIGKILL. +The drain returns a frozen snapshot only after all writes queued during the drain +have settled; later observations belong to a later checkpoint. `probeRecoveryEnqueues.mjs` uses identical saved-run bytes and the actual SDK queue with a bounded synthetic receiver. Startup-only and explicit-only each produce one @@ -112,3 +119,8 @@ error and explicitly marks unavailable or truncated evidence. Snapshots from the sources are not an atomic view of a live process. Tests force these paths and verify retained evidence and child cleanup; they do not claim a hung event loop can answer an IPC request. + +Diagnostic file reads are capped before parsing:1MiB per checkpoint/operation trace, +64KiB per raw event/wait file and4MiB aggregate per raw directory. Truncation and +partial lines remain explicit evidence. These bounds supplement the one-second live +snapshot request; capture is best-effort, not a wall-clock guarantee for filesystem I/O. diff --git a/scripts/pack-admission-workflow-fixture/__tests__/captureAdmissionFailure.test.mjs b/scripts/pack-admission-workflow-fixture/__tests__/captureAdmissionFailure.test.mjs index 4fc639efa..31cd4f642 100644 --- a/scripts/pack-admission-workflow-fixture/__tests__/captureAdmissionFailure.test.mjs +++ b/scripts/pack-admission-workflow-fixture/__tests__/captureAdmissionFailure.test.mjs @@ -44,9 +44,9 @@ for (const scenario of ["timeout", "signal", "decoder", "assertion"]) { const record = output.find(args => args[0] === "PACK_ADMISSION_SAVED_FAILURE"); assert(record); const evidence = JSON.parse(record[1]); - assert.equal(evidence.saved.journal[0].eventId, "retained-event"); - assert.equal(evidence.resumeOperationTrace[0].delivery.messageId, "real-child-message"); - assert.equal(evidence["before-crash.json"][0].stepId, "original"); + assert.equal(evidence.saved.data.journal[0].eventId, "retained-event"); + assert.equal(evidence.resumeOperationTrace.data[0].delivery.messageId, "real-child-message"); + assert.equal(evidence["before-crash.json"].data[0].stepId, "original"); if (scenario === "timeout") assert.equal(evidence.live.trace.delivery.messageId, "real-child-message"); const pid = Number(await readFile(join(root, scenario, "child-pid"), "utf8")); diff --git a/scripts/pack-admission-workflow-fixture/__tests__/diagnosticBounds.test.mjs b/scripts/pack-admission-workflow-fixture/__tests__/diagnosticBounds.test.mjs new file mode 100644 index 000000000..1ad9c027d --- /dev/null +++ b/scripts/pack-admission-workflow-fixture/__tests__/diagnosticBounds.test.mjs @@ -0,0 +1,135 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { mkdtemp, writeFile, rm } from "node:fs/promises"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import { execFileSync } from "node:child_process"; +import { readAdmissionDiagnosticFile } from "../readAdmissionDiagnosticFile.mjs"; +import { observeAdmissionWorld } from "../observeAdmissionWorld.mjs"; +import { assertRecoveryTrace } from "../assertRecoveryTrace.mjs"; +test("caps file reads before parsing and explicitly retains a partial line", async t => { + const dir = await mkdtemp(join(tmpdir(), "admission-bounds-")); + t.after(() => rm(dir, { recursive: true, force: true })); + const path = join(dir, "trace"); + await writeFile(path, '{"id":1}\n' + "x".repeat(10000)); + const capture = await readAdmissionDiagnosticFile(path, "jsonl", 32); + assert.equal(capture.truncated, true); + assert.equal(capture.bytesRead, 33); + assert.deepEqual(capture.data[0], { id: 1 }); + assert(capture.data[1].incompleteRawLine.length <= 32); + const json = await readAdmissionDiagnosticFile(path, "json", 32); + assert.equal(json.truncated, true); + assert.equal(json.data, undefined); +}); +test("post-flush persistence errors prevent success qualification", async () => { + const observer = observeAdmissionWorld( + { registerHandler() {}, events: {} }, + { outputPath: "/dev/null/admission.jsonl" }, + ); + await observer.flush(); + const trace = observer.snapshot(); + assert.match(trace.persistenceError, /ENOTDIR/); + assert.throws(() => assertRecoveryTrace(trace, "run")); +}); +test("observer caps bytes and reports lost entries", async () => { + const world = { registerHandler() {}, events: { create: async () => ({}) } }; + const observer = observeAdmissionWorld(world); + await world.events.create("run", { correlationId: "x".repeat(2097153) }); + assert(observer.snapshot().droppedEntries > 0); + assert.throws(() => assertRecoveryTrace(observer.snapshot(), "run")); +}); +test("local guard rejects WebSocket, HTTP2 and shared transports before execution", () => { + const guard = new URL("../denyAdmissionNetwork.mjs", import.meta.url).href; + execFileSync(process.execPath, [ + "--input-type=module", + "-e", + ` + import assert from "node:assert/strict"; + import { connect } from "node:http2"; + import { denyAdmissionNetwork } from ${JSON.stringify(guard)}; + const count = denyAdmissionNetwork(); + assert.throws(() => new WebSocket("wss://example.invalid"), /Network forbidden/); + assert.throws(() => connect("https://example.invalid"), /Network forbidden/); + assert.throws(() => fetch("https://example.invalid"), /Network forbidden/); + assert.equal(count(), 3); + `, + ]); +}); + +test("finalization waits for a failing close-generated last append and preserves primary errors", async t => { + const { finalizeAdmissionWorld } = await import("../finalizeAdmissionWorld.mjs"); + t.mock.method(console, "error", () => {}); + for (const primary of [undefined, new Error("original operation failure")]) { + let reached, fail; + const lastWriteReached = new Promise(resolve => { + reached = resolve; + }); + const lastWrite = new Promise((_, reject) => { + fail = reject; + }); + const world = { registerHandler() {}, events: {} }; + const observer = observeAdmissionWorld(world, { + outputPath: "controlled-log", + writeLine: async (_path, line) => { + const entry = JSON.parse(line); + if (entry.operation === "close-generated" && entry.stage === "return") { + reached(); + await lastWrite; + } + }, + }); + world.close = () => observer.source("close-generated", async () => {}); + let success = false; + const finish = finalizeAdmissionWorld({ world, observer }, "run", primary).then(value => { + success = true; + return value; + }); + const checked = assert.rejects(finish, error => + primary ? error === primary : error.code === "ERR_ASSERTION", + ); + await lastWriteReached; + assert.equal(success, false); + fail(new Error("injected last append failure")); + await checked; + assert.equal(success, false, "no success qualification or receipt callback can run"); + assert.equal(observer.snapshot().persistenceError, "injected last append failure"); + } +}); + +test("start checkpoint rejects its last append before any ready receipt", async () => { + const { drainAdmissionTrace } = await import("../drainAdmissionTrace.mjs"); + let reached, fail; + const reachedLast = new Promise(resolve => { + reached = resolve; + }); + const last = new Promise((_, reject) => { + fail = reject; + }); + const observer = observeAdmissionWorld( + { registerHandler() {}, events: {} }, + { + outputPath: "controlled-start-log", + writeLine: async (_path, line) => { + if ( + JSON.parse(line).operation === "start-checkpoint" && + JSON.parse(line).stage === "return" + ) { + reached(); + await last; + } + }, + }, + ); + await observer.source("start-checkpoint", async () => {}); + let ready = false; + const checkpoint = drainAdmissionTrace(observer).then(trace => { + ready = true; + return trace; + }); + const rejected = assert.rejects(checkpoint, { code: "ERR_ASSERTION" }); + await reachedLast; + assert.equal(ready, false); + fail(new Error("late start append failure")); + await rejected; + assert.equal(ready, false); +}); diff --git a/scripts/pack-admission-workflow-fixture/captureAdmissionFailure.mjs b/scripts/pack-admission-workflow-fixture/captureAdmissionFailure.mjs index 9de40d411..39289ed00 100644 --- a/scripts/pack-admission-workflow-fixture/captureAdmissionFailure.mjs +++ b/scripts/pack-admission-workflow-fixture/captureAdmissionFailure.mjs @@ -1,11 +1,11 @@ -import { readJson } from "../pack-scheduler-workflow-fixture/readJson.mjs"; +import { readAdmissionDiagnosticFile } from "./readAdmissionDiagnosticFile.mjs"; import { join } from "node:path"; -import { readFile, readdir } from "node:fs/promises"; +import { readdir } from "node:fs/promises"; /** Capture is bounded and best-effort; it must never replace the original failure. */ export async function captureAdmissionFailure(child, effects, error) { const evidence = { error: { name: error.name, message: error.message } }; try { - evidence.saved = await readJson(join(effects, "assertion-evidence.json")); + evidence.saved = await readAdmissionDiagnosticFile(join(effects, "assertion-evidence.json")); } catch (captureError) { evidence.savedUnavailable = captureError.message; } @@ -37,25 +37,17 @@ export async function captureAdmissionFailure(child, effects, error) { } for (const name of ["before-crash.json", "before-crash-world-trace.json", "start-clock.json"]) { try { - evidence[name] = await readJson(join(effects, name)); + evidence[name] = await readAdmissionDiagnosticFile(join(effects, name)); } catch (captureError) { evidence[name] = { unavailable: captureError.message }; } } for (const phase of ["start", "resume"]) { try { - evidence[`${phase}OperationTrace`] = ( - await readFile(join(effects, `${phase}-world-trace.jsonl`), "utf8") - ) - .split("\n") - .filter(Boolean) - .map(line => { - try { - return JSON.parse(line); - } catch { - return { incompleteRawLine: line }; - } - }); + evidence[`${phase}OperationTrace`] = await readAdmissionDiagnosticFile( + join(effects, `${phase}-world-trace.jsonl`), + "jsonl", + ); } catch (captureError) { evidence[`${phase}OperationTrace`] = { unavailable: captureError.message }; } @@ -64,17 +56,26 @@ export async function captureAdmissionFailure(child, effects, error) { try { const directory = join(effects, "journal", kind); const names = (await readdir(directory)).filter(name => name.endsWith(".json")).sort(); + const files = []; + let budget = 4194304; + for (const name of names.slice(0, 2048)) { + if (budget <= 0) break; + try { + const capture = await readAdmissionDiagnosticFile( + join(directory, name), + "json", + Math.min(budget, 65536), + ); + budget -= capture.bytesRead; + files.push({ name, capture }); + } catch (readError) { + files.push({ name, unavailable: readError.message }); + } + } evidence[`raw${kind}`] = { - truncated: names.length > 2048, - files: await Promise.all( - names.slice(0, 2048).map(async name => { - try { - return { name, data: await readJson(join(directory, name)) }; - } catch (readError) { - return { name, unavailable: readError.message }; - } - }), - ), + truncated: files.length < names.length, + byteLimit: 4194304, + files, }; } catch (captureError) { evidence[`raw${kind}`] = { unavailable: captureError.message }; diff --git a/scripts/pack-admission-workflow-fixture/denyAdmissionNetwork.mjs b/scripts/pack-admission-workflow-fixture/denyAdmissionNetwork.mjs new file mode 100644 index 000000000..2ba476a99 --- /dev/null +++ b/scripts/pack-admission-workflow-fixture/denyAdmissionNetwork.mjs @@ -0,0 +1,16 @@ +import http2 from "node:http2"; +import { syncBuiltinESMExports } from "node:module"; +import { denyNetwork } from "../pack-scheduler-workflow-fixture/denyNetwork.mjs"; +/** Extend the unchanged shared guard for this fixture's complete declared transport set. */ +export function denyAdmissionNetwork() { + const sharedAttempts = denyNetwork(); + let attempts = 0; + function deny() { + attempts++; + throw new Error("Network forbidden in pack admission fixture"); + } + globalThis.WebSocket = deny; + http2.connect = deny; + syncBuiltinESMExports(); + return () => sharedAttempts() + attempts; +} diff --git a/scripts/pack-admission-workflow-fixture/drainAdmissionTrace.mjs b/scripts/pack-admission-workflow-fixture/drainAdmissionTrace.mjs new file mode 100644 index 000000000..5718b7bde --- /dev/null +++ b/scripts/pack-admission-workflow-fixture/drainAdmissionTrace.mjs @@ -0,0 +1,12 @@ +import assert from "node:assert/strict"; +/** Qualify the immutable snapshot returned at the observer's fully drained boundary. */ +export async function drainAdmissionTrace(observer) { + const trace = await observer.flush(); + assert.equal(trace.droppedEntries, 0); + assert.equal(trace.persistenceError, undefined); + assert( + !trace.entries.some(entry => entry.stage === "observer-error"), + "observer projection failed", + ); + return trace; +} diff --git a/scripts/pack-admission-workflow-fixture/finalizeAdmissionWorld.mjs b/scripts/pack-admission-workflow-fixture/finalizeAdmissionWorld.mjs new file mode 100644 index 000000000..7af79d5ae --- /dev/null +++ b/scripts/pack-admission-workflow-fixture/finalizeAdmissionWorld.mjs @@ -0,0 +1,24 @@ +import { drainAdmissionTrace } from "./drainAdmissionTrace.mjs"; +import { assertRecoveryTrace } from "./assertRecoveryTrace.mjs"; +/** Close first, drain late observations, then qualify one fresh snapshot. Preserve primary failure. */ +export async function finalizeAdmissionWorld(ctx, runId, originalError) { + let cleanupError; + try { + await ctx.world.close(); + } catch (error) { + cleanupError = error; + } + let trace; + try { + trace = await drainAdmissionTrace(ctx.observer); + } catch (error) { + cleanupError ??= error; + } + if (originalError) { + if (cleanupError) console.error("PACK_ADMISSION_CLEANUP_FAILURE", cleanupError.message); + throw originalError; + } + if (cleanupError) throw cleanupError; + assertRecoveryTrace(trace, runId); + return trace; +} diff --git a/scripts/pack-admission-workflow-fixture/observeAdmissionWorld.mjs b/scripts/pack-admission-workflow-fixture/observeAdmissionWorld.mjs index eddf6e54b..602e99bbb 100644 --- a/scripts/pack-admission-workflow-fixture/observeAdmissionWorld.mjs +++ b/scripts/pack-admission-workflow-fixture/observeAdmissionWorld.mjs @@ -7,6 +7,7 @@ export function observeAdmissionWorld(world, options = {}) { let pending = Promise.resolve(); let persistenceError; let droppedEntries = 0; + let traceBytes = 0; const trace = []; let nextOperation = 0; let nextDelivery = 0; @@ -23,10 +24,17 @@ export function observeAdmissionWorld(world, options = {}) { source: sources.getStore() ?? "external", ...entry, }; + const line = JSON.stringify(item) + "\n"; + const bytes = Buffer.byteLength(line); + if (traceBytes + bytes > 2097152) { + droppedEntries++; + return; + } + traceBytes += bytes; trace.push(item); if (options.outputPath) pending = pending - .then(() => appendFile(options.outputPath, JSON.stringify(item) + "\n")) + .then(() => (options.writeLine ?? appendFile)(options.outputPath, line)) .catch(error => { persistenceError = error.message; }); @@ -138,9 +146,21 @@ export function observeAdmissionWorld(world, options = {}) { sdk: globalThis[Symbol.for("pack.admission.sdk")], sourceHead: process.env.PACK_ADMISSION_SOURCE_HEAD ?? "unbound", }); + const snapshot = () => ({ + entries: structuredClone(trace), + traceBytes, + droppedEntries, + persistenceError, + }); return { - snapshot: () => ({ entries: structuredClone(trace), droppedEntries, persistenceError }), - flush: () => pending, + snapshot, + flush: async () => { + for (;;) { + const draining = pending; + await draining; + if (draining === pending) return snapshot(); + } + }, observeQueue, source: (label, invoke) => sources.run(label, () => observe(label, {}, invoke, () => ({}))), }; diff --git a/scripts/pack-admission-workflow-fixture/probeRecoveryEnqueues.mjs b/scripts/pack-admission-workflow-fixture/probeRecoveryEnqueues.mjs index 70def394f..6d9a90649 100644 --- a/scripts/pack-admission-workflow-fixture/probeRecoveryEnqueues.mjs +++ b/scripts/pack-admission-workflow-fixture/probeRecoveryEnqueues.mjs @@ -6,8 +6,8 @@ import { mkdtemp, cp, rm, writeFile, readFile } from "node:fs/promises"; import { createHash } from "node:crypto"; import { tmpdir } from "node:os"; import { observeAdmissionWorld } from "./observeAdmissionWorld.mjs"; -import { denyNetwork } from "../pack-scheduler-workflow-fixture/denyNetwork.mjs"; -const network = denyNetwork(); +import { denyAdmissionNetwork } from "./denyAdmissionNetwork.mjs"; +const network = denyAdmissionNetwork(); const require = createRequire(import.meta.url); const core = require.resolve("@workflow/core"); const local = createRequire(core).resolve("@workflow/world-local"); diff --git a/scripts/pack-admission-workflow-fixture/probeWaitCreation.mjs b/scripts/pack-admission-workflow-fixture/probeWaitCreation.mjs index 5b16daf5f..59c740e0d 100644 --- a/scripts/pack-admission-workflow-fixture/probeWaitCreation.mjs +++ b/scripts/pack-admission-workflow-fixture/probeWaitCreation.mjs @@ -7,8 +7,8 @@ import { mkdtemp, rm, readFile, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { observeAdmissionWorld } from "./observeAdmissionWorld.mjs"; import { readAdmissionJournal } from "./readAdmissionJournal.mjs"; -import { denyNetwork } from "../pack-scheduler-workflow-fixture/denyNetwork.mjs"; -const network = denyNetwork(); +import { denyAdmissionNetwork } from "./denyAdmissionNetwork.mjs"; +const network = denyAdmissionNetwork(); const require = createRequire(import.meta.url); const local = createRequire(require.resolve("@workflow/core")).resolve("@workflow/world-local"); const fsUrl = pathToFileURL(join(dirname(local), "fs.js")).href; diff --git a/scripts/pack-admission-workflow-fixture/readAdmissionDiagnosticFile.mjs b/scripts/pack-admission-workflow-fixture/readAdmissionDiagnosticFile.mjs new file mode 100644 index 000000000..f4482aaa2 --- /dev/null +++ b/scripts/pack-admission-workflow-fixture/readAdmissionDiagnosticFile.mjs @@ -0,0 +1,40 @@ +import { open } from "node:fs/promises"; +/** Bound allocation and reads before parsing, including partial/growing diagnostic files. */ +export async function readAdmissionDiagnosticFile(path, format = "json", byteLimit = 1048576) { + const file = await open(path, "r"); + try { + const sourceBytes = (await file.stat()).size; + const buffer = Buffer.alloc(byteLimit + 1); + let bytesRead = 0; + while (bytesRead < buffer.length) { + const chunk = await file.read(buffer, bytesRead, buffer.length - bytesRead, bytesRead); + if (!chunk.bytesRead) break; + bytesRead += chunk.bytesRead; + } + const truncated = bytesRead > byteLimit || sourceBytes > byteLimit; + const text = buffer.subarray(0, Math.min(bytesRead, byteLimit)).toString("utf8"); + const metadata = { sourceBytes, bytesRead, byteLimit, truncated }; + if (format === "jsonl") + return { + ...metadata, + data: text + .split("\n") + .filter(Boolean) + .map(line => { + try { + return JSON.parse(line); + } catch { + return { incompleteRawLine: line }; + } + }), + }; + if (truncated) return { ...metadata, rawPrefix: text }; + try { + return { ...metadata, data: JSON.parse(text) }; + } catch (error) { + return { ...metadata, rawPrefix: text, parseError: error.message }; + } + } finally { + await file.close(); + } +} diff --git a/scripts/pack-admission-workflow-fixture/run.mjs b/scripts/pack-admission-workflow-fixture/run.mjs index d845229fc..a7beebdab 100644 --- a/scripts/pack-admission-workflow-fixture/run.mjs +++ b/scripts/pack-admission-workflow-fixture/run.mjs @@ -4,11 +4,11 @@ import { mkdtemp, realpath, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; -import { denyNetwork } from "../pack-scheduler-workflow-fixture/denyNetwork.mjs"; +import { denyAdmissionNetwork } from "./denyAdmissionNetwork.mjs"; import { buildFixture } from "./buildFixture.mjs"; import { runWorker } from "./runWorker.mjs"; import { runScenario } from "./runScenario.mjs"; -const attempts = denyNetwork(); +const attempts = denyAdmissionNetwork(); const here = dirname(fileURLToPath(import.meta.url)); const root = resolve(here, "../.."); process.env.PACK_ADMISSION_SOURCE_HEAD ??= execFileSync("git", ["rev-parse", "HEAD"], { diff --git a/scripts/pack-admission-workflow-fixture/runWorker.mjs b/scripts/pack-admission-workflow-fixture/runWorker.mjs index 4b5ae79b4..e148b4383 100644 --- a/scripts/pack-admission-workflow-fixture/runWorker.mjs +++ b/scripts/pack-admission-workflow-fixture/runWorker.mjs @@ -1,5 +1,6 @@ import assert from "node:assert/strict"; -import { assertRecoveryTrace } from "./assertRecoveryTrace.mjs"; +import { drainAdmissionTrace } from "./drainAdmissionTrace.mjs"; +import { finalizeAdmissionWorld } from "./finalizeAdmissionWorld.mjs"; import { join } from "node:path"; import { writeFile, rename } from "node:fs/promises"; import { createAdmissionWorld } from "./createAdmissionWorld.mjs"; @@ -28,6 +29,8 @@ export async function runWorker(temp, scenario, phase, attempts) { }; process.on("message", onSnapshotRequest); const keepAlive = setInterval(() => {}, 1000); + let failure; + let completed; const idle = () => ctx.counts().deliveries > 0 && ctx.counts().activeDeliveries === 0; const journal = runId => readAdmissionJournal(ctx.world, runId); const results = async runId => readAdmissionResults(await journal(runId), runId); @@ -64,11 +67,8 @@ export async function runWorker(temp, scenario, phase, attempts) { JSON.stringify(await readJson(join(effects, "state.json"))), ); assert.equal(attempts(), 0); - await writeFile( - join(effects, "before-crash-world-trace.json"), - JSON.stringify(ctx.observer.snapshot()), - ); - await ctx.observer.flush(); + const startTrace = await drainAdmissionTrace(ctx.observer); + await writeFile(join(effects, "before-crash-world-trace.json"), JSON.stringify(startTrace)); await writeFile(join(effects, "ready.tmp"), JSON.stringify({ networkAttempts: attempts() })); await rename(join(effects, "ready.tmp"), join(effects, "ready.json")); await new Promise(() => {}); @@ -122,8 +122,7 @@ export async function runWorker(temp, scenario, phase, attempts) { assert.deepEqual(await readEvents(effects), trace); assert.deepEqual(await readJson(join(effects, "state.json")), state); assert.equal(attempts(), 0); - assertRecoveryTrace(ctx.observer.snapshot(), runId); - await writeAdmissionReceipt(effects, { + completed = { scenario, runId, startClock, @@ -133,16 +132,21 @@ export async function runWorker(temp, scenario, phase, attempts) { state, journal: events, networkAttempts: attempts(), - worldTrace: ctx.observer.snapshot(), beforeCrashWorldTrace: evidence.beforeCrashWorldTrace, - }); - console.log( - `PASS ${scenario}: ${value.status}, ${trace.length} read(s), restart and terminal replay`, - ); + }; + } catch (error) { + failure = error; + throw error; } finally { - process.off("message", onSnapshotRequest); - clearInterval(keepAlive); - await ctx.world.close(); - await ctx.observer.flush(); + try { + const worldTrace = await finalizeAdmissionWorld(ctx, completed?.runId, failure); + await writeAdmissionReceipt(effects, { ...completed, worldTrace }); + console.log( + `PASS ${scenario}: ${completed.value.status}, ${completed.trace.length} read(s), restart and terminal replay`, + ); + } finally { + process.off("message", onSnapshotRequest); + clearInterval(keepAlive); + } } }