diff --git a/.changeset/38876-subflow-branch-pause-refusal.md b/.changeset/38876-subflow-branch-pause-refusal.md new file mode 100644 index 00000000000..1d55ee8c8f1 --- /dev/null +++ b/.changeset/38876-subflow-branch-pause-refusal.md @@ -0,0 +1,26 @@ +--- +'@objectstack/service-automation': patch +--- + +fix(automation): a branch whose subflow or map child parks, where the run cannot park, fails the run instead of silently dropping work + +Clause-②: no +Metadata-protocol: none + +A run parks at one place, and a resumed run continues from the step that parked, never back at the node whose out-edges led there. The flow schema already refuses the two shapes that lose work for the steps that always pause (`approval`, `approval_revise`, `screen`, `wait`): two of them on concurrent branches of one node, and a branch that pauses before the node's other out-edges. It cannot see a `subflow` or `map`, whose pause is decided by the child flow it names, so those shapes registered and ran, and lost work without an error: + +- **Concurrent.** A node fanning out to an `approval` and to a `subflow` whose child parks on its own approval opened both requests. Decided parent first, the parent completed and the work after the `subflow` never ran. Decided child first, the child's completion consumed the parent's approval pause, the parent completed, and the parent's own request stayed `pending` with a decision answering `RESUME_TARGET_LOST`. +- **Sequential.** A node whose earlier true conditioned edge led into such a `subflow`, beside a later true conditioned edge to another step: the child's request opened and was decided, the run completed, and the later step never ran. + +The engine now fails such a run with a named error on the pauses that actually happen, a child flow's pause included whatever step raises it, and cancels every child run a refused `subflow` / `map` started, so nothing is left parked: + +- `durable pause on concurrent branches: node '' runs its unconditional out-edges together, and more than one of those branches suspended — …`, naming each step that paused and the child flow it called; +- `durable pause before a later branch: node '' took edge '', and node '' (sub-flow '') suspended on that branch while the same traversal still had to take edge '' …`, naming the edges left untaken. + +Each message ends with the fix: chain the pausing steps onto one branch, make the branch that pauses the last one the node takes, or republish the child flow without a step that pauses. The error is a guard refusal, so a `fault` edge does not route it. It is the failed run's `error`; no failure step is logged for it (it is raised by the traversal, not by a node), so the run's step log ends where its branches stopped. Inside a `loop`, `parallel` or `try_catch` body the region error is raised instead, as for any pause there. + +When it fires. A fan-out still answers at its first rejection, as it always has: when that is a pause, the run parks and the pause is stored at once, with the step log ending at the node it parked on; nothing waits on the other branches, so a branch that never settles holds nothing up. At the first branch that pauses too afterwards, or ends in this error or the region error, the run that had answered `paused` is failed, provided it still waits at the pause it answered with: that pause is withdrawn the way a resume claims it (the same node and correlation, inside the same in-process gate a resume takes), its record turns `failed` with the error (said once at `error` in the log), a parent flow waiting on it as a `subflow` fails with it, even when the parent's own pause is still being stored, and the child runs are cancelled. A run a decision has moved on by then, finished or parked again at another step, is left as it is, its new pause and that pause's child run untouched; the lost branch is logged at `error` and its child run cancelled. A decision that arrives while the engine is reading where the run waits is held until that read is done rather than refused, and goes on when the run has moved on. When the store cannot be read or claimed at that moment the run is not failed, and the `error` line says so and how to cancel it. When the two arrive before the node has answered, the run fails at once and nothing is stored. When a fan-out's first rejection is a failure, the run fails as before, and a branch that pauses after it has its child run cancelled. The after-the-answer check lives in the engine's process memory: an engine restarted between storing the pause and the late branch settling keeps the old behaviour, the run parked and the late branch's work lost without a word. + +What still runs as before: a fan-out whose one pausing branch sits beside branches that do not pause; a branch that pauses with nothing left for the node to take after it; a later conditioned edge whose condition does not hold when the earlier branch pauses; a sibling that fails (with any other error) after another branch paused, which is dropped as before. + +Not changed: what an author can write, and every door a flow passes before it runs (`objectstack validate`, the metadata save and publish, `registerFlow`, trigger arming). A request an `approval` opened before the run was refused stays `pending`; deciding it answers `409 RESUME_TARGET_LOST`; the approvals' sweep of requests whose run has ended releases it where the deployment schedules that sweep, and an administrator can recall it sooner. diff --git a/content/docs/automation/flows.mdx b/content/docs/automation/flows.mdx index 3d2e387f90c..46bc7ff3f74 100644 --- a/content/docs/automation/flows.mdx +++ b/content/docs/automation/flows.mdx @@ -1743,8 +1743,10 @@ for that. Write instead: A `parallel` region is no way out: a region body may not hold a pausing step at all. Still accepted: one pausing branch beside branches that run without pausing, an approval after a `parallel` region, and an approval's `approve` / -`reject` edges each to its own step. Not judged here: a `subflow` or `map` on a -concurrent branch, whose pause is decided by the child flow it names. +`reject` edges each to its own step. A `subflow` or `map` on a concurrent +branch is not judged here, because whether it pauses is decided by the child +flow it names; it is met when the run gets there (*A branch whose child flow +parks* below). **A branch that parks the run, taken before another out-edge, is refused.** A node takes its out-edges in a fixed order, each one finished before the @@ -1785,7 +1787,51 @@ an unconditional sibling meant as the otherwise-branch is marked `isDefault: true` instead; keep one `isDefault` edge per node. Still accepted: the last conditioned branch reaching a pausing step, an exclusive `decision`'s branches, an `isDefault` edge beside conditioned ones, and a `fault` edge. A `subflow` or `map` whose child pauses -drops the later edges all the same, and is not judged here either. +is not judged here either; it is met when the run gets there (next). + +**A branch whose child flow parks, where the run cannot park, fails the run.** +The schema cannot see a `subflow` or `map` pause: it is decided by another +flow. The engine meets the same two shapes on the pauses that actually happen, +a child flow that parks included (whatever its pausing step), and fails the +run with a named error instead of keeping one pause and dropping the rest: + +- **`durable pause on concurrent branches`**: two or more of a node's + unconditional branches paused (an approval beside a `subflow` whose child + parks on its own approval, two such calls). The message names the node and + each step that paused, with the child flow it called. +- **`durable pause before a later branch`**: a branch paused while the node + still had an edge to take after it, a later conditioned edge whose condition + holds at that moment, a later `isDefault` edge or an unconditional sibling. + The message names the node, the edge taken, the step that paused and the + edges left untaken. A later edge whose condition does not hold when the + branch pauses is no lost branch: the run parks as before. + +A fan-out still answers at the first branch that pauses, and that pause is +stored at once, as before; nothing waits on the other branches. At the first of +them that pauses too afterwards, or meets one of these errors or the region +error, the run that had answered `paused` is failed then, if it still waits at +that same pause: the pause is withdrawn the way a resume takes it, the record +turns `failed` with the error, and a parent flow waiting on it as a `subflow` +fails with it. A run a decision has moved on by then, finished or parked again +at another step, is left as it is, with its new pause and that pause's child +run untouched; the engine logs the lost branch at `error` and cancels the child +run it parked. A decision that arrives while the engine is reading where the +run waits is held until that read is done, and goes on when the run has moved +on. This check runs in the engine's memory, so an engine restarted +between the pause and the late branch leaves the run parked as before. + +Each child run a refused `subflow` or `map` started is cancelled, so nothing is +left parked under the failed run. A request an `approval` opened before the run +was refused stays `pending`, and deciding it answers `409 RESUME_TARGET_LOST`; +the approvals' sweep of requests whose run has ended releases it where the +deployment schedules that sweep, and an administrator can recall it sooner. A +fan-out with one branch that pauses, and a branch that pauses with nothing left +to take after it, run as before. Inside a `loop`, `parallel` or `try_catch` body +the region error (`durable pause inside a structured region`) is raised +instead, since a region cannot pause on any branch. The prescriptions are the +ones above: chain the steps onto one branch, make the branch that pauses the +last one the node takes, or republish the child flow without a step that +pauses. ### Batch approval — a `map` node, one item at a time diff --git a/packages/plugins/plugin-approvals/src/flow-route.integration.test.ts b/packages/plugins/plugin-approvals/src/flow-route.integration.test.ts index b9652e0ddb6..2ad42cd7a9f 100644 --- a/packages/plugins/plugin-approvals/src/flow-route.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/flow-route.integration.test.ts @@ -51,6 +51,7 @@ import { ObjectQL, ObjectQLPlugin } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; import { AutomationEngine, AutomationServicePlugin, InMemorySuspendedRunStore, installBuiltinNodes } from '@objectstack/service-automation'; import type { EngineQueryOptions } from '@objectstack/spec/data'; +import { defineActionDescriptor } from '@objectstack/spec/automation'; import { ApprovalService } from './approval-service.js'; import { ApprovalsServicePlugin } from './approvals-plugin.js'; import { registerApprovalNode } from './approval-node.js'; @@ -1016,3 +1017,521 @@ describe('[#38875] a branch that parks the run, taken before a sibling, is refus expect((await rows('branches_last')).filter((r) => r.state === 'active')).toHaveLength(1); }); }); + +/** Holds one `load` of a run until the case lets it go: a remote store's round trip, in flight. */ +class HoldableStore extends InMemorySuspendedRunStore { + private held: { runId: string; reached: () => void; open: Promise } | undefined; + holdNextLoad(runId: string): { reached: Promise; release: () => void } { + let reached!: () => void; + let release!: () => void; + const reachedP = new Promise((r) => { reached = r; }); + const open = new Promise((r) => { release = r; }); + this.held = { runId, reached, open }; + return { reached: reachedP, release }; + } + override async load(runId: string) { + const held = this.held; + if (held !== undefined && held.runId === runId) { + this.held = undefined; + held.reached(); + await held.open; + } + return super.load(runId); + } +} + +/** + * [#38876] A branch whose `subflow` / `map` child parks, where the run cannot + * park, fails the run loud at run time — the shapes the two parse rules above + * cannot see, because a `subflow` / `map` pauses only when the child flow it + * names does (ruling D: not judged by type). The engine half is + * `branch-suspension-refusal.ts` in `service-automation`, the region refusal's + * twin: the run is failed with a named refusal and each child run a refused + * node parked is cancelled. + * + * Measured before the change on this rig, through `registerFlow` + execute: + * - CONCURRENT, a fan-out to an approval and a `subflow` whose child parks on + * its own approval: two pending requests, two suspensions. Decided parent + * first, the parent completed on its own decision and the work after the + * `subflow` never ran; decided child first, the child's completion consumed + * the parent's approval pause, the parent completed, and the parent's own + * request stayed `pending` with a decision answering `RESUME_TARGET_LOST`. + * - SEQUENTIAL, an earlier true conditioned edge into that `subflow` beside a + * later true conditioned edge to a synchronous step: the child's request + * opened and decided, the run completed, the later step never ran. + * Both now fail at execute with the refusal, and no run is left parked. + * + * ⚠️ Direction, measured: against a `service-automation` dist built without the + * change every refusal case below is RED (the run answers `paused`); the + * controls are green on both. + */ +describe('[#38876] a branch whose subflow child parks, where the run cannot park, fails the run at run time', () => { + let engine: ObjectQL; + let seq = 0; + let now = Date.parse('2026-12-02T09:00:00.000Z'); + + // ONE engine for the describe (#38976's lesson: a cold boot per case pushed + // the first case past vitest's default on loaded shards). Each case boots its + // own AutomationEngine over a fresh suspended-run store and runs its own flow + // name on its own record, so the cases share only the object tables. + beforeAll(() => boot(), 30_000); + afterAll(async () => { + try { await engine?.destroy(); } catch { /* noop */ } + }); + + async function boot() { + engine = new ObjectQL(); + engine.registerDriver(new SqlDriver({ + client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true, + }), true); + await engine.init(); + for (const def of [sysUser, contract, ...(await packageObjects())]) { + engine.registry.registerObject(def as any, 'approvals-branch-pause-test', 'approvals-branch-pause-test'); + } + await engine.syncSchemas(); + await installDefaultOrganization(engine); + for (const u of USERS) await engine.insert('sys_user', u, { context: SYSTEM } as any); + } + + /** A fresh engine with the built-ins, the approval node and `flows` registered: the door a published flow reaches. */ + const bootEngine = (...flows: any[]) => bootEngineOver(new InMemorySuspendedRunStore(), ...flows); + const bootEngineOver = (store: InMemorySuspendedRunStore, ...flows: any[]) => { + const svc = new ApprovalService({ engine: engine as any, clock: { now: () => new Date(now += 1000) }, logger: silent }); + const errors: string[] = []; + const automation = new AutomationEngine({ ...silent, error: (m: unknown) => { errors.push(String(m)); } }); + installBuiltinNodes(automation, { logger: silent, getService() { throw new Error('none'); } } as any); + automation.setSuspendedRunStore(store); + svc.attachAutomation(automation as any); + registerApprovalNode(automation as any, svc, silent); + // `delay` finishes after 40 ms: it decides which branch of a fan-out settles first. + automation.registerNodeExecutor({ + type: 'delay', + descriptor: defineActionDescriptor({ type: 'delay', version: '1.0.0', name: 'Delay' }), + async execute() { + await new Promise((r) => setTimeout(r, 40)); + return { success: true }; + }, + } as any); + // `gate` waits until the case opens it: it puts a decision inside the window before a late branch settles. + let openGate!: () => void; + const gateOpen = new Promise((r) => { openGate = r; }); + automation.registerNodeExecutor({ + type: 'gate', + descriptor: defineActionDescriptor({ type: 'gate', version: '1.0.0', name: 'Gate' }), + async execute() { + await gateOpen; + return { success: true }; + }, + } as any); + for (const flow of flows) automation.registerFlow(flow.name, flow); + return { svc, automation, openGate, errors }; + }; + const execute = async (automation: AutomationEngine, flow: string) => { + const record = { id: `B_${++seq}`, title: `Contract B${seq}`, amount: 100, route_legal: false, route_finance: false }; + await engine.insert('crm_contract', record, { context: SYSTEM } as any); + const result: any = await automation.execute(flow, { object: 'crm_contract', record, userId: SUBMITTER } as any); + return { record, result }; + }; + const requests = async (recordId: string): Promise => + (await engine.find('sys_approval_request', { where: { record_id: recordId }, context: SYSTEM } satisfies EngineQueryOptions)) as any[]; + const decidePending = async (svc: ApprovalService, recordId: string, nodeId: string, decider: string) => { + const [row] = (await requests(recordId)).filter((r) => r.flow_node_id === nodeId && r.status === 'pending'); + expect(row, `${nodeId} is pending`).toBeDefined(); + const out = await svc.decide(row.id, { decision: 'approve', actorId: decider }, asUser(decider)); + expect([out.finalized, out.resumed], `${decider} approved ${nodeId}`).toEqual([true, true]); + }; + const ranNodes = async (automation: AutomationEngine, runId: string) => + ((await automation.getRun(runId))?.steps ?? []).filter((s) => s.status === 'success').map((s) => s.nodeId); + /** The refused run: failed, every run it started cancelled, nothing left parked. */ + const tick = (ms = 10) => new Promise((r) => setTimeout(r, ms)); + /** + * The refused run: `failed` with `lead`, every run it started no longer parked. + * A fan-out answers at its first pause, so a refusal that arrives after it + * fails the run that already answered `paused`: read its record once it + * leaves `paused` (3 s at most). + */ + const expectRefused = async (automation: AutomationEngine, recordId: string, result: any, lead: string) => { + let run: any = result; + for (let i = 0; i < 300 && run?.status === 'paused'; i++) { + await tick(); + run = await automation.getRun(result.runId); + } + expect(run?.status).toBe('failed'); + expect(run?.error).toContain(lead); + const runs = [...new Set((await requests(recordId)).map((r) => String(r.flow_run_id)))]; + expect(runs.length, 'the requests the run opened before it was refused').toBeGreaterThan(0); + for (const runId of runs) { + let parked = true; + for (let i = 0; i < 300 && parked; i++) { + parked = await automation.hasSuspendedRun(runId); + if (parked) await tick(); + } + expect(parked, `run ${runId} is not left parked`).toBe(false); + } + return { runs, error: String(run.error) }; + }; + + /** One approval, run as the `subflow` / `map` body: the child parks on it. */ + const PARKING_CHILD = { + name: 'branch_parking_child', label: 'Parking child', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + step('c_review', 'C', 'u_legal'), + { id: 'ok', type: 'end', label: 'Ok' }, + { id: 'no', type: 'end', label: 'Rejected' }, + ], + edges: [ + { id: 'c1', source: 'start', target: 'c_review' }, + { id: 'c2', source: 'c_review', target: 'ok', label: 'approve' }, + { id: 'c3', source: 'c_review', target: 'no', label: 'reject' }, + ], + }; + /** A second child that parks on a timer `wait` rather than an approval. */ + const WAITING_CHILD = { + name: 'branch_waiting_child', label: 'Waiting child', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'hold', type: 'wait', label: 'Hold', waitEventConfig: { eventType: 'timer', timerDuration: 'PT1H' } }, + { id: 'ok', type: 'end', label: 'Ok' }, + ], + edges: [ + { id: 'w1', source: 'start', target: 'hold' }, + { id: 'w2', source: 'hold', target: 'ok' }, + ], + }; + const call = (id: string, type: 'subflow' | 'map' = 'subflow', child = PARKING_CHILD.name) => ({ + id, type, label: `Call ${id}`, + config: { flowName: child, ...(type === 'map' ? { collection: [1] } : {}) }, + }); + const assign = (id: string) => ({ id, type: 'assignment', label: id, config: { assignments: { [`ran_${id}`]: 'yes' } } }); + + /** CONCURRENT: `start` fans out to `a_review` and to `sub`, whose child parks; `s_after` follows `sub`. */ + const fanOutToApprovalAndCall = (name: string, type: 'subflow' | 'map' = 'subflow') => ({ + name, label: 'Fan out to a call', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + step('a_review', 'A', 'u_mgr'), + call('sub', type), + assign('s_after'), + { id: 'ok', type: 'end', label: 'Ok' }, + { id: 'no', type: 'end', label: 'Rejected' }, + { id: 'sub_done', type: 'end', label: 'Sub done' }, + ], + edges: [ + { id: 'f1', source: 'start', target: 'a_review' }, + { id: 'f2', source: 'start', target: 'sub' }, + { id: 'f3', source: 'a_review', target: 'ok', label: 'approve' }, + { id: 'f4', source: 'a_review', target: 'no', label: 'reject' }, + { id: 'f5', source: 'sub', target: 's_after' }, + { id: 'f6', source: 's_after', target: 'sub_done' }, + ], + }); + /** CONCURRENT, no pausing node in the parent at all: two calls whose children both park (an approval, a wait). */ + const fanOutToTwoCalls = (name: string) => ({ + name, label: 'Fan out to two calls', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + call('sub_a'), + call('sub_b', 'subflow', WAITING_CHILD.name), + { id: 'a_done', type: 'end', label: 'A done' }, + { id: 'b_done', type: 'end', label: 'B done' }, + ], + edges: [ + { id: 'f1', source: 'start', target: 'sub_a' }, + { id: 'f2', source: 'start', target: 'sub_b' }, + { id: 'f3', source: 'sub_a', target: 'a_done' }, + { id: 'f4', source: 'sub_b', target: 'b_done' }, + ], + }); + /** SEQUENTIAL: `x1` takes `c1` into `sub` (child parks), then `c2` to `s_sync`; `second` is `c2`'s condition. */ + const callBeforeConditionedSibling = (name: string, second = 'true', callFirst = true) => { + const c1 = { id: 'c1', source: 'x1', target: 'sub', condition: 'true' }; + const c2 = { id: 'c2', source: 'x1', target: 's_sync', condition: second }; + return { + name, label: 'Call before a sibling', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + assign('x1'), + call('sub'), + assign('s_sync'), + { id: 'ok', type: 'end', label: 'Ok' }, + { id: 'synced', type: 'end', label: 'Synced' }, + ], + edges: [ + { id: 'c0', source: 'start', target: 'x1' }, + ...(callFirst ? [c1, c2] : [c2, c1]), + { id: 'c3', source: 'sub', target: 'ok' }, + { id: 'c4', source: 's_sync', target: 'synced' }, + ], + }; + }; + /** SEQUENTIAL: `x1`'s `isDefault` edge into `sub` (no condition held), beside an unconditional edge to `s_sync`. */ + const defaultCallBesideUnconditional = (name: string) => ({ + name, label: 'Default call', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + assign('x1'), + call('sub'), + assign('s_sync'), + { id: 'ok', type: 'end', label: 'Ok' }, + { id: 'synced', type: 'end', label: 'Synced' }, + ], + edges: [ + { id: 'c0', source: 'start', target: 'x1' }, + { id: 'c1', source: 'x1', target: 'sub', isDefault: true }, + { id: 'c2', source: 'x1', target: 's_sync' }, + { id: 'c3', source: 'sub', target: 'ok' }, + { id: 'c4', source: 's_sync', target: 'synced' }, + ], + }); + + /** + * The reviewer's M1: `start` fans out to `a_review` and to `x1`, whose + * earlier true edge enters `sub` (child parks) before a later true edge to + * `s_sync`. `slowApproval` puts a `delay` in front of `a_review`, so the + * refusal on `x1`'s side arrives first. + */ + const approvalBesideSequential = (name: string, slowApproval = false) => ({ + name, label: 'Approval beside a sequential call', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + ...(slowApproval ? [{ id: 'slow', type: 'delay', label: 'Slow' }] : []), + step('a_review', 'A', 'u_mgr'), + assign('x1'), + call('sub'), + assign('s_sync'), + { id: 'ok', type: 'end', label: 'Ok' }, + { id: 'no', type: 'end', label: 'Rejected' }, + { id: 'sub_done', type: 'end', label: 'Sub done' }, + { id: 'synced', type: 'end', label: 'Synced' }, + ], + edges: [ + ...(slowApproval + ? [{ id: 'm0', source: 'start', target: 'slow' }, { id: 'm1', source: 'slow', target: 'a_review' }] + : [{ id: 'm1', source: 'start', target: 'a_review' }]), + { id: 'm2', source: 'start', target: 'x1' }, + { id: 'c1', source: 'x1', target: 'sub', condition: 'true' }, + { id: 'c2', source: 'x1', target: 's_sync', condition: 'true' }, + { id: 'm3', source: 'a_review', target: 'ok', label: 'approve' }, + { id: 'm4', source: 'a_review', target: 'no', label: 'reject' }, + { id: 'm5', source: 'sub', target: 'sub_done' }, + { id: 'm6', source: 's_sync', target: 'synced' }, + ], + }); + + /** + * The approval rig's re-park and resume-wins shapes: `start` fans out to + * `a_review` and, behind a `gate`, to a late branch whose child parks on a + * timer. `twoStages` puts `b_review` after `a_review`'s approval, so the + * decision on `a_review` parks the run again; `sequential` makes the late + * branch the refused sequential shape (`x1`'s true edge into the call before + * a true edge to `s_sync`) instead of a call that simply suspends. + */ + const approvalBesideGatedLate = (name: string, twoStages: boolean, sequential: boolean) => ({ + name, label: 'Approval beside a gated late branch', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + step('a_review', 'A', 'u_mgr'), + ...(twoStages ? [step('b_review', 'B', 'u_fin')] : []), + { id: 'late', type: 'gate', label: 'Late' }, + ...(sequential ? [assign('x1'), assign('s_sync'), { id: 'synced', type: 'end', label: 'Synced' }] : []), + call('sub', 'subflow', WAITING_CHILD.name), + { id: 'ok', type: 'end', label: 'Ok' }, + { id: 'no', type: 'end', label: 'Rejected' }, + { id: 'sub_done', type: 'end', label: 'Sub done' }, + ], + edges: [ + { id: 'r1', source: 'start', target: 'a_review' }, + ...(twoStages + ? [ + { id: 'r2', source: 'a_review', target: 'b_review', label: 'approve' }, + { id: 'r3', source: 'b_review', target: 'ok', label: 'approve' }, + { id: 'r4', source: 'b_review', target: 'no', label: 'reject' }, + ] + : [{ id: 'r2', source: 'a_review', target: 'ok', label: 'approve' }]), + { id: 'r5', source: 'a_review', target: 'no', label: 'reject' }, + { id: 'l0', source: 'start', target: 'late' }, + ...(sequential + ? [ + { id: 'l1', source: 'late', target: 'x1' }, + { id: 'c1', source: 'x1', target: 'sub', condition: 'true' }, + { id: 'c2', source: 'x1', target: 's_sync', condition: 'true' }, + { id: 'c4', source: 's_sync', target: 'synced' }, + ] + : [{ id: 'l1', source: 'late', target: 'sub' }]), + { id: 'c3', source: 'sub', target: 'sub_done' }, + ], + }); + /** Poll until no run is parked (3 s at most); answers what is still parked. */ + const parkedAfterSettling = async (automation: AutomationEngine) => { + let parked = await automation.listSuspendedRunsDurable(); + for (let i = 0; i < 300 && parked.length > 0; i++) { + await tick(); + parked = await automation.listSuspendedRunsDurable(); + } + return parked; + }; + const LEFT = 'had already left that pause'; + + const CONCURRENT = "durable pause on concurrent branches: node 'start' runs its unconditional out-edges together"; + + it('CONCURRENT, an approval beside a subflow whose child parks: the run fails naming both, and the child run is cancelled', async () => { + const { automation } = bootEngine(PARKING_CHILD, fanOutToApprovalAndCall('branch_fan_out_subflow')); + const { record, result } = await execute(automation, 'branch_fan_out_subflow'); + const { error } = await expectRefused(automation, record.id, result, CONCURRENT); + expect(error).toContain("node 'a_review'"); + expect(error).toContain("node 'sub' (sub-flow 'branch_parking_child')"); + const [child] = (await requests(record.id)).filter((r) => r.flow_node_id === 'c_review'); + expect((await automation.getRun(child.flow_run_id))?.status, 'the child run the subflow parked').toBe('cancelled'); + }); + + it('CONCURRENT, the same through a `map`: refused the same way, the item run cancelled', async () => { + const { automation } = bootEngine(PARKING_CHILD, fanOutToApprovalAndCall('branch_fan_out_map', 'map')); + const { record, result } = await execute(automation, 'branch_fan_out_map'); + const { error } = await expectRefused(automation, record.id, result, CONCURRENT); + expect(error).toContain("node 'sub' (sub-flow 'branch_parking_child')"); + const [child] = (await requests(record.id)).filter((r) => r.flow_node_id === 'c_review'); + expect((await automation.getRun(child.flow_run_id))?.status, 'the item run the map parked').toBe('cancelled'); + }); + + it('CONCURRENT, two subflows whose children both park: refused naming both, both child runs cancelled', async () => { + const { automation } = bootEngine(PARKING_CHILD, WAITING_CHILD, fanOutToTwoCalls('branch_fan_out_two_calls')); + const { record, result } = await execute(automation, 'branch_fan_out_two_calls'); + const { runs: [approvalChild], error } = await expectRefused(automation, record.id, result, CONCURRENT); + expect(error).toContain("(sub-flow 'branch_parking_child')"); + expect(error).toContain("(sub-flow 'branch_waiting_child')"); + expect((await automation.getRun(approvalChild))?.status, 'the approval child run').toBe('cancelled'); + let parked = (await automation.listSuspendedRunsDurable()).map((r) => r.flowName); + for (let i = 0; i < 300 && parked.length > 0; i++) { + await tick(); + parked = (await automation.listSuspendedRunsDurable()).map((r) => r.flowName); + } + expect(parked, 'neither child is left parked, the timer child included').toEqual([]); + }); + + it('SEQUENTIAL, a true conditioned edge into a subflow whose child parks, before a later true sibling: refused, the sibling named', async () => { + const { automation } = bootEngine(PARKING_CHILD, callBeforeConditionedSibling('branch_sequential_conditioned')); + const { record, result } = await execute(automation, 'branch_sequential_conditioned'); + const { runs: [child], error } = await expectRefused(automation, record.id, result, "durable pause before a later branch: node 'x1' took edge 'c1'"); + expect(error).toContain("node 'sub' (sub-flow 'branch_parking_child') suspended on that branch"); + expect(error).toContain("edge 'c2' ('x1' → 's_sync')"); + expect((await automation.getRun(child))?.status).toBe('cancelled'); + }); + + it('SEQUENTIAL, an isDefault edge into that subflow beside an unconditional sibling: refused, the sibling named', async () => { + const { automation } = bootEngine(PARKING_CHILD, defaultCallBesideUnconditional('branch_sequential_default')); + const { record, result } = await execute(automation, 'branch_sequential_default'); + const { error } = await expectRefused(automation, record.id, result, "durable pause before a later branch: node 'x1' took edge 'c1'"); + expect(error).toContain("edge 'c2' ('x1' → 's_sync')"); + }); + + it.each([ + ['the approval parks first, the refusal arrives after and fails the parked run', false], + ['the refusal arrives first and fails the run at execute; the approval opens after', true], + ] as const)('M1, an approval beside `x1`, whose true edge enters the subflow before a later true edge (%s)', async (_order, slowApproval) => { + const name = `branch_m1_${slowApproval ? 'refusal_first' : 'approval_first'}`; + const { automation } = bootEngine(PARKING_CHILD, approvalBesideSequential(name, slowApproval)); + const { record, result } = await execute(automation, name); + expect(result.status, 'either the run parked on the approval or it failed at once').toMatch(/^(paused|failed)$/); + if (slowApproval) expect(result.status).toBe('failed'); + else expect(result.status).toBe('paused'); + await tick(80); // the slow approval opens its request in the refusal-first order + const { runs, error } = await expectRefused(automation, record.id, result, "durable pause before a later branch: node 'x1' took edge 'c1'"); + expect(error).toContain("edge 'c2' ('x1' → 's_sync')"); + const [child] = (await requests(record.id)).filter((r) => r.flow_node_id === 'c_review'); + expect((await automation.getRun(child.flow_run_id))?.status, 'the child run the subflow parked').toBe('cancelled'); + for (const runId of runs) { + expect(await ranNodes(automation, runId), 'the later edge never ran').not.toContain('s_sync'); + } + }); + + it.each([ + ['a late branch that suspends', false], + ['a late branch refused as sequential', true], + ] as const)('RE-PARK: `a_review` approved parks the run at `b_review`, then %s: the run is left there, and `b_review` decides it', async (_late, sequential) => { + const name = `branch_repark_${sequential ? 'sequential' : 'concurrent'}`; + const { svc, automation, openGate, errors } = bootEngine(WAITING_CHILD, approvalBesideGatedLate(name, true, sequential)); + const { record, result } = await execute(automation, name); + expect(result.status).toBe('paused'); + await decidePending(svc, record.id, 'a_review', 'u_mgr'); + expect((await automation.getRun(result.runId))?.status, 'parked again, at b_review').toBe('paused'); + openGate(); + for (let i = 0; i < 300 && !errors.some((m) => m.includes(LEFT)); i++) await tick(); + expect(errors.filter((m) => m.includes(result.runId)), 'judged once, and the run left alone').toEqual([expect.stringContaining(LEFT)]); + expect((await automation.getRun(result.runId))?.status).toBe('paused'); + await decidePending(svc, record.id, 'b_review', 'u_fin'); + expect((await automation.getRun(result.runId))?.status, 'b_review\'s decision ends the run').toBe('completed'); + expect(await parkedAfterSettling(automation), 'the late timer child is not left parked').toEqual([]); + }); + + it('`b_review` decided while the late watch\'s read of the run is out: the decision waits for it instead of being refused, and resumes the run', async () => { + const store = new HoldableStore(); + const { svc, automation, openGate, errors } = bootEngineOver(store, WAITING_CHILD, approvalBesideGatedLate('branch_decided_in_window', true, false)); + const { record, result } = await execute(automation, 'branch_decided_in_window'); + expect(result.status).toBe('paused'); + await decidePending(svc, record.id, 'a_review', 'u_mgr'); + expect((await automation.getRun(result.runId))?.status, 'parked again, at b_review').toBe('paused'); + const read = store.holdNextLoad(result.runId); + openGate(); + await read.reached; // the watch holds the run's gate, its read of the run is out + const [row] = (await requests(record.id)).filter((r) => r.flow_node_id === 'b_review' && r.status === 'pending'); + expect(row, 'b_review is pending').toBeDefined(); + const deciding = svc.decide(row.id, { decision: 'approve', actorId: 'u_fin' }, asUser('u_fin')); + await tick(50); + read.release(); + const out = await deciding; + expect([out.finalized, out.resumed], 'recorded AND resumed').toEqual([true, true]); + for (let i = 0; i < 300 && !errors.some((m) => m.includes(LEFT)); i++) await tick(); + expect(errors.filter((m) => m.includes(result.runId)), 'judged once, and the run left alone').toEqual([expect.stringContaining(LEFT)]); + expect((await automation.getRun(result.runId))?.status, 'b_review\'s decision ended the run').toBe('completed'); + expect(await parkedAfterSettling(automation), 'the late timer child is not left parked').toEqual([]); + }); + + it('RESUME WINS: `a_review` approved ends the run before the late branch suspends; it stays completed, the late child cancelled', async () => { + const { svc, automation, openGate, errors } = bootEngine(WAITING_CHILD, approvalBesideGatedLate('branch_resume_wins', false, false)); + const { record, result } = await execute(automation, 'branch_resume_wins'); + expect(result.status).toBe('paused'); + await decidePending(svc, record.id, 'a_review', 'u_mgr'); + expect((await automation.getRun(result.runId))?.status).toBe('completed'); + openGate(); + for (let i = 0; i < 300 && !errors.some((m) => m.includes(LEFT)); i++) await tick(); + expect(errors.filter((m) => m.includes(result.runId))).toEqual([ + expect.stringContaining('the child run that branch parked was cancelled'), + ]); + expect((await automation.getRun(result.runId))?.status).toBe('completed'); + expect(await parkedAfterSettling(automation)).toEqual([]); + }); + + it('CONTROL: one pausing branch (the subflow) beside a synchronous one parks, and the child\'s decision runs the work after it', async () => { + const flow: any = fanOutToApprovalAndCall('branch_fan_out_one_pause'); + flow.nodes = flow.nodes.map((n: any) => (n.id === 'a_review' ? assign('a_review') : n)); + flow.edges = flow.edges.filter((e: any) => e.id !== 'f4').map((e: any) => (e.id === 'f3' ? { id: 'f3', source: 'a_review', target: 'ok' } : e)); + const { svc, automation } = bootEngine(PARKING_CHILD, flow); + const { record, result } = await execute(automation, 'branch_fan_out_one_pause'); + expect(result.status).toBe('paused'); + await decidePending(svc, record.id, 'c_review', 'u_legal'); + const parentRunId = result.runId; + expect((await automation.getRun(parentRunId))?.status).toBe('completed'); + expect(await ranNodes(automation, parentRunId)).toEqual(expect.arrayContaining(['a_review', 'sub', 's_after'])); + }); + + it('CONTROL: the subflow branch taken LAST parks after its sibling has run, and the decision ends the run', async () => { + const { svc, automation } = bootEngine(PARKING_CHILD, callBeforeConditionedSibling('branch_sequential_last', 'true', false)); + const { record, result } = await execute(automation, 'branch_sequential_last'); + expect(result.status).toBe('paused'); + await decidePending(svc, record.id, 'c_review', 'u_legal'); + const parentRunId = result.runId; + expect((await automation.getRun(parentRunId))?.status).toBe('completed'); + expect(await ranNodes(automation, parentRunId)).toEqual(expect.arrayContaining(['x1', 's_sync', 'sub'])); + }); + + it('CONTROL: a later sibling whose condition does not hold at the pause is no lost branch: the run parks and completes', async () => { + const { svc, automation } = bootEngine(PARKING_CHILD, callBeforeConditionedSibling('branch_sequential_untaken', 'false')); + const { record, result } = await execute(automation, 'branch_sequential_untaken'); + expect(result.status).toBe('paused'); + await decidePending(svc, record.id, 'c_review', 'u_legal'); + const parentRunId = result.runId; + expect((await automation.getRun(parentRunId))?.status).toBe('completed'); + expect(await ranNodes(automation, parentRunId)).not.toContain('s_sync'); + }); +}); diff --git a/packages/services/service-automation/src/branch-suspension-refusal.test.ts b/packages/services/service-automation/src/branch-suspension-refusal.test.ts new file mode 100644 index 00000000000..5dcff28a163 --- /dev/null +++ b/packages/services/service-automation/src/branch-suspension-refusal.test.ts @@ -0,0 +1,734 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [#38876] The branch refusal (`branch-suspension-refusal.ts`): a branch whose +// `subflow` / `map` child parks, where the run cannot park, fails the run. +// The approval-backed reproductions live with the approval service +// (`plugin-approvals/src/flow-route.integration.test.ts`); these pin the +// engine half on timer children: +// +// - the refusal's fields, what it leaves in the suspended-run store, and the +// boundary with the region refusal (inside a region body the region rule +// names the fault, and a `try_catch` around it does not turn the run green); +// - WHEN it fires: a fan-out answers at its first suspension and stores it as +// base does (the step log it parks with ends at the node it parked on, and +// a sibling that never settles keeps nothing waiting); a branch that then +// suspends too, or ends in a branch or region refusal, fails the PARKED run +// afterwards — in either arrival order the run ends `failed` and nothing is +// left parked. + +import { describe, it, expect, vi } from 'vitest'; +import { defineActionDescriptor } from '@objectstack/spec/automation'; +import { AutomationEngine } from './engine.js'; +import { InMemorySuspendedRunStore } from './suspended-run-store.js'; +import { + registerSubflowNode, + registerMapNode, + registerLoopNode, + registerParallelNode, + registerTryCatchNode, + registerWaitNode, + registerLogicNodes, +} from './builtin/index.js'; +import { FlowBranchSuspensionRefusalError, isBranchSuspensionRefusal } from './branch-suspension-refusal.js'; +import { isGuardRefusal } from './guard-refusal.js'; +import { withLoaderSetFromPull } from './loader-set.test-support.js'; + +function rig(options: { store?: S | null } = {}) { + const logger: any = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; + logger.child = () => logger; + const engine = withLoaderSetFromPull(new AutomationEngine(logger)); + const store = (options.store === undefined ? new InMemorySuspendedRunStore() : options.store) as S; + if (store) engine.setSuspendedRunStore(store); + const ctx = { logger, getService: () => undefined } as any; + for (const register of [ + registerSubflowNode, registerMapNode, registerLoopNode, registerParallelNode, + registerTryCatchNode, registerWaitNode, registerLogicNodes, + ]) { + (register as (e: AutomationEngine, c: unknown) => void)(engine, ctx); + } + // `delay` finishes after 40 ms: it decides which branch of a fan-out settles first. + engine.registerNodeExecutor({ + type: 'delay', + descriptor: defineActionDescriptor({ type: 'delay', version: '1.0.0', name: 'Delay' }), + async execute() { + await new Promise((r) => setTimeout(r, 40)); + return { success: true }; + }, + } as any); + // `stuck` may pause and never settles. + let release!: () => void; + const never = new Promise((r) => { release = r; }); + engine.registerNodeExecutor({ + type: 'stuck', + descriptor: defineActionDescriptor({ type: 'stuck', version: '1.0.0', name: 'Stuck', supportsPause: true, resumeAuthority: 'any' }), + async execute() { + await never; + return { success: true }; + }, + } as any); + // `gate` waits until the test opens the gate its `config.key` names: it puts + // a decision, a store write or a second late branch inside a window. + const gates = new Map; release: () => void }>(); + const gateOf = (key: string) => { + let gate = gates.get(key); + if (!gate) { + let release!: () => void; + const open = new Promise((r) => { release = r; }); + gate = { open, release }; + gates.set(key, gate); + } + return gate; + }; + engine.registerNodeExecutor({ + type: 'gate', + descriptor: defineActionDescriptor({ type: 'gate', version: '1.0.0', name: 'Gate' }), + async execute(n: { config?: { key?: string } }) { + await gateOf(String(n.config?.key)).open; + return { success: true }; + }, + } as any); + const open = (key: string) => gateOf(key).release(); + const errorLines = (): string[] => logger.error.mock.calls.map((c: unknown[]) => String(c[0])); + return { engine, logger, store, release, open, errorLines }; +} + +type Node = Record; +const START: Node = { id: 'start', type: 'start', label: 'Start' }; +const node = (id: string, type = 'assignment', config: Record = {}): Node => ({ id, type, label: id, config }); +const end = (id: string): Node => ({ id, type: 'end', label: id }); +const call = (id: string, flowName = 'deal_hold', type: 'subflow' | 'map' = 'subflow'): Node => + node(id, type, { flowName, ...(type === 'map' ? { collection: [1] } : {}) }); +const edge = (id: string, source: string, target: string, extra: Record = {}) => ({ id, source, target, ...extra }); +const WAIT = (id: string): Node => ({ id, type: 'wait', label: id, waitEventConfig: { eventType: 'timer', timerDuration: 'PT1H' } }); + +/** A child that parks on a one-hour timer. */ +const HOLD = { + name: 'deal_hold', label: 'Hold', type: 'autolaunched', + nodes: [START, WAIT('hold'), end('done')], + edges: [edge('h1', 'start', 'hold'), edge('h2', 'hold', 'done')], +}; +/** A child that CAN park (its wait is reachable) and does not: the gate's condition is false, so it ends. */ +const MAYBE = { + name: 'deal_maybe', label: 'Maybe', type: 'autolaunched', + nodes: [START, node('gate'), WAIT('hold'), end('done')], + edges: [ + edge('m0', 'start', 'gate'), + edge('m1', 'gate', 'hold', { condition: 'false' }), + edge('m2', 'gate', 'done', { isDefault: true }), + edge('m3', 'hold', 'done'), + ], +}; + +const flow = (name: string, nodes: Node[], edges: Array>) => ({ name, label: name, type: 'autolaunched', nodes, edges }); + +/** `start` fans out to two calls whose child parks. */ +const FAN_OUT = flow('deal_fan_out', [START, call('sub_a'), call('sub_b', 'deal_hold', 'map'), end('a_done'), end('b_done')], [ + edge('f1', 'start', 'sub_a'), edge('f2', 'start', 'sub_b'), edge('f3', 'sub_a', 'a_done'), edge('f4', 'sub_b', 'b_done'), +]); + +/** `x1` takes `c1` into a call whose child parks, then `c2` to `s_sync`. */ +const SEQUENTIAL = flow('deal_sequential', [START, node('x1'), call('sub'), node('s_sync'), end('ok'), end('synced')], [ + edge('c0', 'start', 'x1'), + edge('c1', 'x1', 'sub', { condition: 'true' }), + edge('c2', 'x1', 's_sync', { condition: 'true' }), + edge('c3', 'sub', 'ok'), edge('c4', 's_sync', 'synced'), +]); + +/** + * The reviewer's N2: `start` fans out to an outer `wait` and to `x1`, whose + * sequential shape is refused. `slowFirst` puts a `delay` in front of the + * outer wait, so the refusal arrives first (N2b). + */ +const outerWaitBesideSequential = (name: string, slowFirst = false) => flow(name, [ + START, ...(slowFirst ? [node('slow', 'delay')] : []), WAIT('outer_hold'), node('x1'), call('sub'), node('s_sync'), + end('outer_done'), end('ok'), end('synced'), +], [ + ...(slowFirst ? [edge('o0', 'start', 'slow'), edge('o1', 'slow', 'outer_hold')] : [edge('o1', 'start', 'outer_hold')]), + edge('o2', 'start', 'x1'), + edge('c1', 'x1', 'sub', { condition: 'true' }), + edge('c2', 'x1', 's_sync', { condition: 'true' }), + edge('o3', 'outer_hold', 'outer_done'), edge('c3', 'sub', 'ok'), edge('c4', 's_sync', 'synced'), +]); + +/** The reviewer's N1: an outer `wait` beside `x1`, which itself fans out to two calls whose child parks. */ +const outerWaitBesideFanOut = (name: string) => flow(name, [ + START, WAIT('outer_hold'), node('x1'), call('sub_a'), call('sub_b'), end('outer_done'), end('a_done'), end('b_done'), +], [ + edge('o1', 'start', 'outer_hold'), edge('o2', 'start', 'x1'), + edge('f1', 'x1', 'sub_a'), edge('f2', 'x1', 'sub_b'), + edge('o3', 'outer_hold', 'outer_done'), edge('f3', 'sub_a', 'a_done'), edge('f4', 'sub_b', 'b_done'), +]); + +/** An outer `wait` beside a `loop` whose body calls a child that parks: the region refusal arrives late. */ +const outerWaitBesideRegion = (name: string) => flow(name, [ + START, WAIT('outer_hold'), + node('box', 'loop', { collection: [1], iteratorVariable: 'item', body: { nodes: [call('step')], edges: [] } }), + end('outer_done'), end('box_done'), +], [ + edge('o1', 'start', 'outer_hold'), edge('o2', 'start', 'box'), + edge('o3', 'outer_hold', 'outer_done'), edge('o4', 'box', 'box_done'), +]); + +/** The same fan-out as the body of a container node `box`. */ +const inRegion = (kind: 'parallel' | 'try_catch') => { + const body = { + nodes: [node('entry'), call('sub_a'), call('sub_b'), node('exit')], + edges: [edge('r1', 'entry', 'sub_a'), edge('r2', 'entry', 'sub_b'), edge('r3', 'sub_a', 'exit'), edge('r4', 'sub_b', 'exit')], + }; + const box = kind === 'parallel' + ? node('box', 'parallel', { branches: [{ name: 'a', ...body }, { name: 'b', nodes: [node('noop')], edges: [] }] }) + : node('box', 'try_catch', { try: body, catch: { nodes: [node('noop')], edges: [] } }); + return flow(`deal_region_${kind}`, [START, box, end('done')], [edge('e1', 'start', 'box'), edge('e2', 'box', 'done')]); +}; + +const tick = (ms = 10) => new Promise((r) => setTimeout(r, ms)); + +/** The run as it ends: the answer itself when it failed, else its record once it leaves `paused` (3 s at most). */ +async function settled(engine: AutomationEngine, answer: any): Promise<{ status?: string; error?: string; steps?: any[] }> { + if (answer.status !== 'paused') return answer; + for (let i = 0; i < 300; i++) { + const run: any = await engine.getRun(answer.runId); + if (run && run.status !== 'paused') return run; + await tick(); + } + return (await engine.getRun(answer.runId)) as any; +} + +/** The suspended-run store once nothing more is being parked or cancelled (3 s at most). */ +async function parkedAfterSettling(engine: AutomationEngine): Promise { + let parked: unknown[] = []; + for (let i = 0; i < 300; i++) { + parked = await engine.listSuspendedRunsDurable(); + if (parked.length === 0) return parked; + await tick(); + } + return parked; +} + +describe('[#38876] the branch refusal on the engine', () => { + it('CONCURRENT: two calls whose child parks fail the run with the named refusal, and both children are cancelled', async () => { + const { engine } = rig(); + engine.registerFlow(HOLD.name, HOLD); + engine.registerFlow(FAN_OUT.name, FAN_OUT); + const run = await settled(engine, await engine.execute(FAN_OUT.name, {} as any)); + expect(run.status).toBe('failed'); + expect(run.error).toContain("durable pause on concurrent branches: node 'start'"); + expect(run.error).toContain("node 'sub_a' (sub-flow 'deal_hold')"); + expect(run.error).toContain("node 'sub_b' (sub-flow 'deal_hold')"); + expect(await parkedAfterSettling(engine), 'nothing is left parked').toEqual([]); + }); + + it('SEQUENTIAL: a call whose child parks before a later true sibling fails the run at once, and the sibling never runs', async () => { + const { engine } = rig(); + engine.registerFlow(HOLD.name, HOLD); + engine.registerFlow(SEQUENTIAL.name, SEQUENTIAL); + const result: any = await engine.execute(SEQUENTIAL.name, {} as any); + expect(result).toMatchObject({ success: false, status: 'failed' }); + expect(result.error).toContain("durable pause before a later branch: node 'x1' took edge 'c1' ('x1' → 'sub')"); + expect(result.error).toContain("edge 'c2' ('x1' → 's_sync')"); + expect(await parkedAfterSettling(engine)).toEqual([]); + }); + + it('the refusal carries its facts as fields, is recognised by its symbol, and is a guard refusal (no fault edge routes it)', () => { + const refusal = new FlowBranchSuspensionRefusalError({ + shape: 'sequential', + forkNodeId: 'x1', + suspendedEdge: { id: 'c1', target: 'sub' }, + suspended: [{ nodeId: 'sub', subFlowName: 'deal_hold' }], + untakenEdges: [{ id: 'c2', target: 's_sync' }], + }); + expect(isBranchSuspensionRefusal(refusal)).toBe(true); + expect(isBranchSuspensionRefusal(new Error(refusal.message)), 'never by its text').toBe(false); + expect(isGuardRefusal(refusal)).toBe(true); + expect(refusal).toMatchObject({ shape: 'sequential', forkNodeId: 'x1', untakenEdges: [{ id: 'c2', target: 's_sync' }] }); + }); + + it.each(['parallel', 'try_catch'] as const)('inside a `%s` body the region refusal names the fault, and the run fails rather than turning green', async (kind) => { + const { engine } = rig(); + engine.registerFlow(HOLD.name, HOLD); + const caller = inRegion(kind); + engine.registerFlow(caller.name, caller); + const result: any = await engine.execute(caller.name, {} as any); + expect(result.success, 'a try_catch around it does not contain it').toBe(false); + expect(result.error).toContain("durable pause inside a structured region: node 'sub_a' (sub-flow 'deal_hold')"); + expect(await parkedAfterSettling(engine), 'both children are cancelled, the later one as it parks').toEqual([]); + }); + + it('N2, refusal LATE: an outer wait parks first, then the sequential refusal beside it fails the parked run; s_sync never runs', async () => { + const { engine, logger } = rig(); + engine.registerFlow(HOLD.name, HOLD); + const shape = outerWaitBesideSequential('deal_n2'); + engine.registerFlow(shape.name, shape); + const answer: any = await engine.execute(shape.name, {} as any); + expect(answer.status, 'the outer wait parked first and the run answered as base does').toBe('paused'); + const run = await settled(engine, answer); + expect(run.status).toBe('failed'); + expect(run.error).toContain("durable pause before a later branch: node 'x1' took edge 'c1'"); + expect(run.steps?.map((s: any) => s.nodeId), 'the failed record keeps the log it parked with').not.toContain('s_sync'); + expect(await engine.resume(answer.runId, {} as any), 'nothing is left to resume').toMatchObject({ success: false }); + expect(await parkedAfterSettling(engine)).toEqual([]); + expect(logger.error.mock.calls.map((c: unknown[]) => String(c[0])).some((m: string) => m.includes(`run '${answer.runId}' was answered 'paused'`))) + .toBe(true); + }); + + it('a parent waiting on that run as a `subflow` fails with it when it fails late', async () => { + const { engine } = rig(); + engine.registerFlow(HOLD.name, HOLD); + const child = outerWaitBesideSequential('deal_n2_child'); + engine.registerFlow(child.name, child); + const parent = flow('deal_n2_parent', [START, call('run_child', 'deal_n2_child'), end('done')], [ + edge('p1', 'start', 'run_child'), edge('p2', 'run_child', 'done'), + ]); + engine.registerFlow(parent.name, parent); + const answer: any = await engine.execute(parent.name, {} as any); + expect(answer.status, 'the child parked on its outer wait, and the parent on the child').toBe('paused'); + const run = await settled(engine, answer); + expect(run.status).toBe('failed'); + expect(run.error).toContain('subflow descendant failed: durable pause before a later branch'); + expect(await parkedAfterSettling(engine)).toEqual([]); + }); + + it('N2b, refusal FIRST: the same flow with the outer branch slower fails at execute, and the late outer wait leaves nothing parked', async () => { + const { engine } = rig(); + engine.registerFlow(HOLD.name, HOLD); + const shape = outerWaitBesideSequential('deal_n2b', true); + engine.registerFlow(shape.name, shape); + const result: any = await engine.execute(shape.name, {} as any); + expect(result).toMatchObject({ success: false, status: 'failed' }); + expect(result.error).toContain("durable pause before a later branch: node 'x1' took edge 'c1'"); + await tick(80); + expect(await parkedAfterSettling(engine)).toEqual([]); + }); + + it('N1: an outer wait beside a fan-out to two calls whose child parks: the run ends failed, both children cancelled', async () => { + const { engine } = rig(); + engine.registerFlow(HOLD.name, HOLD); + const shape = outerWaitBesideFanOut('deal_n1'); + engine.registerFlow(shape.name, shape); + const run = await settled(engine, await engine.execute(shape.name, {} as any)); + expect(run.status).toBe('failed'); + expect(run.error).toContain('durable pause on concurrent branches'); + expect(await parkedAfterSettling(engine)).toEqual([]); + }); + + it('a REGION refusal collected after a sibling parked fails the parked run too', async () => { + const { engine } = rig(); + engine.registerFlow(HOLD.name, HOLD); + const shape = outerWaitBesideRegion('deal_region_late'); + engine.registerFlow(shape.name, shape); + const run = await settled(engine, await engine.execute(shape.name, {} as any)); + expect(run.status).toBe('failed'); + expect(run.error).toContain('durable pause inside a structured region'); + expect(await parkedAfterSettling(engine)).toEqual([]); + }); + + it('P1b: a wait beside a call whose child can pause and does not parks with the step log ending at the wait, as on base', async () => { + const { engine, store } = rig(); + engine.registerFlow(MAYBE.name, MAYBE); + const shape = flow('deal_p1b', [START, node('fork'), WAIT('hold'), call('sub', 'deal_maybe'), node('s_after'), end('h_done'), end('s_done')], [ + edge('e0', 'start', 'fork'), edge('e1', 'fork', 'hold'), edge('e2', 'fork', 'sub'), + edge('e3', 'hold', 'h_done'), edge('e4', 'sub', 's_after'), edge('e5', 's_after', 's_done'), + ]); + engine.registerFlow(shape.name, shape); + const answer: any = await engine.execute(shape.name, {} as any); + expect(answer.status).toBe('paused'); + const stored = await store.load(answer.runId); + expect(stored?.steps.map((s) => s.nodeId)).toEqual(['start', 'fork', 'hold']); + await tick(50); + expect((await engine.getRun(answer.runId))?.status, 'a sibling that does not pause leaves the run parked').toBe('paused'); + }); + + it('N4: one branch parks while a sibling that may pause never settles: the run answers paused and the pause is stored', async () => { + const { engine, store, release } = rig(); + const shape = flow('deal_n4', [START, WAIT('hold'), node('stall', 'stuck'), end('h_done'), end('s_done')], [ + edge('e1', 'start', 'hold'), edge('e2', 'start', 'stall'), edge('e3', 'hold', 'h_done'), edge('e4', 'stall', 's_done'), + ]); + engine.registerFlow(shape.name, shape); + const answer: any = await Promise.race([engine.execute(shape.name, {} as any), tick(2000).then(() => ({ status: 'NO ANSWER' }))]); + expect(answer.status).toBe('paused'); + expect((await store.load(answer.runId))?.nodeId).toBe('hold'); + release(); + }); + + it('CONTROL: one call whose child parks, beside a synchronous branch, parks the run as before', async () => { + const { engine } = rig(); + engine.registerFlow(HOLD.name, HOLD); + const oneCall = flow('deal_one_call', [START, call('sub_a'), node('s_sync'), end('a_done'), end('s_done')], [ + edge('f1', 'start', 'sub_a'), edge('f2', 'start', 's_sync'), edge('f3', 'sub_a', 'a_done'), edge('f4', 's_sync', 's_done'), + ]); + engine.registerFlow(oneCall.name, oneCall); + const result: any = await engine.execute(oneCall.name, {} as any); + expect(result.status).toBe('paused'); + await tick(50); + const run = await engine.getRun(result.runId); + expect(run?.status, 'nothing fails it afterwards').toBe('paused'); + expect(run?.steps.filter((s) => s.status === 'success').map((s) => s.nodeId), 'both branches ran') + .toEqual(expect.arrayContaining(['s_sync', 'sub_a'])); + }); +}); + +/** Poll `probe` until it answers truthy (3 s at most); answers its last value. */ +async function until(probe: () => T | Promise): Promise { + let value = await probe(); + for (let i = 0; i < 300 && !value; i++) { + await tick(); + value = await probe(); + } + return value; +} + +/** A gate in front of the late branch: `late` → `x1`, whose true edge enters `sub` (child parks) before a true edge to `s_sync`. */ +const LATE_SEQUENTIAL = { nodes: [node('late', 'gate', { key: 'late' }), node('x1'), call('sub'), node('s_sync'), end('ok'), end('synced')], edges: [ + edge('l0', 'start', 'late'), edge('l1', 'late', 'x1'), + edge('c1', 'x1', 'sub', { condition: 'true' }), edge('c2', 'x1', 's_sync', { condition: 'true' }), + edge('c3', 'sub', 'ok'), edge('c4', 's_sync', 'synced'), +] }; +/** A gate in front of a call whose child parks: the late branch SUSPENDS. */ +const lateCall = (id: string, key = id) => ({ nodes: [node(`g_${id}`, 'gate', { key }), call(id), end(`${id}_done`)], edges: [ + edge(`g0_${id}`, 'start', `g_${id}`), edge(`g1_${id}`, `g_${id}`, id), edge(`g2_${id}`, id, `${id}_done`), +] }); + +/** + * `start` fans out to `outer_hold` (a wait) and to `late`. What follows the + * outer wait is `then`: nothing (the run ends on its decision), a second wait, + * or a call whose child parks. + */ +const besideLate = (name: string, late: { nodes: Node[]; edges: Array> }, then: 'end' | 'wait' | 'call' | 'gate' = 'end') => { + const second = then === 'wait' ? [WAIT('hold2')] : then === 'call' ? [call('hold2')] : then === 'gate' ? [node('hold2', 'gate', { key: 'resume' })] : []; + return flow(name, [START, WAIT('outer_hold'), ...second, end('outer_done'), ...late.nodes], [ + edge('o1', 'start', 'outer_hold'), + ...(second.length > 0 ? [edge('o2', 'outer_hold', 'hold2'), edge('o3', 'hold2', 'outer_done')] : [edge('o2', 'outer_hold', 'outer_done')]), + ...late.edges, + ]); +}; + +describe('[#38876] the late failure binds to the pause it watched (race arms, pinned with gates)', () => { + const LEFT = 'had already left that pause'; + + it.each(['wait', 'call'] as const)('RE-PARK on a %s: a decision moved the run to its next pause before the late refusal; the run stays parked there, intact, and completes', async (then) => { + const { engine, store, open, errorLines } = rig(); + engine.registerFlow(HOLD.name, HOLD); + const shape = besideLate(`deal_repark_${then}`, LATE_SEQUENTIAL, then); + engine.registerFlow(shape.name, shape); + const answer: any = await engine.execute(shape.name, {} as any); + expect(answer.status).toBe('paused'); + expect(await engine.resume(answer.runId, {} as any), 'the decision on the outer wait').toMatchObject({ success: true, status: 'paused' }); + const reparked = await store.load(answer.runId); + expect(reparked?.nodeId).toBe('hold2'); + const secondChild = then === 'call' ? reparked?.correlation?.slice('subflow:'.length) : undefined; + open('late'); + expect(await until(() => errorLines().some((m) => m.includes(LEFT))), 'the late refusal was judged and said').toBe(true); + expect((await store.load(answer.runId))?.nodeId, 'left parked at its new pause').toBe('hold2'); + expect((await engine.getRun(answer.runId))?.status).toBe('paused'); + if (secondChild !== undefined) expect(await store.load(secondChild), 'the child its new pause parked is untouched').not.toBeNull(); + expect(errorLines().some((m) => m.includes('is now FAILED')), 'nothing was failed').toBe(false); + expect(await engine.resume(answer.runId, {} as any), 'its next decision ends it').toMatchObject({ success: true }); + expect((await engine.getRun(answer.runId))?.status).toBe('completed'); + }); + + it('RESUME WINS: the run completes on its decision before the late branch suspends; it stays completed and the late child is cancelled', async () => { + const { engine, open, errorLines } = rig(); + engine.registerFlow(HOLD.name, HOLD); + const shape = besideLate('deal_resume_wins', lateCall('sub_late')); + engine.registerFlow(shape.name, shape); + const answer: any = await engine.execute(shape.name, {} as any); + expect(answer.status).toBe('paused'); + expect(await engine.resume(answer.runId, {} as any)).toMatchObject({ success: true }); + expect((await engine.getRun(answer.runId))?.status).toBe('completed'); + open('sub_late'); + expect(await until(() => errorLines().some((m) => m.includes(LEFT) && m.includes('the child run that branch parked was cancelled')))).toBe(true); + expect((await engine.getRun(answer.runId))?.status).toBe('completed'); + expect(await parkedAfterSettling(engine), 'the late child is not left parked').toEqual([]); + }); + + it('TWO late branches: the first fails the run, the second\'s child is cancelled as it parks; one failed record, one line', async () => { + const { engine, open, errorLines } = rig(); + engine.registerFlow(HOLD.name, HOLD); + const a = lateCall('sub_a'), b = lateCall('sub_b'); + const shape = besideLate('deal_two_late', { nodes: [...a.nodes, ...b.nodes], edges: [...a.edges, ...b.edges] }); + engine.registerFlow(shape.name, shape); + const answer: any = await engine.execute(shape.name, {} as any); + open('sub_a'); + const run = await settled(engine, answer); + expect(run.status).toBe('failed'); + expect(run.error).toContain("node 'outer_hold', node 'sub_a' (sub-flow 'deal_hold')"); + open('sub_b'); + expect(await parkedAfterSettling(engine), 'both late children are cancelled').toEqual([]); + expect(errorLines().filter((m) => m.includes('is now FAILED')), 'said once').toHaveLength(1); + expect((await engine.getRun(answer.runId))?.status).toBe('failed'); + }); + + it('the FIRST late suspension acts: a sibling that never settles does not hold the failure back', async () => { + const { engine, open, release } = rig(); + engine.registerFlow(HOLD.name, HOLD); + const a = lateCall('sub_a'); + const shape = besideLate('deal_first_acts', { + nodes: [...a.nodes, node('stall', 'stuck'), end('s_done')], + edges: [...a.edges, edge('s0', 'start', 'stall'), edge('s1', 'stall', 's_done')], + }); + engine.registerFlow(shape.name, shape); + const answer: any = await engine.execute(shape.name, {} as any); + expect(answer.status).toBe('paused'); + open('sub_a'); + const run = await settled(engine, answer); + expect(run.status, 'failed while `stall` is still running').toBe('failed'); + expect(await parkedAfterSettling(engine)).toEqual([]); + release(); + }); + + it('NO STORE (no claim to take): while a resume of the run holds the in-process gate the watch waits; let go at the same pause, it fails the run', async () => { + const { engine, open, errorLines } = rig({ store: null }); + engine.registerFlow(HOLD.name, HOLD); + const shape = besideLate('deal_no_store_gate', lateCall('sub_late')); + engine.registerFlow(shape.name, shape); + const answer: any = await engine.execute(shape.name, {} as any); + expect(answer.status).toBe('paused'); + const gate = (engine as any).resuming as { add(id: string): unknown; delete(id: string): unknown }; + gate.add(answer.runId); // what `resume` holds from its first line to its last + open('sub_late'); + await tick(80); + expect((await engine.getRun(answer.runId))?.status, 'the watch did not act inside the gate').toBe('paused'); + expect(errorLines().some((m) => m.includes('is now FAILED'))).toBe(false); + gate.delete(answer.runId); // that resume was refused before it consumed anything + const run = await settled(engine, answer); + expect(run.status, 'then it judged the pause it watched, still in place').toBe('failed'); + expect(await engine.hasSuspendedRun(answer.runId)).toBe(false); + }); + + it('NO STORE: a resume in flight when the late branch suspends finishes the run, and the watch leaves it alone', async () => { + const { engine, open, errorLines } = rig({ store: null }); + engine.registerFlow(HOLD.name, HOLD); + const shape = besideLate('deal_no_store', lateCall('sub_late'), 'gate'); + engine.registerFlow(shape.name, shape); + const answer: any = await engine.execute(shape.name, {} as any); + expect(answer.status).toBe('paused'); + const resumed = engine.resume(answer.runId, {} as any); // runs into `hold2`, a gate: the resume is in flight + await tick(20); + open('sub_late'); // the late branch suspends while the resume holds the run + await tick(50); + expect(errorLines().some((m) => m.includes('is now FAILED')), 'the watch did not act inside the resume').toBe(false); + open('resume'); + expect(await resumed).toMatchObject({ success: true }); + expect(await until(() => errorLines().some((m) => m.includes(LEFT)))).toBe(true); + expect((await engine.getRun(answer.runId))?.status).toBe('completed'); + expect(errorLines().some((m) => m.includes('is now FAILED')), 'never failed').toBe(false); + }); + + it('a child\'s bubble that meets the watch while its read of the run is out WAITS for it: the run has moved on, so the bubble completes it', async () => { + const store = new HoldableStore(); + const { engine, open, errorLines } = rig({ store }); + engine.registerFlow(HOLD.name, HOLD); + const shape = besideLate('deal_bubble_in_window', lateCall('sub_late'), 'call'); + engine.registerFlow(shape.name, shape); + const answer: any = await engine.execute(shape.name, {} as any); + expect(answer.status).toBe('paused'); + expect(await engine.resume(answer.runId, {} as any), 'the decision on the outer wait').toMatchObject({ success: true, status: 'paused' }); + const reparked = await store.load(answer.runId); + expect(reparked?.nodeId, 'parked again, on the call `hold2`').toBe('hold2'); + const child = String(reparked?.correlation).slice('subflow:'.length); + const read = store.holdNextLoad(answer.runId); + open('sub_late'); + await read.reached; // the watch holds the run's gate, its read of the run is out + const decided = engine.resume(child, {} as any); // the child completes and bubbles to the parent + await tick(50); + read.release(); + expect(await decided).toMatchObject({ success: true }); + expect(await until(() => errorLines().some((m) => m.includes(LEFT))), 'the watch left the run alone').toBe(true); + const run = await settled(engine, answer); + expect(run.status, 'the bubble was not refused: the parent completed on its completed child').toBe('completed'); + expect(errorLines().some((m) => m.includes('is now FAILED'))).toBe(false); + expect(await parkedAfterSettling(engine), 'nothing parked, the late child cancelled').toEqual([]); + }); + + it('a resume that meets the watch while its read is out, at the pause the watch watched, is refused once the watch claims it: one actor', async () => { + const store = new HoldableStore(); + const { engine, open } = rig({ store }); + engine.registerFlow(HOLD.name, HOLD); + const shape = besideLate('deal_resume_in_window', lateCall('sub_late')); + engine.registerFlow(shape.name, shape); + const answer: any = await engine.execute(shape.name, {} as any); + expect(answer.status).toBe('paused'); + const read = store.holdNextLoad(answer.runId); + open('sub_late'); + await read.reached; + const resumed = (engine as any).resumeInternal(answer.runId, {}, false); // past the public door's own read + await tick(50); + read.release(); + expect(await resumed).toMatchObject({ success: false, code: 'RESUME_IN_PROGRESS' }); + const run = await settled(engine, answer); + expect(run.status, 'the watch failed it where it waited').toBe('failed'); + expect(await parkedAfterSettling(engine)).toEqual([]); + }); +}); + +/** Holds one `load` of a run until the case lets it go: a remote store's round trip, in flight. */ +class HoldableStore extends InMemorySuspendedRunStore { + private held: { runId: string; reached: () => void; open: Promise } | undefined; + holdNextLoad(runId: string): { reached: Promise; release: () => void } { + let reached!: () => void; + let release!: () => void; + const reachedP = new Promise((r) => { reached = r; }); + const open = new Promise((r) => { release = r; }); + this.held = { runId, reached, open }; + return { reached: reachedP, release }; + } + override async load(runId: string) { + const held = this.held; + if (held !== undefined && held.runId === runId) { + this.held = undefined; + held.reached(); + await held.open; + } + return super.load(runId); + } +} + +/** Delays a store's round trips: `save` for the runs `slowSave` picks, every `load` by `loadMs`. */ +class LatentStore extends InMemorySuspendedRunStore { + onSaveStart: (run: { runId: string; flowName: string }) => void = () => {}; + constructor(private readonly delays: { save: (flowName: string) => number; load: () => number }) { + super(); + } + override async save(run: Parameters[0]): Promise { + this.onSaveStart(run); + await new Promise((r) => setTimeout(r, this.delays.save(run.flowName))); + return super.save(run); + } + override async load(runId: string) { + await new Promise((r) => setTimeout(r, this.delays.load())); + return super.load(runId); + } +} + +describe('[#38876] a parent whose own pause is not stored yet when the late failure reaches it', () => { + const CHILD = besideLate('deal_late_child', LATE_SEQUENTIAL); + const callerOf = (name: string, callee: string) => flow(name, [START, call('run_child', callee), end('done')], [ + edge('p1', 'start', 'run_child'), edge('p2', 'run_child', 'done'), + ]); + + it.each([ + ['the parent', ['deal_late_parent'], 'deal_late_parent'], + ['the grandparent (the walk fails the parent, the grandparent fails itself)', ['deal_late_mid', 'deal_late_top'], 'deal_late_top'], + ] as const)('save 60 ms, read 2 ms, the late refusal released as %s starts saving: every ancestor ends failed, nothing parked', async (_who, chain, slow) => { + const store = new LatentStore({ save: (flowName) => (flowName === slow ? 60 : 0), load: () => 2 }); + const { engine, open } = rig({ store }); + engine.registerFlow(HOLD.name, HOLD); + engine.registerFlow(CHILD.name, CHILD); + let callee = CHILD.name; + for (const name of chain) { + engine.registerFlow(name, callerOf(name, callee)); + callee = name; + } + store.onSaveStart = (run) => { if (run.flowName === slow) open('late'); }; + const answer: any = await engine.execute(slow, {} as any); + expect(answer.status, 'the whole chain parked first').toBe('paused'); + const run = await settled(engine, answer); + expect(run.status).toBe('failed'); + expect(run.error).toContain('subflow descendant failed: durable pause before a later branch'); + expect(await parkedAfterSettling(engine), 'no ancestor left parked on a failed child').toEqual([]); + }); + + it('ObjectStore-shaped latency (save = two round trips, load = one, each 1-6 ms), 40 trials: no parent is left parked', async () => { + let seed = 38876; + const roundTrip = () => { seed = (seed * 1103515245 + 12345) % 2147483648; return 1 + (seed % 6); }; + const SHORT = besideLate('deal_short_child', { + nodes: [node('x1'), call('sub'), node('s_sync'), end('ok'), end('synced')], + edges: [ + edge('l0', 'start', 'x1'), + edge('c1', 'x1', 'sub', { condition: 'true' }), edge('c2', 'x1', 's_sync', { condition: 'true' }), + edge('c3', 'sub', 'ok'), edge('c4', 's_sync', 'synced'), + ], + }); + const stranded: string[] = []; + for (let trial = 0; trial < 40; trial++) { + const store = new LatentStore({ save: () => roundTrip() + roundTrip(), load: roundTrip }); + const { engine } = rig({ store }); + engine.registerFlow(HOLD.name, HOLD); + engine.registerFlow(SHORT.name, SHORT); + engine.registerFlow('deal_short_parent', callerOf('deal_short_parent', SHORT.name)); + const run = await settled(engine, await engine.execute('deal_short_parent', {} as any)); + if (run.status !== 'failed' || (await parkedAfterSettling(engine)).length > 0) stranded.push(`trial ${trial}: ${run.status}`); + } + expect(stranded).toEqual([]); + }, 30_000); +}); + +describe('[#38876] the watch says what happened, and nothing it does escapes it', () => { + it('a history sink whose terminal write throws: the run is still failed, the late child cancelled, the write failure said', async () => { + class ThrowingSink extends InMemorySuspendedRunStore { + override recordTerminal(record: Parameters[0]): Promise { + if (record.status === 'failed') throw new Error('history sink down'); + return super.recordTerminal(record); + } + } + const { engine, open, errorLines } = rig({ store: new ThrowingSink() }); + engine.registerFlow(HOLD.name, HOLD); + const shape = besideLate('deal_sink_throws', lateCall('sub_late')); + engine.registerFlow(shape.name, shape); + const answer: any = await engine.execute(shape.name, {} as any); + expect(answer.status).toBe('paused'); + open('sub_late'); + expect(await until(() => errorLines().some((m) => m.includes('is now FAILED')))).toBe(true); + expect(errorLines().some((m) => m.includes("recording its terminal 'failed' history threw"))).toBe(true); + expect(await engine.hasSuspendedRun(answer.runId), 'the pause is consumed').toBe(false); + expect(await parkedAfterSettling(engine), 'the late child is cancelled').toEqual([]); + }); + + it('a history sink that throws on the PARENT\'s terminal write only, the parent read by the walk: the late child is still cancelled, and both are said', async () => { + class ParentSinkThrows extends InMemorySuspendedRunStore { + override recordTerminal(record: Parameters[0]): Promise { + if (record.status === 'failed' && record.flowName === 'deal_sink_parent') throw new Error('history sink down'); + return super.recordTerminal(record); + } + } + const { engine, open, errorLines } = rig({ store: new ParentSinkThrows() }); + engine.registerFlow(HOLD.name, HOLD); + const child = besideLate('deal_sink_child', lateCall('sub_late')); + engine.registerFlow(child.name, child); + engine.registerFlow('deal_sink_parent', flow('deal_sink_parent', [START, call('run_child', child.name), end('done')], [ + edge('p1', 'start', 'run_child'), edge('p2', 'run_child', 'done'), + ])); + const answer: any = await engine.execute('deal_sink_parent', {} as any); + expect(answer.status).toBe('paused'); + open('sub_late'); + expect(await until(() => errorLines().some((m) => m.includes('is now FAILED')))).toBe(true); + expect(errorLines().some((m) => m.includes('failing a run that waits on it as a subflow threw'))).toBe(true); + let parked: string[] = []; + for (let i = 0; i < 300; i++) { + parked = (await engine.listSuspendedRunsDurable()).map((r) => r.flowName).filter((n) => n === HOLD.name); + if (parked.length === 0) break; + await tick(); + } + expect(parked, 'the child run the late branch parked is cancelled').toEqual([]); + }); + + it.each(['load', 'claim'] as const)('a store whose %s fails after the pause: the line says the run may still read paused, never that a decision moved it', async (fault) => { + class FaultyStore extends InMemorySuspendedRunStore { + failing = false; + override async load(runId: string) { + if (this.failing && fault === 'load') throw new Error('store down'); + return super.load(runId); + } + override async claimSuspension(...a: Parameters) { + if (this.failing && fault === 'claim') throw new Error('store down'); + return super.claimSuspension(...a); + } + } + const store = new FaultyStore(); + const { engine, open, errorLines } = rig({ store }); + engine.registerFlow(HOLD.name, HOLD); + const shape = besideLate(`deal_store_${fault}`, LATE_SEQUENTIAL); + engine.registerFlow(shape.name, shape); + const answer: any = await engine.execute(shape.name, {} as any); + expect(answer.status).toBe('paused'); + store.failing = true; + open('late'); + const said = fault === 'load' ? 'the suspended-run store could not be read' : 'did not answer the claim'; + expect(await until(() => errorLines().some((m) => m.includes(`run '${answer.runId}' had to be failed`) && m.includes(said)))).toBe(true); + await tick(50); + expect(errorLines().some((m) => m.includes(`run '${answer.runId}' parked at node`)), 'no line says a decision moved it').toBe(false); + expect(errorLines().some((m) => m.includes('is now FAILED'))).toBe(false); + store.failing = false; + expect((await store.load(answer.runId))?.nodeId, 'still parked where it was').toBe('outer_hold'); + }); +}); diff --git a/packages/services/service-automation/src/branch-suspension-refusal.ts b/packages/services/service-automation/src/branch-suspension-refusal.ts new file mode 100644 index 00000000000..499fe282f1e --- /dev/null +++ b/packages/services/service-automation/src/branch-suspension-refusal.ts @@ -0,0 +1,451 @@ +import type { FlowEdgeParsed, FlowNodeParsed, FlowParsed } from '@objectstack/spec/automation'; +import type { DagTraversalHost } from './dag-traversal.js'; +import { isSuspendSignal, type FlowSuspendSignal } from './engine-signals.js'; +import { markGuardRefusal } from './guard-refusal.js'; +import { cancelParkedChild } from './parked-child-cancel.js'; +import { isRegionSuspensionRefusal } from './region-suspension-refusal.js'; + +/** + * The "a branch's durable pause would drop another branch" refusal (#38876), + * the run-time door of the limit #3267 ruled 禁: a durable pause where the run + * cannot park. + * + * ## The limit this makes loud + * + * A run parks at ONE place, and a resumed run continues from the node that + * parked, never back at the node whose out-edges led there. `traverseNext` + * takes a node's out-edges in a fixed order within one traversal: its + * conditioned edges one after another, then its `isDefault` edges when no + * condition held, then its unconditional edges together (`Promise.all`). Two + * shapes therefore lose work when a branch pauses: + * + * - **concurrent** — two or more of the unconditional branches pause. Only + * one suspension can be kept; the other branch's continuation was dropped + * without a word. Measured on the real engine and approval service (a + * fan-out to an `approval` and a `subflow` whose child parks on its own + * approval): both requests opened, each decision resumed a run, and the + * work after the `subflow` never ran — or, decided child-first, the child's + * completion consumed the parent's approval pause, the run completed, and + * the parent's own request was left `pending` with a decision that answers + * `RESUME_TARGET_LOST`. + * - **sequential** — an earlier branch pauses while the same traversal still + * has an edge to take after it (a later conditioned edge whose condition + * holds, a later `isDefault` edge, an unconditional sibling). Measured: an + * earlier true conditioned edge into a `subflow` whose child parks, beside a + * later true conditioned edge to a synchronous step: the child's request + * opened and decided, the run completed, and the later sibling never ran. + * + * The flow parse refuses both shapes for the node types that ALWAYS pause + * (`flow-concurrent-pause.ts` in `packages/spec`). It cannot see a `subflow` + * or `map`: whether those pause is decided by the child flow record their + * `config.flowName` names — a DIFFERENT record, not in hand at parse — and the + * region rule's ruling D (decision batch #153 item 1) keeps them unjudged by + * type for exactly that reason. Nor can it see a plugin-registered pausing + * type (ADR-0018). Those shapes are met HERE, on the suspensions that actually + * happen — whatever node raised them, a child flow's plugin-registered pausing + * type included. + * + * ## What the refusal does, and WHEN + * + * It FAILS the run, loud and named, where the engine used to keep one pause + * and drop the rest — the region refusal's answer to the same limit + * (`region-suspension-refusal.ts`), and for the same reason: "prefer failing to + * falling back". Each child run a refused `subflow` / `map` node parked is + * cancelled (`parked-child-cancel.ts`, the one copy the region refusal calls + * too), so no run is left parked under a caller that failed. + * + * ⛔ It never delays a pause and never waits on a branch. A fan-out answers at + * its first rejection, as `Promise.all` did: when that is a suspension the run + * parks and its continuation is stored exactly as before — the same moment, + * the same step log ending at the node it parked on. The branches still + * running are watched from there (`late-branch-watch.ts`, armed by the three + * places that store a pause): at the FIRST of them that later suspends too, + * or ends in this refusal or a region refusal, the run is failed after the + * fact — but only while it still waits at the pause that was watched (same + * node, same correlation), claimed there as a resume claims it and inside the + * same in-process gate a resume takes; its `failed` record is written from + * that pause, its ancestors are failed as a failed child fails them, and every + * child run the suspensions parked is cancelled. A run a decision has already + * moved on — finished, or parked again elsewhere — is left as it is, its new + * pause and that pause's child untouched; that is said at `error`, and the + * late child is cancelled. A sibling that never settles holds nothing back and + * keeps nothing waiting. A rejection collected before the node answers decides + * at once: two suspensions, or a suspension beside one of these refusals, fail + * the run before anything is stored. When the first rejection is a failure the + * run fails as before, and a branch that suspends after it has its child run + * cancelled, since nothing will resume it. The watch lives in process memory: + * an engine restarted between the store write and the late settle keeps the + * old behaviour (the run stays parked, the late branch's work lost unsaid). + * + * Not changed: a sibling that FAILS (with anything but these refusals) after + * another branch parked is dropped, as it always was — `Promise.all`'s + * arrival-order outcome; this refusal does not widen to it. + * + * A traversal that pauses on ONE branch with nothing left to take after it is + * untouched: the synchronous siblings settle as before (concurrent), or the + * pausing branch is the last one taken (sequential), and the run parks and + * resumes exactly as before. The later edges of a sequential traversal are + * judged as they stand at the pause, with the variables the earlier branch + * wrote: an edge whose condition does not hold then is not one the run loses; + * an edge whose condition fails to evaluate is counted as taken, because the + * run could not have gone past it either way. + * + * Inside a region body a pause is refused by the region rule whatever the + * branch shape, so `runRegion` re-raises this refusal as the region one: the + * region is the author's fault there, and the containers know that type. + * + * ## Recognisable, un-routable, named + * + * As the region refusal: recognised by a registered symbol (never + * `instanceof`, which answers `false` across the ESM and CJS builds), branded + * a #3863 guard refusal so a `fault` edge cannot route it, and carrying the + * node whose out-edges diverged, the nodes that suspended and the sub-flows + * they called as structured FIELDS beside the sentence. + * + * ⛔ It carries no `error.code` of its own, and the closed ADR-0112 ledger in + * `packages/spec` is not widened for it — the region refusal's choice, for its + * reason. Unlike the region refusal it logs no failure step: it is thrown from + * the traversal, not from a node's executor, so the failed run carries it as + * its `error`, and its step log ends where the branches stopped (a run failed + * after it parked keeps the log it parked with). + */ + +/** One node that suspended on a refused branch. */ +export interface SuspendedBranchNode { + /** The node that asked to suspend. */ + readonly nodeId: string; + /** + * The child flow a `subflow` / `map` node calls (`config.flowName`). + * Absent for a node that pauses on its own (a plugin-registered pausing + * type): recorded honestly as absent rather than filled with invented text. + */ + readonly subFlowName?: string; +} + +/** An out-edge the traversal would still have taken after the branch that suspended. */ +export interface UntakenBranchEdge { + readonly id?: string; + readonly target: string; +} + +export interface BranchSuspensionRefusalFacts { + /** `concurrent`: two or more unconditional branches suspended; `sequential`: a branch suspended before a later edge. */ + readonly shape: 'concurrent' | 'sequential'; + /** The node whose out-edges led to the branches. */ + readonly forkNodeId: string; + /** The edge the suspending branch was entered by (`sequential` only). */ + readonly suspendedEdge?: UntakenBranchEdge; + /** The nodes that suspended, in the order their suspensions arrived. */ + readonly suspended: readonly SuspendedBranchNode[]; + /** The edges left untaken after the suspending branch (`sequential` only; empty otherwise). */ + readonly untakenEdges: readonly UntakenBranchEdge[]; +} + +const BRANCH_SUSPENSION_REFUSAL: unique symbol = Symbol.for( + 'objectstack.automation.branchSuspensionRefusal', +) as never; + +/** The refusal itself — an `Error`, so every reader of a failed run keeps working with no arm of its own. */ +export class FlowBranchSuspensionRefusalError extends Error implements BranchSuspensionRefusalFacts { + readonly shape: 'concurrent' | 'sequential'; + readonly forkNodeId: string; + readonly suspendedEdge?: UntakenBranchEdge; + readonly suspended: readonly SuspendedBranchNode[]; + readonly untakenEdges: readonly UntakenBranchEdge[]; + + constructor(facts: BranchSuspensionRefusalFacts) { + super(describeBranchSuspensionRefusal(facts)); + this.name = 'FlowBranchSuspensionRefusalError'; + this.shape = facts.shape; + this.forkNodeId = facts.forkNodeId; + if (facts.suspendedEdge !== undefined) this.suspendedEdge = facts.suspendedEdge; + this.suspended = facts.suspended; + this.untakenEdges = facts.untakenEdges; + Object.defineProperty(this, BRANCH_SUSPENSION_REFUSAL, { + value: true, + enumerable: false, + configurable: false, + writable: false, + }); + markGuardRefusal(this); + } +} + +const nodeNamed = (n: SuspendedBranchNode): string => + n.subFlowName !== undefined ? `'${n.nodeId}' (sub-flow '${n.subFlowName}')` : `'${n.nodeId}'`; + +const edgeNamed = (forkNodeId: string, e: UntakenBranchEdge): string => + e.id !== undefined ? `'${e.id}' ('${forkNodeId}' → '${e.target}')` : `'${forkNodeId}' → '${e.target}'`; + +/** + * The sentence, built in one place so the names can never disagree with the + * fields beside them: the limit, why the run is failed rather than parked, and + * the moves that fix the flow — the prescriptions the parse-time rules give for + * the shapes a parse can see, plus the child flow, which only this door names. + */ +function describeBranchSuspensionRefusal(facts: BranchSuspensionRefusalFacts): string { + const { forkNodeId } = facts; + if (facts.shape === 'concurrent') { + return ( + `durable pause on concurrent branches: node '${forkNodeId}' runs its unconditional out-edges together, ` + + `and more than one of those branches suspended — node ${facts.suspended.map(nodeNamed).join(', node ')}. ` + + 'A run parks at one place only, so the pause on every other branch would be dropped without a word and ' + + 'the work after it would never run. The run is FAILED, even where it had already parked on the first ' + + 'of them, and every child run a `subflow` / `map` node of these branches parked is cancelled. Chain the ' + + 'pausing steps one ' + + 'after another on a single branch, or republish the child flow without a node that suspends, so at ' + + 'most one branch of the fan-out pauses.' + ); + } + const via = facts.suspendedEdge !== undefined ? `took edge ${edgeNamed(forkNodeId, facts.suspendedEdge)}, and ` : ''; + return ( + `durable pause before a later branch: node '${forkNodeId}' ${via}node ` + + `${facts.suspended.map(nodeNamed).join(', node ')} suspended on that branch while the same traversal ` + + `still had to take ${facts.untakenEdges.map((e) => `edge ${edgeNamed(forkNodeId, e)}`).join(', ')}. A ` + + `resumed run continues from the node that parked, never back at '${forkNodeId}', so those edges would ` + + 'never be taken and nothing would report it. The run is FAILED rather than parked, and the child run a ' + + '`subflow` / `map` node of that branch parked is cancelled. Make the branch that parks the last one ' + + `'${forkNodeId}' takes (declare its edge after its conditioned siblings, with no unconditional sibling ` + + 'beside it), chain the steps onto one branch so the work after the pause runs on resume, or republish ' + + 'the child flow without a node that suspends.' + ); +} + +/** + * True when `err` is this refusal. Duck-typed on a registered symbol, as + * `isRegionSuspensionRefusal` is, so the ESM and CJS builds agree. + */ +export function isBranchSuspensionRefusal(err: unknown): err is FlowBranchSuspensionRefusalError { + return ( + !!err + && typeof err === 'object' + && (err as Record)[BRANCH_SUSPENSION_REFUSAL] === true + ); +} + +/** The suspended node as the refusal names it: its id and, for a `subflow` / `map`, the child flow. */ +function suspendedNodeOf(flow: FlowParsed, signal: FlowSuspendSignal): SuspendedBranchNode { + const node = flow.nodes.find((n) => n.id === signal.nodeId); + const flowName = (node?.config as { flowName?: unknown } | undefined)?.flowName; + return { + nodeId: signal.nodeId, + ...(typeof flowName === 'string' && flowName ? { subFlowName: flowName } : {}), + }; +} + +/** Cancel each child run the refused suspensions parked, then hand the refusal back for the caller to throw. */ +async function refuse( + host: Pick, + signals: readonly FlowSuspendSignal[], + refusal: FlowBranchSuspensionRefusalError, +): Promise { + const where = `on a branch of node '${refusal.forkNodeId}'`; + // True whatever the run then does: a refusal on a branch still running + // beside a stored pause fails the run only while it waits at that pause + // (`late-branch-watch.ts`); one that meets a run a decision moved on + // leaves the run as it is, and this child is cancelled all the same. + const reason = `a branch of the run that started it was refused because it could not carry the pause, so nothing will resume this run: ${refusal.message}`; + for (const signal of signals) { + await cancelParkedChild(host, { nodeId: signal.nodeId, correlation: signal.correlation }, where, reason); + // The run fails here, so a fan-out this suspension answered for has + // nothing left to park on: what its other branches park is cancelled. + drainLateBranches(host, signal, reason); + } + return refusal; +} + +/** A refusal that fails a run at a pause it cannot carry: this one, or the region one. */ +export function isPauseRefusal(err: unknown): boolean { + return isBranchSuspensionRefusal(err) || isRegionSuspensionRefusal(err); +} + +/** + * The rejections of one fan-out from some index on, AS THEY ARRIVE: a listener + * is handed the ones already in hand at once, then each later one the moment + * its branch rejects. Never "once every branch has settled": a sibling that + * never settles must not hold back what the others did. + */ +export type LateFeed = (listener: (err: unknown) => void) => void; + +/** The branches of one fan-out still running when its first suspension answered for it. */ +export interface LateBranches { + readonly forkNodeId: string; + readonly flow: FlowParsed; + /** Every rejection after the first, each as it arrives. */ + readonly feed: LateFeed; +} + +/** + * The fan-outs a suspension answered for while branches of theirs were still + * running, innermost first. Keyed by the signal itself, which travels up the + * traversal unchanged to the place that stores the pause. + */ +const LATE_BRANCHES = new WeakMap(); + +/** The fan-outs `signal` answered for with branches still running (empty for none). */ +export function lateBranchesOf(signal: FlowSuspendSignal): readonly LateBranches[] { + return LATE_BRANCHES.get(signal) ?? []; +} + +export type CancelHost = Pick; + +/** + * The run failed (or is being failed) where `signal` would have parked it: + * cancel the child run every suspension still to come from those fan-outs + * parks, deepest first, as each arrives. Never awaited by the traversal; every + * failure inside is logged by {@link cancelParkedChild}. + */ +export function drainLateBranches(host: CancelHost, signal: FlowSuspendSignal, reason: string): void { + for (const late of lateBranchesOf(signal)) cancelLateSuspensions(host, late.feed, late.forkNodeId, reason); +} + +/** Cancel the child run of each suspension `feed` delivers, the moment it arrives. */ +export function cancelLateSuspensions(host: CancelHost, feed: LateFeed, forkNodeId: string, reason: string): void { + feed((err) => { + if (!isSuspendSignal(err)) return; + void cancelParkedChild(host, err, `on a branch of node '${forkNodeId}' after the run had failed`, reason) + .then(() => drainLateBranches(host, err, reason)); + }); +} + +/** + * Run a node's unconditional branches together. + * + * The node answers at its FIRST rejection, at the moment it arrives, as + * `Promise.all` did — so a pause is never delayed and nothing waits on a + * branch that may never settle. What changes is what happens to the rest: + * + * - first a suspension, and nothing else collected yet: it is thrown, the + * run parks as before, and the branches still running are recorded on the + * signal for `watchLateBranches` (`late-branch-watch.ts`), which fails the + * parked run at the first of them that later suspends or ends in a pause + * refusal; + * - first a suspension, and before this frame resumed a second suspension or + * a pause refusal already arrived: the concurrent refusal (or that + * refusal) is thrown at once, nothing is stored, and the children parked + * are cancelled; + * - first anything else: it is thrown, as before, and a branch that suspends + * after it has its child run cancelled, since no run will resume it. + */ +export async function runConcurrentBranches( + host: CancelHost, + node: FlowNodeParsed, + flow: FlowParsed, + branches: ReadonlyArray>, +): Promise { + const rejections: unknown[] = []; + const listeners: Array<(err: unknown) => void> = []; + let remaining = branches.length; + let wake: () => void = () => {}; + const changed = (): Promise => new Promise((resolve) => { wake = resolve; }); + const settle = (): void => { + remaining--; + wake(); + }; + for (const run of branches) { + run.then(settle, (err: unknown) => { + rejections.push(err); + for (const listener of listeners) listener(err); + settle(); + }); + } + /** The rejections from index `from` on: those in hand now, then each as it arrives. */ + const feedFrom = (from: number): LateFeed => (listener) => { + for (const err of rejections.slice(from)) listener(err); + listeners.push(listener); + }; + while (remaining > 0 && rejections.length === 0) await changed(); + if (rejections.length === 0) return; + const first = rejections[0]; + const collected = rejections.slice(1); + const rest = feedFrom(1 + collected.length); + const reason = (message: string) => `the run that started it failed at a branch that could not carry the pause: ${message}`; + if (!isSuspendSignal(first)) { + // A failure answers for the node, as before; a suspension already + // collected or still to come beside it parks a child nobody resumes. + const message = first instanceof Error ? first.message : String(first); + cancelLateSuspensions( + host, feedFrom(1), node.id, + `another branch of node '${node.id}' failed first, so nothing will resume the pause this run parked on: ${message}`, + ); + throw first; + } + const collectedSignals = collected.filter(isSuspendSignal); + const collectedRefusal = collected.find(isPauseRefusal); + if (collectedSignals.length > 0) { + throw await refuseConcurrent(host, node, flow, [first, ...collectedSignals], rest); + } + if (collectedRefusal !== undefined) { + const message = (collectedRefusal as Error).message; + await cancelParkedChild(host, first, `on a branch of node '${node.id}'`, reason(message)); + drainLateBranches(host, first, reason(message)); + cancelLateSuspensions(host, rest, node.id, reason(message)); + throw collectedRefusal; + } + // Nothing collected but the suspension: the run parks on it now, and the + // branches still running are judged as they settle. + const late = LATE_BRANCHES.get(first) ?? []; + late.push({ forkNodeId: node.id, flow, feed: feedFrom(1) }); + LATE_BRANCHES.set(first, late); + throw first; +} + +/** The concurrent refusal over `signals`, each parked child cancelled; suspensions still to come cancel theirs. */ +async function refuseConcurrent( + host: CancelHost, + node: FlowNodeParsed, + flow: FlowParsed, + signals: readonly FlowSuspendSignal[], + rest: LateFeed, +): Promise { + const refusal = await refuse(host, signals, new FlowBranchSuspensionRefusalError({ + shape: 'concurrent', + forkNodeId: node.id, + suspended: signals.map((s) => suspendedNodeOf(flow, s)), + untakenEdges: [], + })); + cancelLateSuspensions(host, rest, node.id, `the run that started it failed at a branch that could not carry the pause: ${refusal.message}`); + return refusal; +} + +/** The concurrent refusal's sentence for the watched pause and the branch that suspended after it. */ +export function lateConcurrentRefusalMessage(entry: LateBranches, watched: FlowSuspendSignal, late: FlowSuspendSignal): string { + return new FlowBranchSuspensionRefusalError({ + shape: 'concurrent', + forkNodeId: entry.forkNodeId, + suspended: [watched, late].map((s) => suspendedNodeOf(entry.flow, s)), + untakenEdges: [], + }).message; +} + +/** + * Take one branch of a node's sequential out-edges (a conditioned or an + * `isDefault` edge): run `branch`, and when it suspends while `later` would + * still be taken by this traversal, throw the sequential refusal instead of + * the suspension. `later` is asked only after the suspension, so it judges the + * later edges against the variables the branch wrote; a suspension with + * nothing left to take is re-thrown untouched. + */ +export async function runSequentialBranch( + host: Pick, + node: FlowNodeParsed, + flow: FlowParsed, + edge: FlowEdgeParsed, + branch: () => Promise, + later: () => FlowEdgeParsed[], +): Promise { + try { + await branch(); + } catch (err) { + if (!isSuspendSignal(err)) throw err; + const untaken = later(); + if (untaken.length === 0) throw err; + throw await refuse(host, [err], new FlowBranchSuspensionRefusalError({ + shape: 'sequential', + forkNodeId: node.id, + suspendedEdge: { ...(edge.id ? { id: edge.id } : {}), target: edge.target }, + suspended: [suspendedNodeOf(flow, err)], + untakenEdges: untaken.map((e) => ({ ...(e.id ? { id: e.id } : {}), target: e.target })), + })); + } +} diff --git a/packages/services/service-automation/src/dag-traversal.ts b/packages/services/service-automation/src/dag-traversal.ts index 8007e54d629..5a6cdad716b 100644 --- a/packages/services/service-automation/src/dag-traversal.ts +++ b/packages/services/service-automation/src/dag-traversal.ts @@ -37,7 +37,6 @@ import { isRefusalSignal, isSuspendSignal, MAX_STEP_CHILD_RUN_IDS, - nestedChildRunId, type ExecutionLogEntry, type NodeExecutionResult, type StepLogEntry, @@ -67,6 +66,8 @@ import { ExpressionEngine, validateExpression } from '@objectstack/formula'; import type { ExprValidationCode } from '@objectstack/formula'; import { readPartialSteps } from './partial-steps.js'; import { isRegionSuspensionRefusal, refuseRegionSuspension } from './region-suspension-refusal.js'; +import { drainLateBranches, isBranchSuspensionRefusal, runConcurrentBranches, runSequentialBranch } from './branch-suspension-refusal.js'; +import { cancelParkedChild } from './parked-child-cancel.js'; import { stampFlowRunSlot } from './flow-slots.js'; import { stampRootRun } from './root-run.js'; import { stampRunFlowChecksum } from './run-flow-checksum.js'; @@ -212,6 +213,8 @@ export interface DagTraversalHost { readonly renderFlowTerminalMessage: AutomationEngine['renderFlowTerminalMessage']; readonly resolveSuspensionChainForCancel: AutomationEngine['resolveSuspensionChainForCancel']; readonly cancelRun: AutomationEngine['cancelRun']; + /** [#38876] Arm the late-branch watch on a pause just stored (`watchLateBranches`). */ + readonly watchLateBranches: AutomationEngine['watchLateBranches']; } /** @@ -664,7 +667,7 @@ export async function executeNode( /** The body of {@link AutomationEngine.traverseNext}, moved unedited; that method's docblock is its contract. */ export async function traverseNext( - this: Pick, + this: Pick, node: FlowNodeParsed, flow: FlowParsed, variables: Map, @@ -792,8 +795,26 @@ export async function traverseNext( // its migration cover the gateway, and nothing else was measured to // carry two conditioned out-edges (the corpus census on #15429). const exclusive = node.type === 'decision' && !decisionTakesEveryBranch(node); + // [#38876] The edges this traversal still takes after a branch that + // suspends, judged at the pause (`branch-suspension-refusal.ts`): an edge + // that would have run is one the resumed run never takes, because it + // resumes from the node that parked, never back here. Only ever asked + // after a suspension, so a traversal that does not pause evaluates + // exactly what it evaluated before. + const hasTarget = (e: FlowEdgeParsed): boolean => flow.nodes.some(n => n.id === e.target); + const wouldHold = (e: FlowEdgeParsed): boolean => { + try { + return this.evaluateCondition(e.condition!, variables, context); + } catch { + // A condition that fails to evaluate would have failed the run: + // the run could not have gone past it either way. + return true; + } + }; + const takenAfterwards = (rest: readonly FlowEdgeParsed[]): FlowEdgeParsed[] => + [...rest, ...unconditionalEdges].filter(hasTarget); let anyConditionMet = false; - for (const edge of conditionalEdges) { + for (const [i, edge] of conditionalEdges.entries()) { const nextNode = flow.nodes.find(n => n.id === edge.target); if (exclusive && anyConditionMet) { // A sibling already won: passed over, not evaluated. @@ -803,7 +824,11 @@ export async function traverseNext( if (this.evaluateCondition(edge.condition!, variables, context)) { anyConditionMet = true; if (nextNode) { - await this.executeNode(nextNode, flow, variables, context, steps); + await runSequentialBranch( + this, node, flow, edge, + () => this.executeNode(nextNode, flow, variables, context, steps), + () => takenAfterwards(exclusive ? [] : conditionalEdges.slice(i + 1).filter(wouldHold)), + ); } } else if (nextNode) { recordSkipped(nextNode, edge); @@ -817,11 +842,15 @@ export async function traverseNext( // of every sibling condition, and forgetting to do that ran both // branches. A default edge passed over because a real branch won records // the same `skipped` trace a closed gate does (#4354). - for (const edge of defaultEdges) { + for (const [k, edge] of defaultEdges.entries()) { const nextNode = flow.nodes.find(n => n.id === edge.target); if (!anyConditionMet) { if (nextNode) { - await this.executeNode(nextNode, flow, variables, context, steps); + await runSequentialBranch( + this, node, flow, edge, + () => this.executeNode(nextNode, flow, variables, context, steps), + () => takenAfterwards(defaultEdges.slice(k + 1)), + ); } } else if (nextNode) { const at = new Date().toISOString(); @@ -842,14 +871,18 @@ export async function traverseNext( } } - // Unconditional edges: execute in parallel (Promise.all) + // Unconditional edges: execute in parallel. [#38876] The first rejection + // answers for the node at once, as `Promise.all` threw it; a second + // suspension or a pause refusal from another branch fails the run instead + // of being dropped — at once when it is already in hand, after the run + // has parked otherwise (`branch-suspension-refusal.ts`). if (unconditionalEdges.length > 0) { const parallelTasks = unconditionalEdges .map(edge => flow.nodes.find(n => n.id === edge.target)) .filter((n): n is FlowNodeParsed => n != null) .map(nextNode => this.executeNode(nextNode, flow, variables, context, steps)); - await Promise.all(parallelTasks); + await runConcurrentBranches(this, node, flow, parallelTasks); } } @@ -927,6 +960,20 @@ export async function runRegion( // this error is not a suspend signal and must not reach the generic // rethrow below with an enclosing region's identity stamped on it. if (isRegionSuspensionRefusal(err)) throw err; + // [#38876] A branch refusal raised inside this body: a region cannot + // carry a pause on ANY branch, so the region rule names the fault, + // exactly as it would for a lone suspension, and the containers that + // know the region type re-throw it. The branch refusal has already + // cancelled every child run its suspensions parked. + if (isBranchSuspensionRefusal(err)) { + const first = err.suspended[0]; + throw refuseRegionSuspension({ + regionNodeId: grouping?.parentNodeId ?? entryId, + regionKind: grouping?.regionKind ?? 'region', + suspendedNodeId: first?.nodeId ?? err.forkNodeId, + ...(first?.subFlowName !== undefined ? { subFlowName: first.subFlowName } : {}), + }); + } // [#18881] The runtime half of #15646's ruling D: a region body // cannot carry a durable pause, and the refusal is now NAMED // (region node, suspending node, sub-flow) instead of a plain @@ -956,55 +1003,20 @@ export async function runRegion( // resume ran the rest of the child for a caller that had already // failed, then failed to resume that caller. So the child run is // cancelled, with every run it is itself parked on, deepest - // first, through the engine's own `cancelRun`. ⛔ The refusal is - // thrown exactly as before: a failed cancellation is logged, never - // put in its place. - const childRunId = nestedChildRunId(err.correlation); - if (childRunId !== undefined) { - try { - // [#29333] The chain is read through the STRICT loader, - // the read `cancelRun` itself takes. The degrading one - // answered an unreadable link as "nothing suspended", so - // the walk stopped there and every run below that link - // stayed parked with only a `warn` said (#29166 covered - // the case where the unreadable link is the child itself). - const { chain, unreadable } = await this.resolveSuspensionChainForCancel(childRunId); - const reason = `the run that started it failed at a region boundary: ${refusal.message}`; - if (unreadable) { - // The deepest link the walk knows of. Its id is known - // (the link above names it, or it is the child), so it - // is cancelled anyway, deepest first: `cancelRun` - // reads it again and owns the `error` record for THAT - // run when the store still cannot be read, and it is a - // no-op when the run is in fact gone. - await this.cancelRun(unreadable.runId, reason); - // What `cancelRun` cannot say: the walk never read - // this link, so a run it is itself parked on was never - // reached and may still be parked. #4632 verdict: - // DURABILITY, `error`. - this.logger.error( - `[automation] node '${err.nodeId}' suspended inside region '${refusal.regionNodeId}', and ` + - `the suspended run '${unreadable.runId}' in the chain of the child run '${childRunId}' could not be ` + - `read while cancelling that chain, so any run '${unreadable.runId}' is itself parked on ` + - `was not reached and may still be parked. Once the suspended-run store answers, cancel ` + - `each with cancelRun(runId). The read failure is in this record's meta.`, - undefined, - describeThrownForLog(unreadable.cause), - ); - } - for (const run of [...chain].reverse()) await this.cancelRun(run.runId, reason); - } catch (cancelErr) { - // #4632 verdict: DURABILITY, `error`, as `cancelRun`'s own - // store failure: the child may still be parked. - this.logger.error( - `[automation] node '${err.nodeId}' suspended inside region '${refusal.regionNodeId}', and ` + - `cancelling the child run '${childRunId}' it parked failed, so that run may still be ` + - `parked. Cancel it with cancelRun('${childRunId}'). The failure is in this record's meta.`, - undefined, - describeThrownForLog(cancelErr), - ); - } - } + // first, through the engine's own `cancelRun` — the one copy in + // `parked-child-cancel.ts`, which the branch refusal calls too + // (#38876). ⛔ The refusal is thrown exactly as before: a failed + // cancellation is logged, never put in its place. + await cancelParkedChild( + this, + { nodeId: err.nodeId, correlation: err.correlation }, + `inside region '${refusal.regionNodeId}'`, + `the run that started it failed at a region boundary: ${refusal.message}`, + ); + // [#38876] A fan-out inside the body answered with this + // suspension while other branches of it still ran: what they park + // is cancelled too, since the run fails here. + drainLateBranches(this, err, `the run that started it failed at a region boundary: ${refusal.message}`); throw refusal; } // [#15788] The refusing `end` node's signal, converted at exactly @@ -1380,7 +1392,7 @@ export function startConditionHolds( /** The body of {@link AutomationEngine.executeWithoutRetry}, moved unedited; that method's docblock is its contract. */ export async function executeWithoutRetry( - this: Pick, + this: Pick, flowName: string, context?: AutomationContext, dispatched?: { errorMessage: string | undefined }, @@ -1681,6 +1693,9 @@ export async function executeWithoutRetry( steps, variables: variablesSnapshot, }, context); + // [#38876] Stored first; a branch still running beside the pause + // is judged as it settles, never waited on here. + void this.watchLateBranches(runId, err); return { success: true, status: 'paused', diff --git a/packages/services/service-automation/src/dry-run.ts b/packages/services/service-automation/src/dry-run.ts index 3444840101c..b026de3191f 100644 --- a/packages/services/service-automation/src/dry-run.ts +++ b/packages/services/service-automation/src/dry-run.ts @@ -449,6 +449,11 @@ function traverseHost(state: DryRunState): ThisParameterType dryExecuteNode(state, ...a), + // [#38876] A branch that cannot carry a pause cancels the child run a + // `subflow` / `map` parked. A dry run starts no child run (its stops + // carry no correlation), so nothing reaches these; reached, they say so. + resolveSuspensionChainForCancel: () => Promise.reject(new Error('a dry run parks no child run to cancel')), + cancelRun: () => Promise.reject(new Error('a dry run parks no child run to cancel')), }; } diff --git a/packages/services/service-automation/src/engine-run-facet.ts b/packages/services/service-automation/src/engine-run-facet.ts index 51c7ee85e8e..4af013bae7a 100644 --- a/packages/services/service-automation/src/engine-run-facet.ts +++ b/packages/services/service-automation/src/engine-run-facet.ts @@ -85,6 +85,7 @@ export interface RunHost { readonly nextRunId: AutomationEngine['nextRunId']; readonly noteRunStarted: AutomationEngine['noteRunStarted']; readonly persistSuspendedRun: AutomationEngine['persistSuspendedRun']; + readonly watchLateBranches: AutomationEngine['watchLateBranches']; readonly recordLog: AutomationEngine['recordLog']; readonly renderFlowTerminalMessage: AutomationEngine['renderFlowTerminalMessage']; readonly resolveFlowKey: AutomationEngine['resolveFlowKey']; @@ -185,7 +186,7 @@ export class RunFacet { * [#31696] {@link execute} for the flow filed under the slot key * `flowName`, already resolved. Every record of the run is keyed by it. */ - static async executeKey(this: Pick, flowName: string, context: AutomationContext | undefined, startTime: number): Promise { + static async executeKey(this: Pick, flowName: string, context: AutomationContext | undefined, startTime: number): Promise { const flow = this.flows.get(flowName); // [#31696] Read with the flow, before any await: the slot's key can // move while the run is in flight, its package cannot. @@ -610,6 +611,9 @@ export class RunFacet { steps, variables: variablesSnapshot, }, context); + // [#38876] Stored first; a branch still running beside the + // pause is judged as it settles, never waited on here. + void this.watchLateBranches(runId, err); return { success: true, status: 'paused', diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index 9da9a6757ba..e5f5ef04e0f 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -197,6 +197,7 @@ import { readRecordRun, readRootRun, type RecordRun, type RootRun } from './root import { ConnectorInstances } from './connector-instances.js'; import type { ConnectorInstanceOptions } from './plugin-extension-api.js'; import { regionSuspendingCall } from './subflow-region-guard.js'; +import { ResumeGate, watchLateBranches, type PendingAncestorFailure } from './late-branch-watch.js'; import { subflowRetriedCallout } from './subflow-retry-guard.js'; // [#25222] The consumed-suspension restore's bodies: journaling a consumed // suspension, resolving its witnesses, and restoring, peeking at or inspecting @@ -307,6 +308,7 @@ export { missedRunId, } from './engine-run-trigger.js'; import { + type FlowSuspendSignal, type RefusalI18nService, type FlowTextSlotTranslation, type ChildRunRefusal, @@ -886,8 +888,16 @@ export class AutomationEngine implements IAutomationService { /** * Run ids currently mid-resume — an in-process idempotency guard so a * duplicate `resume(runId)` can't re-enter and double-run side effects. + * [#38876] A `Set` that can also be waited on: the late-branch watch + * (`late-branch-watch.ts`) takes this same gate, waiting its turn. */ - private resuming = new Set(); + private resuming = new ResumeGate(); + /** + * [#38876] Failed descendants handed to an ancestor whose own pause was + * not stored yet when the late-branch watch's ancestor walk read it; its + * store step takes the entry (`late-branch-watch.ts`). + */ + private pendingAncestorFailures = new Map(); /** * [#13909] Suspensions this process consumed on a resume that then failed * downstream — the hot half of {@link restoreConsumedSuspension}, mirrored @@ -1219,6 +1229,38 @@ export class AutomationEngine implements IAutomationService { return ResumeFacet.persistSuspendedRun.call(resumeHost.of(this), run); } + /** + * [#38876] Judge the branches still running beside a pause this run has + * just stored: when one of them later suspends too, or ends in a branch or + * region refusal, the parked run cannot carry it and is failed where it + * waited (claimed as a resume claims it, its ancestors failed, every + * child run the suspensions parked cancelled), and a failed descendant + * left for this run by an ancestor walk that could not read its pause yet + * fails it too. Armed by the three places that store a pause, after they + * stored it, and never awaited, so it neither delays the pause nor waits + * on a branch that never settles; it never rejects: a fault in it is said + * at `error`. + */ + private watchLateBranches(runId: string, signal: FlowSuspendSignal): Promise { + // The body lives in ./late-branch-watch.ts. + const host: ThisParameterType = { + resuming: this.resuming, + pendingAncestorFailures: this.pendingAncestorFailures, + loadSuspendedRunStrict: (...a) => this.loadSuspendedRunStrict(...a), + loadSuspendedRun: (...a) => this.loadSuspendedRun(...a), + claimAdvance: (...a) => this.claimAdvance(...a), + evictConsumedSuspension: (...a) => this.evictConsumedSuspension(...a), + forgetSuspendedRun: (...a) => this.forgetSuspendedRun(...a), + failSuspendedRun: (...a) => this.failSuspendedRun(...a), + consumedSuspensions: this.consumedSuspensions, + recordLog: (...a) => this.recordLog(...a), + resolveSuspensionChainForCancel: (...a) => this.resolveSuspensionChainForCancel(...a), + cancelRun: (...a) => this.cancelRun(...a), + logger: this.logger, + }; + return watchLateBranches.call(host, runId, signal); + } + /** * Drop a suspended run from the in-memory cache and (best-effort) the * durable store. Called once the run is claimed for resume or reaches a @@ -5181,6 +5223,7 @@ export class AutomationEngine implements IAutomationService { loadSuspendedRun: (...a) => this.loadSuspendedRun(...a), resumeInternal: (...a) => this.resumeInternal(...a), persistSuspendedRun: (...a) => this.persistSuspendedRun(...a), + watchLateBranches: (...a) => this.watchLateBranches(...a), failSuspendedRun: (...a) => this.failSuspendedRun(...a), consumedSuspensions: this.consumedSuspensions, buildSubflowResumeSignal: (...a) => this.buildSubflowResumeSignal(...a), @@ -6860,6 +6903,8 @@ export class AutomationEngine implements IAutomationService { logger: this.logger, evaluateCondition: (...a) => this.evaluateCondition(...a), executeNode: (...a) => this.executeNode(...a), + resolveSuspensionChainForCancel: (...a) => this.resolveSuspensionChainForCancel(...a), + cancelRun: (...a) => this.cancelRun(...a), }; return traverseNext.call(host, node, flow, variables, context, steps, branchLabel); } @@ -7460,6 +7505,7 @@ export class AutomationEngine implements IAutomationService { logger: this.logger, finishRefusedRun: (...a) => this.finishRefusedRun(...a), persistSuspendedRun: (...a) => this.persistSuspendedRun(...a), + watchLateBranches: (...a) => this.watchLateBranches(...a), flowChecksumOf: (...a) => this.flowChecksumOf(...a), renderFlowTerminalMessage: (...a) => this.renderFlowTerminalMessage(...a), flowSlotPackage: (...a) => this.flowSlotPackage(...a), @@ -7698,6 +7744,7 @@ export class AutomationEngine implements IAutomationService { nextRunId: (...a) => engine.nextRunId(...a), noteRunStarted: (...a) => engine.noteRunStarted(...a), persistSuspendedRun: (...a) => engine.persistSuspendedRun(...a), + watchLateBranches: (...a) => engine.watchLateBranches(...a), recordLog: (...a) => engine.recordLog(...a), renderFlowTerminalMessage: (...a) => engine.renderFlowTerminalMessage(...a), resolveFlowKey: (...a) => engine.resolveFlowKey(...a), diff --git a/packages/services/service-automation/src/late-branch-watch.ts b/packages/services/service-automation/src/late-branch-watch.ts new file mode 100644 index 00000000000..4460eb50c08 --- /dev/null +++ b/packages/services/service-automation/src/late-branch-watch.ts @@ -0,0 +1,485 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38876] What happens AFTER a fan-out answered `paused` and a branch still + * running beside the pause then cannot carry its own: the run-time half of the + * branch refusal (`branch-suspension-refusal.ts`), split out because it binds + * to stored state rather than to the traversal. + * + * ## The watch + * + * The three places that store a pause (`execute`, a retry attempt, a resume + * that parks again) arm {@link watchLateBranches} right after they stored it, + * never awaited. It listens to the branches the pause left running and acts on + * the FIRST of them that suspends too, or ends in a branch or region refusal — + * not once every branch has settled, so a sibling that never settles holds + * nothing back. It acts on the PAUSE it watched, never on whatever the run + * holds by then: + * + * 1. it enters the run's in-process resume gate (`resuming`, the gate + * `resume` takes), waiting while a resume holds it, so no resume of the run + * in this process overlaps it — the whole guarantee where the store cannot + * claim (no store, a store without `claimSuspension`, `unsupported`, a + * cache-only pause). Until step 3 has claimed the pause, a resume that + * meets the gate waits for the watch instead of being refused + * ({@link ResumeGate}); + * 2. it reads the run, and a run that is no longer parked at the watched node + * with the watched correlation — a decision resumed it, whether it then + * finished or parked again elsewhere, or it ended otherwise — is left + * alone, its new pause and that pause's child untouched, and a resume that + * waited goes on; + * 3. it claims that pause as a resume claims it, against the watched node and + * correlation, so a replica that moved the run first wins; + * 4. it writes the `failed` record from the stored pause (its step log ends + * at the node it parked on), fails the run's ancestors as a failed child + * fails them, and cancels every child run the suspensions parked. + * + * The child run the late branch parked is cancelled in every outcome: no run + * will resume through it. Every outcome of a late branch is said once at `error`, by what + * happened — failed, left alone because it had moved on, or not failed because + * the store could not be read or claimed (with the remedy). + * + * ## An ancestor whose pause is not stored yet + * + * A run that waits on this one as a `subflow` / `map` stores its own pause + * only after this one answered it `paused`, and its store write can still be + * in flight — or not started — when a short late branch settles. A read then + * finds no parent, and a plain walk would stop there and leave the parent + * parked for good on a child that failed. So each hop of the ancestor walk + * first leaves a {@link PendingAncestorFailure} under the parent's id, THEN + * reads it: a parent the read finds is failed by the walk; one it does not is + * failed by its own store step, which reads the entry right after its pause is + * durable (the same {@link watchLateBranches} call). Whichever side takes the + * entry first acts; the other stands down. A parent whose save landed before + * the entry was left is one the read finds. + * + * ## Process memory + * + * The watch, its feed and the pending ancestor failures live in this process. + * An engine restarted between the store write and the late settle keeps the + * old behaviour: the run stays parked and resumable, and the late branch's + * work is lost without a word. + */ + +import type { AutomationEngine, SuspendedRun } from './engine.js'; +import { waitOfPausedRun } from './engine-resume.js'; +import { nestedChildRunId } from './engine-run-log.js'; +import { buildRunTrigger } from './engine-run-trigger.js'; +import { isSuspendSignal, type FlowSuspendSignal } from './engine-signals.js'; +import { + drainLateBranches, + isPauseRefusal, + lateBranchesOf, + lateConcurrentRefusalMessage, + type CancelHost, + type LateBranches, +} from './branch-suspension-refusal.js'; +import { cancelParkedChild, type ParkedChildSuspension } from './parked-child-cancel.js'; +import { describeThrownForLog } from './thrown-cause-diagnostics.js'; + +/** + * The engine's in-process resume gate: the set of run ids a resume is + * advancing in this process (`has` / `add` / `delete`, as the `Set` it + * replaces), plus a way to wait for one to be let go. The late-branch watch + * waits its turn, since nobody retries it. + * + * The watch takes the gate before it has read whether the run is still at the + * pause it watched, and it must never refuse a resume of a run it then leaves + * alone: nobody retries that resume either (a child's bubble to its parent, a + * decision the approval service has already recorded). So while the watch + * holds the gate UNDECIDED, a resume waits ({@link whenDecided}) instead of + * being refused; once the watch has claimed the pause it fails the run, and a + * resume is answered `RESUME_IN_PROGRESS` as at any held gate. It waits only + * for the watch's read and claim, never for a node's release hook, so a hook + * that resumes the run cannot deadlock it. + */ +export class ResumeGate { + private readonly held = new Set(); + private readonly waiters = new Map void>>(); + /** Runs the watch holds without having decided yet whether it acts, each with the resumes waiting for that. */ + private readonly undecided = new Map void>>(); + + has(runId: string): boolean { + return this.held.has(runId); + } + + add(runId: string): this { + this.held.add(runId); + return this; + } + + delete(runId: string): boolean { + const wasHeld = this.held.delete(runId); + // The resumes the watch kept waiting go first: a watch let go undecided + // left the run alone, so they find it free. + this.decide(runId); + const waiting = this.waiters.get(runId); + if (waiting) { + this.waiters.delete(runId); + for (const wake of waiting) wake(); + } + return wasHeld; + } + + /** The watch takes the free gate before it knows whether it acts (see the class docblock). */ + holdUndecided(runId: string): void { + this.held.add(runId); + this.undecided.set(runId, []); + } + + /** The watch has claimed the pause and fails the run: a resume that waited is now refused, as at any held gate. */ + decide(runId: string): void { + const waiting = this.undecided.get(runId); + if (waiting === undefined) return; + this.undecided.delete(runId); + for (const wake of waiting) wake(); + } + + /** The watch holds `runId` and has not decided yet whether it acts. */ + isUndecided(runId: string): boolean { + return this.undecided.has(runId); + } + + /** Resolves once the watch holding `runId` has decided (at once when none holds it undecided). */ + whenDecided(runId: string): Promise { + const waiting = this.undecided.get(runId); + if (waiting === undefined) return Promise.resolve(); + return new Promise((resolve) => waiting.push(resolve)); + } + + /** Resolves once `runId` is not held (at once when it is not). */ + whenFree(runId: string): Promise { + if (!this.held.has(runId)) return Promise.resolve(); + return new Promise((resolve) => { + const waiting = this.waiters.get(runId) ?? []; + waiting.push(resolve); + this.waiters.set(runId, waiting); + }); + } +} + +/** Take the gate for `runId` undecided, waiting while anything in this process holds it. */ +async function enterResumeGate(gate: ResumeGate, runId: string): Promise { + while (gate.has(runId)) await gate.whenFree(runId); + gate.holdUndecided(runId); +} + +/** A failed descendant handed to an ancestor whose pause was not readable as stored when the walk reached it. */ +export interface PendingAncestorFailure { + /** The run this ancestor waits on (its pause's `subflow:` / `map:` correlation names it). */ + readonly childRunId: string; + /** The failure, as the ancestor walk words it after `subflow descendant failed: `. */ + readonly error: string; +} + +/** How many pending ancestor failures one engine keeps; the oldest goes first. */ +const MAX_PENDING_ANCESTOR_FAILURES = 1000; + +/** What {@link watchLateBranches} reads and writes. */ +export interface LateBranchHost extends CancelHost { + readonly resuming: ResumeGate; + readonly pendingAncestorFailures: Map; + readonly loadSuspendedRunStrict: AutomationEngine['loadSuspendedRunStrict']; + readonly loadSuspendedRun: AutomationEngine['loadSuspendedRun']; + readonly claimAdvance: AutomationEngine['claimAdvance']; + readonly evictConsumedSuspension: AutomationEngine['evictConsumedSuspension']; + readonly forgetSuspendedRun: AutomationEngine['forgetSuspendedRun']; + readonly failSuspendedRun: AutomationEngine['failSuspendedRun']; + readonly consumedSuspensions: AutomationEngine['consumedSuspensions']; + readonly recordLog: AutomationEngine['recordLog']; +} + +/** + * The body of `AutomationEngine.watchLateBranches`, armed by every place that + * stores a pause right after it stored it (see the module docblock). + * + * Two things are judged here, both against the pause `signal` just stored: + * a failed descendant left for this run by an ancestor walk that could not + * read its pause yet, and the branches the pause left running. + * + * #4632 verdict: a caller answered `paused` whose run is now `failed` holds a + * stale answer: said once at `error`, naming the run and the refusal. Never + * rejects: the three store sites do not await it, so a fault inside is said at + * `error` here. + */ +export function watchLateBranches(this: LateBranchHost, runId: string, signal: FlowSuspendSignal): Promise { + const fault = (err: unknown): void => { + // #4632 verdict: DURABILITY, `error`: a run that had to be failed may + // still read paused, and a late child may still be parked. + this.logger.error( + `[automation] the late-branch watch of run '${runId}' (parked at node '${signal.nodeId}') failed, so a ` + + `run that had to be failed may still read paused and a child run a late branch parked may still be ` + + `parked. Cancel them with cancelRun(runId). The failure is in this record's meta.`, + undefined, + describeThrownForLog(err), + ); + }; + try { + return judgeLateBranches(this, runId, signal).catch(fault); + } catch (err) { + fault(err); + return Promise.resolve(); + } +} + +function judgeLateBranches(host: LateBranchHost, runId: string, signal: FlowSuspendSignal): Promise { + const work: Array> = []; + const descendant = takePendingAncestorFailure(host, runId, signal); + if (descendant !== undefined) work.push(failForDescendant(host, runId, signal, descendant)); + const entries = lateBranchesOf(signal); + if (entries.length > 0) work.push(watchEntries(host, runId, signal, entries)); + return Promise.all(work).then(() => undefined); +} + +/** + * Act on the first late suspension or pause refusal any of `entries` delivers; + * cancel the child of every suspension after it. Resolves once that first one + * has been acted on — never, when none arrives. + */ +function watchEntries(host: LateBranchHost, runId: string, signal: FlowSuspendSignal, entries: readonly LateBranches[]): Promise { + return new Promise((resolve, reject) => { + let acted: string | undefined; + for (const entry of entries) { + entry.feed((err) => { + if (acted !== undefined) { + // Another branch parked after the watch had acted: nothing + // will resume it, whatever became of the run. + if (isSuspendSignal(err)) { + const reason = lateChildReason(acted); + void cancelParkedChild(host, err, `on a branch of node '${entry.forkNodeId}'`, reason) + .then(() => drainLateBranches(host, err, reason)); + } + return; + } + // A sibling that FAILS with anything else is dropped, as it + // always was: `Promise.all`'s arrival-order outcome. + if (!isSuspendSignal(err) && !isPauseRefusal(err)) return; + const message = isSuspendSignal(err) ? lateConcurrentRefusalMessage(entry, signal, err) : (err as Error).message; + acted = message; + actOnLate(host, runId, signal, entry, err, message).then(resolve, reject); + }); + } + }); +} + +const failedRunReason = (message: string): string => + `the run that started it failed at a branch that could not carry the pause: ${message}`; +const lateChildReason = (message: string): string => + `the run that started it had already parked on another branch and cannot carry this pause beside it: ${message}`; + +async function actOnLate( + host: LateBranchHost, + runId: string, + signal: FlowSuspendSignal, + entry: LateBranches, + late: unknown, + message: string, +): Promise { + const outcome = await failParkedRun(host, runId, signal, message, message); + if (outcome === 'failed') { + await cancelParkedChild(host, signal, `on a branch of the run '${runId}'`, failedRunReason(message)); + } + const lateSignal = isSuspendSignal(late) ? late : undefined; + if (lateSignal !== undefined) { + const reason = outcome === 'failed' ? failedRunReason(message) : lateChildReason(message); + await cancelParkedChild(host, lateSignal, `on a branch of node '${entry.forkNodeId}'`, reason); + drainLateBranches(host, lateSignal, reason); + } + const cancelled = lateSignal !== undefined && nestedChildRunId(lateSignal.correlation) !== undefined + ? `; the child run that branch parked was cancelled` + : ''; + if (outcome === 'failed') { + host.logger.error( + `[automation] run '${runId}' was answered 'paused' at node '${signal.nodeId}', and a branch still running beside ` + + `it then could not carry its own pause, so the run is now FAILED${cancelled}: ${message}`, + ); + } else if (outcome === 'moved-on') { + host.logger.error( + `[automation] run '${runId}' parked at node '${signal.nodeId}', and a branch still running beside it then could ` + + `not carry its own pause, but the run had already left that pause (resumed past it, or ended), so it was ` + + `left as it is and that branch's work was not carried${cancelled}: ${message}`, + ); + } + // 'not-failed': `failParkedRun` already said why at `error`, with the remedy. +} + +/** A failed descendant left for `runId`, when its pause waits on exactly that descendant. Taken either way. */ +function takePendingAncestorFailure(host: LateBranchHost, runId: string, signal: FlowSuspendSignal): PendingAncestorFailure | undefined { + const pending = host.pendingAncestorFailures.get(runId); + if (pending === undefined) return undefined; + host.pendingAncestorFailures.delete(runId); + return nestedChildRunId(signal.correlation) === pending.childRunId ? pending : undefined; +} + +async function failForDescendant(host: LateBranchHost, runId: string, signal: FlowSuspendSignal, pending: PendingAncestorFailure): Promise { + const error = `subflow descendant failed: ${pending.error}`; + const outcome = await failParkedRun(host, runId, signal, error, pending.error); + if (outcome !== 'failed') return; + host.logger.error( + `[automation] run '${runId}' was answered 'paused' at node '${signal.nodeId}', waiting on the child run ` + + `'${pending.childRunId}', which had already been failed because a branch beside its own pause could not carry ` + + `its own, so the run is now FAILED: ${error}`, + ); +} + +type ParkedRunOutcome = 'failed' | 'moved-on' | 'not-failed'; + +/** The run is still parked where `watched` parked it: same node, same correlation. */ +const isAtPause = (run: SuspendedRun, watched: ParkedChildSuspension): boolean => + run.nodeId === watched.nodeId && (run.correlation ?? undefined) === (watched.correlation ?? undefined); + +/** + * Fail `runId` where it waited at `watched`, inside its resume gate: `failed`; + * `moved-on` when it no longer waits there (no row, another pause, a claim + * another replica won); `not-failed` when the store could not be read or + * claimed, or failing it threw — said here at `error`. + */ +async function failParkedRun( + host: LateBranchHost, + runId: string, + watched: ParkedChildSuspension, + error: string, + ancestorError: string, +): Promise { + await enterResumeGate(host.resuming, runId); + let failedRun: SuspendedRun; + try { + let run: SuspendedRun | null; + try { + run = await host.loadSuspendedRunStrict(runId); + } catch (err) { + // #4632 verdict: DURABILITY, `error`: the run may still read paused + // over a branch it can never carry. + host.logger.error( + `[automation] run '${runId}' had to be failed because a branch beside its pause could not carry its own, ` + + `but the suspended-run store could not be read, so the run may still read paused. Once the store ` + + `answers, cancel it with cancelRun('${runId}'). The read failure is in this record's meta.`, + undefined, + describeThrownForLog(err), + ); + return 'not-failed'; + } + if (!run || !isAtPause(run, watched)) return 'moved-on'; + const claim = await host.claimAdvance(run); + if (claim.kind === 'lost') { + // [#15832] The store answered: no row is parked where this read + // one, so the snapshot this process holds is stale. The gate is + // held, so no resume in this process moved it. + host.evictConsumedSuspension(runId); + return 'moved-on'; + } + if (claim.kind === 'unavailable') { + host.logger.error( + `[automation] run '${runId}' had to be failed because a branch beside its pause could not carry its own, ` + + `but the suspended-run store did not answer the claim, so whether the pause was consumed is unknown ` + + `and the run may still read paused. Once the store answers, cancel it with cancelRun('${runId}'): ` + + `${claim.message}`, + ); + return 'not-failed'; + } + // The pause is the watch's now: a resume that waited on the read and + // the claim is refused from here on, as at any held gate. Before the + // release hook `forgetSuspendedRun` fires, so a hook that resumes the + // run is answered, never kept waiting on the watch that awaits it. + host.resuming.decide(runId); + await host.forgetSuspendedRun(run, 'failed', claim.kind === 'claimed'); + recordFailedWhereItWaited(host, run, error); + failedRun = run; + } catch (err) { + host.logger.error( + `[automation] run '${runId}' had to be failed because a branch beside its pause could not carry its own, ` + + `but failing it threw, so the run may still read paused. Cancel it with cancelRun('${runId}'). The ` + + `failure is in this record's meta.`, + undefined, + describeThrownForLog(err), + ); + return 'not-failed'; + } finally { + host.resuming.delete(runId); + } + try { + await failAncestorsAfterLateFailure(host, failedRun, ancestorError); + } catch (err) { + // The run itself is failed: its caller still cancels the child runs + // the suspensions parked and says so, whatever an ancestor's write did. + // #4632 verdict: DURABILITY, `error`: an ancestor may still read paused. + host.logger.error( + `[automation] run '${runId}' was failed because a branch beside its pause could not carry its own, but ` + + `failing a run that waits on it as a subflow threw, so that run may still read paused or have no ` + + `history row that says why. Cancel it with cancelRun(runId). The failure is in this record's meta.`, + undefined, + describeThrownForLog(err), + ); + } + return 'failed'; +} + +/** The `failed` record of a run failed where it waited, its write guarded as `settleUnresumableSuspension` guards it. */ +function recordFailedWhereItWaited(host: LateBranchHost, run: SuspendedRun, error: string): void { + try { + // [#32284] Failed where it waited: everything since its pause is wait. + const durationMs = Date.now() - run.startTime; + host.recordLog({ + id: run.runId, + flowName: run.flowName, + flowVersion: run.flowVersion, + status: 'failed', + startedAt: run.startedAt, + completedAt: new Date().toISOString(), + durationMs, + waitMs: waitOfPausedRun(run, durationMs), + trigger: buildRunTrigger(run.context), + steps: run.steps, + error, + }, run.context); + } catch (bookkeeping) { + // #4632 verdict: DURABILITY, `error`, as in `settleUnresumableSuspension`: + // the pause is consumed, so the run no longer reads as paused, but the + // `failed` row that says why never landed and nothing retries it. + host.logger.error( + `[automation] run '${run.runId}' of flow '${run.flowName}' was failed because a branch beside its pause ` + + `could not carry its own, and its suspension was consumed, but recording its terminal 'failed' history ` + + `threw, so no history row says why: the run no longer reads as paused, and nothing retries the write. ` + + `Fix the history failure in this record's meta.`, + undefined, + describeThrownForLog(bookkeeping), + ); + } +} + +/** + * Fail the ancestors of a run the watch failed, as `failAncestors` does — the + * degrading read, the same error at every hop — with the hand-over of the + * module docblock for an ancestor whose pause the read cannot find yet. + */ +async function failAncestorsAfterLateFailure(host: LateBranchHost, run: SuspendedRun, error: string): Promise { + let below = run.runId; + let context = run.context as Record | undefined; + for (let hops = 0; hops < 32; hops++) { + const parentId = context?.$parentRunId; + if (typeof parentId !== 'string' || !parentId) return; + const pending: PendingAncestorFailure = { childRunId: below, error }; + host.pendingAncestorFailures.set(parentId, pending); + while (host.pendingAncestorFailures.size > MAX_PENDING_ANCESTOR_FAILURES) { + const oldest = host.pendingAncestorFailures.keys().next().value; + if (oldest === undefined) break; + host.pendingAncestorFailures.delete(oldest); + } + const parent = await host.loadSuspendedRun(parentId); + // Its own store step took the hand-over while this read was out: it + // fails itself and walks on from there. + if (host.pendingAncestorFailures.get(parentId) !== pending) return; + // Not stored yet: left for its store step. + if (!parent) return; + host.pendingAncestorFailures.delete(parentId); + await host.failSuspendedRun( + parent, + `subflow descendant failed: ${error}`, + // [#15222] As `failAncestors`: only a descendant this process holds + // a snapshot for makes the ancestor's own snapshot restorable. + hops > 0 && host.consumedSuspensions.has(below) ? below : undefined, + ); + below = parent.runId; + context = parent.context as Record | undefined; + } +} diff --git a/packages/services/service-automation/src/parked-child-cancel.ts b/packages/services/service-automation/src/parked-child-cancel.ts new file mode 100644 index 00000000000..27686c5de29 --- /dev/null +++ b/packages/services/service-automation/src/parked-child-cancel.ts @@ -0,0 +1,94 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Cancel the child run a `subflow` / `map` node parked, when the run that + * started it fails instead of parking on it. + * + * A `subflow` / `map` node suspends by parking the CHILD run it started and + * linking it through its correlation (`subflow:` / + * `map:`). When the calling run is failed at that point rather + * than parked, nothing will ever resume through that link: measured (#28897), + * the child stayed parked in the durable store, and a later resume ran the rest + * of the child for a caller that had already failed, then failed to resume + * that caller. So the child run is cancelled, with every run it is itself + * parked on, deepest first, through the engine's own `cancelRun`. + * + * Two refusals fail a run at that point, and both call this one copy: + * + * - `runRegion`'s region refusal (`region-suspension-refusal.ts`): the call + * sits inside a region body, which cannot carry a pause at all; + * - the branch refusal (`branch-suspension-refusal.ts`): the call sits on a + * branch whose pause would drop another branch of the same traversal. + * + * ⛔ The caller throws its refusal exactly as it would have: a failed + * cancellation is logged here, never put in the refusal's place. + */ + +import type { DagTraversalHost } from './dag-traversal.js'; +import { nestedChildRunId } from './engine-run-log.js'; +import { describeThrownForLog } from './thrown-cause-diagnostics.js'; + +/** The suspension a refused node raised, and where the refusal met it, for the log line. */ +export interface ParkedChildSuspension { + /** The node that suspended (a `subflow` / `map` node when a child is parked). */ + readonly nodeId: string; + /** The suspend signal's correlation; only `subflow:` / `map:` name a child run. */ + readonly correlation?: string; +} + +/** + * Cancel the child run `suspension` parked, and every run that child is parked + * on, deepest first. A no-op when the suspension parked no child run. + * + * @param where - completes "node 'X' suspended …" in the log line, e.g. + * `inside region 'box'`. + * @param reason - the reason each cancelled run's terminal record carries. + */ +export async function cancelParkedChild( + host: Pick, + suspension: ParkedChildSuspension, + where: string, + reason: string, +): Promise { + const childRunId = nestedChildRunId(suspension.correlation); + if (childRunId === undefined) return; + try { + // [#29333] The chain is read through the STRICT loader, the read + // `cancelRun` itself takes. The degrading one answered an unreadable + // link as "nothing suspended", so the walk stopped there and every run + // below that link stayed parked with only a `warn` said (#29166 + // covered the case where the unreadable link is the child itself). + const { chain, unreadable } = await host.resolveSuspensionChainForCancel(childRunId); + if (unreadable) { + // The deepest link the walk knows of. Its id is known (the link + // above names it, or it is the child), so it is cancelled anyway, + // deepest first: `cancelRun` reads it again and owns the `error` + // record for THAT run when the store still cannot be read, and it + // is a no-op when the run is in fact gone. + await host.cancelRun(unreadable.runId, reason); + // What `cancelRun` cannot say: the walk never read this link, so a + // run it is itself parked on was never reached and may still be + // parked. #4632 verdict: DURABILITY, `error`. + host.logger.error( + `[automation] node '${suspension.nodeId}' suspended ${where}, and ` + + `the suspended run '${unreadable.runId}' in the chain of the child run '${childRunId}' could not be ` + + `read while cancelling that chain, so any run '${unreadable.runId}' is itself parked on ` + + `was not reached and may still be parked. Once the suspended-run store answers, cancel ` + + `each with cancelRun(runId). The read failure is in this record's meta.`, + undefined, + describeThrownForLog(unreadable.cause), + ); + } + for (const run of [...chain].reverse()) await host.cancelRun(run.runId, reason); + } catch (cancelErr) { + // #4632 verdict: DURABILITY, `error`, as `cancelRun`'s own store + // failure: the child may still be parked. + host.logger.error( + `[automation] node '${suspension.nodeId}' suspended ${where}, and ` + + `cancelling the child run '${childRunId}' it parked failed, so that run may still be ` + + `parked. Cancel it with cancelRun('${childRunId}'). The failure is in this record's meta.`, + undefined, + describeThrownForLog(cancelErr), + ); + } +} diff --git a/packages/services/service-automation/src/run-resume.ts b/packages/services/service-automation/src/run-resume.ts index 33d45593028..0a64ddcdaf8 100644 --- a/packages/services/service-automation/src/run-resume.ts +++ b/packages/services/service-automation/src/run-resume.ts @@ -108,6 +108,7 @@ export interface RunResumeHost { readonly settleUnresumableSuspension: AutomationEngine['settleUnresumableSuspension']; readonly creditChildRun: AutomationEngine['creditChildRun']; readonly persistSuspendedRun: AutomationEngine['persistSuspendedRun']; + readonly watchLateBranches: AutomationEngine['watchLateBranches']; readonly buildSubflowResumeSignal: AutomationEngine['buildSubflowResumeSignal']; readonly refuseInvalidScreenInput: AutomationEngine['refuseInvalidScreenInput']; readonly cloneVariablesAtPause: AutomationEngine['cloneVariablesAtPause']; @@ -1412,7 +1413,7 @@ export function takeSubflowParentStrand(this: Pick, + this: Pick, runId: string, // Never `undefined` past the public door: `resume` normalises an // absent caller signal to `{}` (commit 7307191db), and the engine's own @@ -1429,6 +1430,11 @@ export async function resumeInternal( // concurrent duplicate resume of the same run so side effects can't run // twice. A duplicate that arrives *after* this one finishes finds no // suspended run and returns the "no suspended run" error below. + // [#38876] The one wait before it: the late-branch watch holds the gate + // while it reads whether the run is still at the pause it watched, and a + // run it leaves alone must not have this resume refused on its account — + // nobody retries it. The loop ends in the same tick as the check below. + while (this.resuming.isUndecided(runId)) await this.resuming.whenDecided(runId); if (this.resuming.has(runId)) { return { success: false, code: 'RESUME_IN_PROGRESS', error: `Run '${runId}' is already being resumed` }; } @@ -2322,6 +2328,9 @@ export async function resumeInternal( steps, variables: variablesSnapshot, }, context); + // [#38876] Stored first; a branch still running beside the + // pause is judged as it settles, never waited on here. + void this.watchLateBranches(runId, err); return { success: true, status: 'paused', runId, durationMs, screen: err.screen, flowLabel: flow.label }; }