mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-01 04:36:26 +00:00
fix(workflows): preserve wakes during pause and prevent signal double-delivery
This commit is contained in:
@@ -418,7 +418,10 @@ export interface WorkflowStore {
|
||||
completeStepAttempt(input: CompleteStepAttemptInput): Promise<WorkflowRunSnapshot>;
|
||||
transitionRun(input: TransitionRunInput): Promise<WorkflowRunSnapshot>;
|
||||
|
||||
listSuspendedWaits(kind?: StepWaitSpec["kind"]): Promise<readonly SuspendedWaitRecord[]>;
|
||||
listSuspendedWaits(
|
||||
kind?: StepWaitSpec["kind"],
|
||||
options?: { readonly includePaused?: boolean },
|
||||
): Promise<readonly SuspendedWaitRecord[]>;
|
||||
findExpiredWaits(now: Date): Promise<readonly SuspendedWaitRecord[]>;
|
||||
|
||||
publishWorkflowOutput(input: PublishedWorkflowOutput): Promise<readonly SuspendedWaitRecord[]>;
|
||||
|
||||
@@ -927,7 +927,7 @@ export function createWorkflowEngineImpl(options: WorkflowEngineOptions): Workfl
|
||||
onlyRunId?: string,
|
||||
): Promise<WorkflowRunSnapshot[]> => {
|
||||
const resumed: WorkflowRunSnapshot[] = [];
|
||||
const waits = await store.listSuspendedWaits("integration");
|
||||
const waits = await store.listSuspendedWaits("integration", { includePaused: true });
|
||||
|
||||
for (const entry of waits) {
|
||||
if (onlyRunId !== undefined && entry.runId !== onlyRunId) {
|
||||
@@ -937,7 +937,7 @@ export function createWorkflowEngineImpl(options: WorkflowEngineOptions): Workfl
|
||||
continue;
|
||||
}
|
||||
const run = await store.loadRun(entry.runId);
|
||||
if (run === undefined || run.status !== "waiting") {
|
||||
if (run === undefined || (run.status !== "waiting" && run.status !== "paused")) {
|
||||
continue;
|
||||
}
|
||||
const integration = registry.get(entry.wait.integrationId);
|
||||
@@ -967,7 +967,9 @@ export function createWorkflowEngineImpl(options: WorkflowEngineOptions): Workfl
|
||||
error: message,
|
||||
now: clock.now(),
|
||||
});
|
||||
resumed.push(await finalizeRunTerminal(workflow, run.id, "failed", message));
|
||||
if (run.status !== "paused") {
|
||||
resumed.push(await finalizeRunTerminal(workflow, run.id, "failed", message));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
@@ -980,6 +982,10 @@ export function createWorkflowEngineImpl(options: WorkflowEngineOptions): Workfl
|
||||
output: eventResult.output,
|
||||
now: clock.now(),
|
||||
});
|
||||
if (run.status === "paused") {
|
||||
// Record the completed wait without advancing until resume() is called.
|
||||
continue;
|
||||
}
|
||||
await transitionAfterStepOutcome(workflow, run.id, entry.stepId, eventResult.outcome);
|
||||
resumed.push(await advanceRun(run.id));
|
||||
}
|
||||
@@ -1110,44 +1116,108 @@ export function createWorkflowEngineImpl(options: WorkflowEngineOptions): Workfl
|
||||
await store.cancelRunGates(cancelledRun.id);
|
||||
};
|
||||
|
||||
const resumePendingWait = async (
|
||||
workflow: WorkflowIR,
|
||||
run: WorkflowRunSnapshot,
|
||||
): Promise<WorkflowRunSnapshot | undefined> => {
|
||||
const lastAttempt = run.attempts[run.attempts.length - 1];
|
||||
if (lastAttempt === undefined || lastAttempt.stepId !== run.currentState) {
|
||||
return undefined;
|
||||
}
|
||||
if (lastAttempt.status === "failed") {
|
||||
return finalizeRunTerminal(
|
||||
workflow,
|
||||
run.id,
|
||||
"failed",
|
||||
lastAttempt.error ?? `step "${lastAttempt.stepId}" failed while paused`,
|
||||
);
|
||||
}
|
||||
if (lastAttempt.status === "completed") {
|
||||
await store.transitionRun({
|
||||
runId: run.id,
|
||||
status: "running",
|
||||
now: clock.now(),
|
||||
});
|
||||
await transitionAfterStepOutcome(
|
||||
workflow,
|
||||
run.id,
|
||||
lastAttempt.stepId,
|
||||
lastAttempt.outcome ?? "ok",
|
||||
);
|
||||
return advanceRun(run.id);
|
||||
}
|
||||
if (lastAttempt.status === "waiting" && lastAttempt.wait?.kind === "wait_workflow") {
|
||||
const published = await store.findWorkflowOutput(
|
||||
lastAttempt.wait.workflowId,
|
||||
lastAttempt.wait.outputKey,
|
||||
);
|
||||
if (published !== undefined) {
|
||||
const outcome = extractPublishedOutcome(published.payload);
|
||||
await store.completeStepAttempt({
|
||||
runId: run.id,
|
||||
attemptId: lastAttempt.id,
|
||||
status: "completed",
|
||||
outcome,
|
||||
output: published.payload,
|
||||
now: clock.now(),
|
||||
});
|
||||
await store.transitionRun({
|
||||
runId: run.id,
|
||||
status: "running",
|
||||
now: clock.now(),
|
||||
});
|
||||
await transitionAfterStepOutcome(workflow, run.id, lastAttempt.stepId, outcome);
|
||||
return advanceRun(run.id);
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const startInternal = async (
|
||||
input: StartWorkflowInput,
|
||||
startOptions: { readonly skipSignalDelivery?: boolean } = {},
|
||||
): Promise<WorkflowRunSnapshot> => {
|
||||
const workflow = getWorkflowOrThrow(input.workflowId);
|
||||
const inputs = resolveInputsWithDefaults(workflow, input.inputs);
|
||||
const subjectData = input.subjectData ?? input.event?.subject?.data ?? {};
|
||||
const subjectKey = resolveStartSubjectKey(workflow, input, inputs, subjectData);
|
||||
|
||||
const accepted = await store.acceptRun({
|
||||
workflowId: workflow.id,
|
||||
initialState: workflow.initial,
|
||||
subjectKey,
|
||||
subjectData,
|
||||
onConflict: workflow.subject?.onConflict,
|
||||
inputs,
|
||||
event: input.event,
|
||||
now: clock.now(),
|
||||
});
|
||||
|
||||
if (accepted.action === "ignored") {
|
||||
return accepted.existingRun;
|
||||
}
|
||||
if (accepted.action === "signal") {
|
||||
if (!startOptions.skipSignalDelivery && input.event !== undefined) {
|
||||
const resumed = await deliverEventToSuspendedRuns(input.event, accepted.existingRun.id);
|
||||
return resumed[0] ?? accepted.existingRun;
|
||||
}
|
||||
return (await store.loadRun(accepted.existingRun.id)) ?? accepted.existingRun;
|
||||
}
|
||||
if (accepted.action === "queued") {
|
||||
return accepted.run;
|
||||
}
|
||||
if (accepted.action === "replaced") {
|
||||
await cleanupSupersededRun(accepted.cancelledRun);
|
||||
}
|
||||
|
||||
return advanceRun(accepted.run.id);
|
||||
};
|
||||
|
||||
const engine: WorkflowEngine = {
|
||||
registerWorkflow,
|
||||
|
||||
async start(input: StartWorkflowInput): Promise<WorkflowRunSnapshot> {
|
||||
const workflow = getWorkflowOrThrow(input.workflowId);
|
||||
const inputs = resolveInputsWithDefaults(workflow, input.inputs);
|
||||
const subjectData = input.subjectData ?? input.event?.subject?.data ?? {};
|
||||
const subjectKey = resolveStartSubjectKey(workflow, input, inputs, subjectData);
|
||||
|
||||
const accepted = await store.acceptRun({
|
||||
workflowId: workflow.id,
|
||||
initialState: workflow.initial,
|
||||
subjectKey,
|
||||
subjectData,
|
||||
onConflict: workflow.subject?.onConflict,
|
||||
inputs,
|
||||
event: input.event,
|
||||
now: clock.now(),
|
||||
});
|
||||
|
||||
if (accepted.action === "ignored") {
|
||||
return accepted.existingRun;
|
||||
}
|
||||
if (accepted.action === "signal") {
|
||||
if (input.event !== undefined) {
|
||||
const resumed = await deliverEventToSuspendedRuns(input.event, accepted.existingRun.id);
|
||||
return resumed[0] ?? accepted.existingRun;
|
||||
}
|
||||
return accepted.existingRun;
|
||||
}
|
||||
if (accepted.action === "queued") {
|
||||
return accepted.run;
|
||||
}
|
||||
if (accepted.action === "replaced") {
|
||||
await cleanupSupersededRun(accepted.cancelledRun);
|
||||
}
|
||||
|
||||
return advanceRun(accepted.run.id);
|
||||
return startInternal(input);
|
||||
},
|
||||
|
||||
async ingest(event: NormalizedIntegrationEvent): Promise<IngestResult> {
|
||||
@@ -1158,10 +1228,15 @@ export function createWorkflowEngineImpl(options: WorkflowEngineOptions): Workfl
|
||||
if (!matchesWorkflowTrigger(workflow, event)) {
|
||||
continue;
|
||||
}
|
||||
const run = await engine.start({
|
||||
workflowId: workflow.id,
|
||||
event,
|
||||
});
|
||||
// `deliverEventToSuspendedRuns` already delivered this event to every matching
|
||||
// suspended wait, so `onConflict: "signal"` must not deliver it a second time.
|
||||
const run = await startInternal(
|
||||
{
|
||||
workflowId: workflow.id,
|
||||
event,
|
||||
},
|
||||
{ skipSignalDelivery: true },
|
||||
);
|
||||
matchedRuns.push(run);
|
||||
}
|
||||
|
||||
@@ -1266,6 +1341,9 @@ export function createWorkflowEngineImpl(options: WorkflowEngineOptions): Workfl
|
||||
|
||||
await gates.onGateResolved?.(resolved);
|
||||
|
||||
const runBeforeResolve = await store.loadRun(resolved.runId);
|
||||
const isPaused = runBeforeResolve?.status === "paused";
|
||||
|
||||
const gateState = {
|
||||
choice: resolution.choice,
|
||||
note: resolution.note ?? null,
|
||||
@@ -1279,6 +1357,19 @@ export function createWorkflowEngineImpl(options: WorkflowEngineOptions): Workfl
|
||||
output: gateState,
|
||||
now,
|
||||
});
|
||||
|
||||
if (isPaused) {
|
||||
// Persist gate decision while honoring the pause; resume() will transition and advance.
|
||||
return store.transitionRun({
|
||||
runId: resolved.runId,
|
||||
status: "paused",
|
||||
pausedFromStatus: runBeforeResolve.pausedFromStatus ?? "waiting",
|
||||
currentState: resolved.stepId,
|
||||
lastGate: gateState,
|
||||
now,
|
||||
});
|
||||
}
|
||||
|
||||
await store.transitionRun({
|
||||
runId: resolved.runId,
|
||||
status: "running",
|
||||
@@ -1380,7 +1471,16 @@ export function createWorkflowEngineImpl(options: WorkflowEngineOptions): Workfl
|
||||
throw new Error(`cannot resume run "${runId}" in status "${run.status}"`);
|
||||
}
|
||||
|
||||
const workflow = getWorkflowOrThrow(run.workflowId);
|
||||
const restoreStatus = run.pausedFromStatus ?? "running";
|
||||
|
||||
if (restoreStatus === "waiting") {
|
||||
const resumedFromWait = await resumePendingWait(workflow, run);
|
||||
if (resumedFromWait !== undefined) {
|
||||
return resumedFromWait;
|
||||
}
|
||||
}
|
||||
|
||||
const restored = await store.transitionRun({
|
||||
runId: run.id,
|
||||
status: restoreStatus,
|
||||
@@ -1391,7 +1491,7 @@ export function createWorkflowEngineImpl(options: WorkflowEngineOptions): Workfl
|
||||
return advanceRun(restored.id);
|
||||
}
|
||||
|
||||
// If waiting on a timer/gate/output that expired or arrived while paused, evaluate now.
|
||||
// Re-evaluate any due timers or timeouts that expired while paused.
|
||||
await engine.tick();
|
||||
return (await store.loadRun(runId)) ?? restored;
|
||||
},
|
||||
|
||||
@@ -539,7 +539,11 @@ export function createMemoryWorkflowStore(): WorkflowStore {
|
||||
return cloneRun(run);
|
||||
},
|
||||
|
||||
async listSuspendedWaits(kind?: StepWaitSpec["kind"]): Promise<readonly SuspendedWaitRecord[]> {
|
||||
async listSuspendedWaits(
|
||||
kind?: StepWaitSpec["kind"],
|
||||
options?: { readonly includePaused?: boolean },
|
||||
): Promise<readonly SuspendedWaitRecord[]> {
|
||||
const includePaused = options?.includePaused === true;
|
||||
const result: SuspendedWaitRecord[] = [];
|
||||
for (const attempt of attemptsById.values()) {
|
||||
if (attempt.status !== "waiting" || attempt.wait === undefined) {
|
||||
@@ -549,7 +553,10 @@ export function createMemoryWorkflowStore(): WorkflowStore {
|
||||
continue;
|
||||
}
|
||||
const run = runs.get(attempt.runId);
|
||||
if (run === undefined || run.status !== "waiting") {
|
||||
if (run === undefined) {
|
||||
continue;
|
||||
}
|
||||
if (run.status !== "waiting" && !(includePaused && run.status === "paused")) {
|
||||
continue;
|
||||
}
|
||||
result.push({
|
||||
|
||||
@@ -887,4 +887,204 @@ describe("fake acme integration end-to-end engine contract", () => {
|
||||
grant: { repo: "acme/widget", allowWrite: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("honors pause across wait_workflow, integration waits, and gates, and replays wakes on resume", async () => {
|
||||
const acme = createAcmeIntegration();
|
||||
const clock = createFakeClock();
|
||||
const gates = createFakeGateSink();
|
||||
|
||||
const waitWfIR = roundTripIR(
|
||||
defineWorkflow({
|
||||
id: "pause-wait-wf",
|
||||
on: { "manual.run": {} },
|
||||
initial: "wait_child",
|
||||
steps: {
|
||||
wait_child: step.waitWorkflow({
|
||||
workflow: "child-wf",
|
||||
outputKey: "k1",
|
||||
on: { approved: terminal.done("child_approved") },
|
||||
}),
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const waitCiIR = roundTripIR(
|
||||
defineWorkflow({
|
||||
id: "pause-wait-ci",
|
||||
on: { "manual.run": {} },
|
||||
initial: "wait_ci",
|
||||
steps: {
|
||||
wait_ci: step.integration("acme.wait_ci", {
|
||||
input: { repo: "acme/widget", pr_number: 5, head_sha: "sha_p" },
|
||||
on: { green: terminal.done("ci_green") },
|
||||
}),
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const gateIR = roundTripIR(
|
||||
defineWorkflow({
|
||||
id: "pause-gate",
|
||||
on: { "manual.run": {} },
|
||||
initial: "ask",
|
||||
steps: {
|
||||
ask: step.gate({
|
||||
title: "Approve while paused?",
|
||||
choices: [{ id: "ok", label: "OK" }],
|
||||
on: { ok: "record" },
|
||||
}),
|
||||
record: step.integration("acme.close_issue", {
|
||||
input: {
|
||||
repo: "acme/widget",
|
||||
issue_number: 5,
|
||||
comment: tpl`choice=${ref("gate.choice")} note=${ref("gate.note")}`,
|
||||
},
|
||||
on: { closed: terminal.done("gate_done") },
|
||||
}),
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const engine = createWorkflowEngine({
|
||||
store: createMemoryWorkflowStore(),
|
||||
runner: createFakeAgentRunner(),
|
||||
gates,
|
||||
integrations: [acme.integration],
|
||||
clock,
|
||||
workflows: [waitWfIR, waitCiIR, gateIR],
|
||||
});
|
||||
|
||||
// 1. wait_workflow output arrives while paused -> stays paused, then completes on resume
|
||||
const wfRun = await engine.start({ workflowId: "pause-wait-wf" });
|
||||
await engine.pause(wfRun.id);
|
||||
const pub = await engine.publishOutput({
|
||||
workflowId: "child-wf",
|
||||
outputKey: "k1",
|
||||
payload: { verdict: "approved" },
|
||||
});
|
||||
expect(pub.resumedRuns).toHaveLength(0);
|
||||
expect((await engine.getRun(wfRun.id))?.status).toBe("paused");
|
||||
const wfResumed = await engine.resume(wfRun.id);
|
||||
expect(wfResumed.status).toBe("done");
|
||||
expect(wfResumed.terminalReason).toBe("child_approved");
|
||||
|
||||
// 2. Integration wait event arrives while paused -> stays paused, then completes on resume
|
||||
const ciRun = await engine.start({ workflowId: "pause-wait-ci" });
|
||||
await engine.pause(ciRun.id);
|
||||
const ciIngest = await engine.ingest(
|
||||
makeEvent("acme.ci_status", {
|
||||
repo: "acme/widget",
|
||||
pr_number: 5,
|
||||
head_sha: "sha_p",
|
||||
state: "green",
|
||||
}),
|
||||
);
|
||||
expect(ciIngest.resumedRuns).toHaveLength(0);
|
||||
expect((await engine.getRun(ciRun.id))?.status).toBe("paused");
|
||||
const ciResumed = await engine.resume(ciRun.id);
|
||||
expect(ciResumed.status).toBe("done");
|
||||
expect(ciResumed.terminalReason).toBe("ci_green");
|
||||
|
||||
// 3. Gate resolved while paused -> does NOT advance until resume, then runs downstream with gate context
|
||||
const gateRun = await engine.start({ workflowId: "pause-gate" });
|
||||
await engine.pause(gateRun.id);
|
||||
const gateId = gates.opened[0]!.id;
|
||||
const afterResolve = await engine.resolveGate(gateId, {
|
||||
choice: "ok",
|
||||
note: "approved during pause",
|
||||
actor: "mo",
|
||||
});
|
||||
expect(afterResolve.status).toBe("paused");
|
||||
expect(acme.closedIssues).toHaveLength(0);
|
||||
|
||||
const gateResumed = await engine.resume(gateRun.id);
|
||||
expect(gateResumed.status).toBe("done");
|
||||
expect(gateResumed.terminalReason).toBe("gate_done");
|
||||
expect(acme.closedIssues).toEqual([
|
||||
{
|
||||
repo: "acme/widget",
|
||||
issue_number: 5,
|
||||
comment: "choice=ok note=approved during pause",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("delivers an ingested event at most once per run with onConflict: signal", async () => {
|
||||
const deliveries: string[] = [];
|
||||
const countingIntegration: WorkflowIntegration = {
|
||||
id: "acme",
|
||||
steps: {
|
||||
wait_stage: {
|
||||
inputSchema: z.object({ stage: z.string(), pr: z.number().int() }),
|
||||
outcomes: ["green"],
|
||||
async execute(input) {
|
||||
return {
|
||||
status: "suspended",
|
||||
waitKey: `stage:${String(input["stage"])}#${String(input["pr"])}`,
|
||||
};
|
||||
},
|
||||
async onEvent(event, input) {
|
||||
deliveries.push(String(input["stage"]));
|
||||
if (event.payload["pr"] === input["pr"] && event.payload["state"] === "green") {
|
||||
return { status: "completed", outcome: "green" };
|
||||
}
|
||||
return { status: "still_waiting" };
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const twoStageSignalIR = roundTripIR(
|
||||
defineWorkflow({
|
||||
id: "acme-two-stage-signal",
|
||||
on: { "acme.ci": { connection: "acme-main" } },
|
||||
subject: {
|
||||
key: tpl`pr#${ref("event.pr")}`,
|
||||
onConflict: "signal",
|
||||
},
|
||||
initial: "first",
|
||||
steps: {
|
||||
first: step.integration("acme.wait_stage", {
|
||||
input: { stage: "first", pr: ref("event.pr") },
|
||||
on: { green: "second" },
|
||||
}),
|
||||
second: step.integration("acme.wait_stage", {
|
||||
input: { stage: "second", pr: ref("event.pr") },
|
||||
on: { green: terminal.done("both_stages") },
|
||||
}),
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const engine = createWorkflowEngine({
|
||||
store: createMemoryWorkflowStore(),
|
||||
runner: createFakeAgentRunner(),
|
||||
gates: createFakeGateSink(),
|
||||
integrations: [countingIntegration],
|
||||
clock: createFakeClock(),
|
||||
workflows: [twoStageSignalIR],
|
||||
});
|
||||
|
||||
// Event 1 opens the run and suspends in `first`.
|
||||
const firstIngest = await engine.ingest(makeEvent("acme.ci", { pr: 1, state: "pending" }));
|
||||
const runId = firstIngest.matchedRuns[0]!.id;
|
||||
expect(firstIngest.matchedRuns[0]?.status).toBe("waiting");
|
||||
expect(firstIngest.matchedRuns[0]?.currentState).toBe("first");
|
||||
expect(deliveries).toEqual([]);
|
||||
|
||||
// Event 2 (green) satisfies ONLY `first`, leaving the run waiting on `second`.
|
||||
const secondIngest = await engine.ingest(makeEvent("acme.ci", { pr: 1, state: "green" }));
|
||||
expect(deliveries).toEqual(["first"]);
|
||||
expect(secondIngest.resumedRuns).toHaveLength(1);
|
||||
const midRun = await engine.getRun(runId);
|
||||
expect(midRun?.status).toBe("waiting");
|
||||
expect(midRun?.currentState).toBe("second");
|
||||
|
||||
// Event 3 (green) now satisfies `second` and completes the run.
|
||||
await engine.ingest(makeEvent("acme.ci", { pr: 1, state: "green" }));
|
||||
expect(deliveries).toEqual(["first", "second"]);
|
||||
const doneRun = await engine.getRun(runId);
|
||||
expect(doneRun?.status).toBe("done");
|
||||
expect(doneRun?.terminalReason).toBe("both_stages");
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user