From a4b0676dcb400181893ba468ab4ff6ebe982f662 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 02:14:50 +0000 Subject: [PATCH 01/14] wip(automation): refuse a branch pause that would drop another branch at run time Claude-Session: https://claude.ai/code/session_01QSeKYnrQ7UMtHofKQVjcH2 Co-authored-by: Claude --- .../src/branch-suspension-refusal.ts | 285 ++++++++++++++++++ .../service-automation/src/dag-traversal.ts | 120 ++++---- .../service-automation/src/dry-run.ts | 5 + .../services/service-automation/src/engine.ts | 2 + .../src/parked-child-cancel.ts | 94 ++++++ 5 files changed, 449 insertions(+), 57 deletions(-) create mode 100644 packages/services/service-automation/src/branch-suspension-refusal.ts create mode 100644 packages/services/service-automation/src/parked-child-cancel.ts 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..f3135391022 --- /dev/null +++ b/packages/services/service-automation/src/branch-suspension-refusal.ts @@ -0,0 +1,285 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +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'; + +/** + * 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, at the traversal, the first time + * a branch actually pauses where the run cannot park. + * + * ## What the refusal does + * + * 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 first (`parked-child-cancel.ts`, the one copy the region refusal + * calls too), so no run is left parked under a caller that failed. + * + * ⛔ It does not make the engine resume the dropped continuation, nor + * serialise concurrent branches: that would change what a fan-out means. + * + * A traversal that pauses on ONE branch with nothing left to take after it is + * untouched: the synchronous siblings have completed (concurrent), or the + * pausing branch is the last one taken (sequential), and the run parks and + * resumes exactly as before. The later edges 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: the failed run keeps the + * `EXECUTION_ERROR` code every thrown failure carries, and the closed + * ADR-0112 ledger in `packages/spec` is not widened for it — the region + * refusal's choice, for its reason. + */ + +/** 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 rather than parked at one 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}'`; + const reason = `the run that started it failed at a branch that could not carry the pause: ${refusal.message}`; + for (const signal of signals) { + await cancelParkedChild(host, { nodeId: signal.nodeId, correlation: signal.correlation }, where, reason); + } + return refusal; +} + +/** + * Run a node's unconditional branches together and settle them ALL before + * answering, so a second suspension cannot be dropped behind the first. + * + * What is thrown is what `Promise.all` threw — the FIRST rejection to arrive — + * except when two or more branches suspended: that is the concurrent refusal, + * thrown once every branch has settled and each parked child run is cancelled. + * + * The one change to a traversal that is not refused: the node no longer + * answers before its slower branches have settled. A synchronous sibling of + * the one pausing branch used to finish after the run had already answered + * `paused`; it now finishes first. + */ +export async function runConcurrentBranches( + host: Pick, + node: FlowNodeParsed, + flow: FlowParsed, + branches: ReadonlyArray>, +): Promise { + const rejections: unknown[] = []; + await Promise.all(branches.map((branch) => branch.catch((err: unknown) => { rejections.push(err); }))); + if (rejections.length === 0) return; + const signals = rejections.filter(isSuspendSignal); + if (signals.length < 2) throw rejections[0]; + throw await refuse(host, signals, new FlowBranchSuspensionRefusalError({ + shape: 'concurrent', + forkNodeId: node.id, + suspended: signals.map((s) => suspendedNodeOf(flow, s)), + untakenEdges: [], + })); +} + +/** + * 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..c8fb2cb879a 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 { 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'; @@ -664,7 +665,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 +793,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 +822,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 +840,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 +869,18 @@ export async function traverseNext( } } - // Unconditional edges: execute in parallel (Promise.all) + // Unconditional edges: execute in parallel. [#38876] Every branch is + // settled before the node answers, and two suspensions are the + // concurrent refusal rather than one kept and one dropped + // (`branch-suspension-refusal.ts`); otherwise the first rejection is + // thrown, as `Promise.all` threw it. 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 +958,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 +1001,16 @@ 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}`, + ); throw refusal; } // [#15788] The refusing `end` node's signal, converted at exactly 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.ts b/packages/services/service-automation/src/engine.ts index 9da9a6757ba..a9867df7863 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -6860,6 +6860,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); } 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), + ); + } +} From c86fa44a74b0ca0f7a0ecb924dceacf9645643aa Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 02:20:08 +0000 Subject: [PATCH 02/14] test: pin the run-time branch pause refusal on the engine and the approval rig Claude-Session: https://claude.ai/code/session_01QSeKYnrQ7UMtHofKQVjcH2 Co-authored-by: Claude --- .../src/flow-route.integration.test.ts | 288 ++++++++++++++++++ .../src/branch-suspension-refusal.test.ts | 147 +++++++++ 2 files changed, 435 insertions(+) create mode 100644 packages/services/service-automation/src/branch-suspension-refusal.test.ts 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..0741e1d0a20 100644 --- a/packages/plugins/plugin-approvals/src/flow-route.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/flow-route.integration.test.ts @@ -1016,3 +1016,291 @@ 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); }); }); + +/** + * [#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[]) => { + const svc = new ApprovalService({ engine: engine as any, clock: { now: () => new Date(now += 1000) }, logger: silent }); + const automation = new AutomationEngine(silent); + installBuiltinNodes(automation, { logger: silent, getService() { throw new Error('none'); } } as any); + automation.setSuspendedRunStore(new InMemorySuspendedRunStore()); + svc.attachAutomation(automation as any); + registerApprovalNode(automation as any, svc, silent); + for (const flow of flows) automation.registerFlow(flow.name, flow); + return { svc, automation }; + }; + 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 } as any)) 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 expectRefused = async (automation: AutomationEngine, recordId: string, result: any, lead: string) => { + expect(result.success).toBe(false); + expect(result.status).toBe('failed'); + expect(result.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) { + expect(await automation.hasSuspendedRun(runId), `run ${runId} is not left parked`).toBe(false); + } + return runs; + }; + + /** 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' }, + ], + }); + + 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'); + await expectRefused(automation, record.id, result, CONCURRENT); + expect(result.error).toContain("node 'a_review', 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'); + await expectRefused(automation, record.id, result, CONCURRENT); + expect(result.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 [approvalChild] = await expectRefused(automation, record.id, result, CONCURRENT); + expect(result.error).toContain("(sub-flow 'branch_parking_child')"); + expect(result.error).toContain("(sub-flow 'branch_waiting_child')"); + expect((await automation.getRun(approvalChild))?.status, 'the approval child run').toBe('cancelled'); + const 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 [child] = await expectRefused(automation, record.id, result, "durable pause before a later branch: node 'x1' took edge 'c1'"); + expect(result.error).toContain("node 'sub' (sub-flow 'branch_parking_child') suspended on that branch"); + expect(result.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'); + await expectRefused(automation, record.id, result, "durable pause before a later branch: node 'x1' took edge 'c1'"); + expect(result.error).toContain("edge 'c2' ('x1' → 's_sync')"); + }); + + 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..ffa29ec1290 --- /dev/null +++ b/packages/services/service-automation/src/branch-suspension-refusal.test.ts @@ -0,0 +1,147 @@ +// 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 a timer child: 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. + +import { describe, it, expect, vi } from 'vitest'; +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() { + const logger: any = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; + logger.child = () => logger; + const engine = withLoaderSetFromPull(new AutomationEngine(logger)); + engine.setSuspendedRunStore(new InMemorySuspendedRunStore()); + 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); + } + return { engine, logger }; +} + +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 }); + +/** A child that parks on a one-hour timer. */ +const HOLD = { + name: 'deal_hold', label: 'Hold', type: 'autolaunched', + nodes: [START, { id: 'hold', type: 'wait', label: 'Hold', waitEventConfig: { eventType: 'timer', timerDuration: 'PT1H' } }, end('done')], + edges: [edge('h1', 'start', 'hold'), edge('h2', '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 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')]); +}; + +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 result: any = await engine.execute(FAN_OUT.name, {} as any); + expect(result).toMatchObject({ success: false, status: 'failed' }); + expect(result.error).toContain("durable pause on concurrent branches: node 'start'"); + expect(result.error).toContain("node 'sub_a' (sub-flow 'deal_hold')"); + expect(result.error).toContain("node 'sub_b' (sub-flow 'deal_hold')"); + expect(await engine.listSuspendedRunsDurable(), 'nothing is left parked').toEqual([]); + }); + + it('SEQUENTIAL: a call whose child parks before a later true sibling fails the run, 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 engine.listSuspendedRunsDurable()).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 engine.listSuspendedRunsDurable(), 'both children are cancelled').toEqual([]); + }); + + 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'); + const run = await engine.getRun(result.runId); + expect(run?.steps.filter((s) => s.status === 'success').map((s) => s.nodeId), 'the synchronous branch ran before the run answered') + .toEqual(expect.arrayContaining(['s_sync', 'sub_a'])); + }); +}); From 5d611a2c464e671b54cb92e77a4306771a8fe070 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 02:32:15 +0000 Subject: [PATCH 03/14] fix(automation): a fan-out waits for its other branches only when one of them may still pause Claude-Session: https://claude.ai/code/session_01QSeKYnrQ7UMtHofKQVjcH2 Co-authored-by: Claude --- .../src/branch-suspension-refusal.test.ts | 2 +- .../src/branch-suspension-refusal.ts | 92 ++++++++++++++++--- .../service-automation/src/dag-traversal.ts | 16 ++-- .../service-automation/src/dry-run.ts | 3 + .../services/service-automation/src/engine.ts | 7 ++ 5 files changed, 100 insertions(+), 20 deletions(-) diff --git a/packages/services/service-automation/src/branch-suspension-refusal.test.ts b/packages/services/service-automation/src/branch-suspension-refusal.test.ts index ffa29ec1290..e6204301500 100644 --- a/packages/services/service-automation/src/branch-suspension-refusal.test.ts +++ b/packages/services/service-automation/src/branch-suspension-refusal.test.ts @@ -141,7 +141,7 @@ describe('[#38876] the branch refusal on the engine', () => { const result: any = await engine.execute(oneCall.name, {} as any); expect(result.status).toBe('paused'); const run = await engine.getRun(result.runId); - expect(run?.steps.filter((s) => s.status === 'success').map((s) => s.nodeId), 'the synchronous branch ran before the run answered') + expect(run?.steps.filter((s) => s.status === 'success').map((s) => s.nodeId), 'both branches ran') .toEqual(expect.arrayContaining(['s_sync', 'sub_a'])); }); }); diff --git a/packages/services/service-automation/src/branch-suspension-refusal.ts b/packages/services/service-automation/src/branch-suspension-refusal.ts index f3135391022..ffc5f64e1cf 100644 --- a/packages/services/service-automation/src/branch-suspension-refusal.ts +++ b/packages/services/service-automation/src/branch-suspension-refusal.ts @@ -1,10 +1,13 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +import { FLOW_PAUSE_CAPABLE_NODE_TYPES } from '@objectstack/spec/automation'; import type { FlowEdgeParsed, FlowNodeParsed, FlowParsed } from '@objectstack/spec/automation'; import type { DagTraversalHost } from './dag-traversal.js'; +import type { NodeExecutor } from './engine-node-contract.js'; import { isSuspendSignal, type FlowSuspendSignal } from './engine-signals.js'; import { markGuardRefusal } from './guard-refusal.js'; import { cancelParkedChild } from './parked-child-cancel.js'; +import { suspendingNode, type FlowCallKey } from './subflow-notice-guard.js'; /** * The "a branch's durable pause would drop another branch" refusal (#38876), @@ -220,30 +223,95 @@ async function refuse( return refusal; } +/** What {@link branchMayPause} reads: the engine's flows, the call-key resolver and the executor registry. */ +export interface BranchPauseReader { + readonly flows: ReadonlyMap; + readonly flowCallKey: FlowCallKey; + readonly nodeExecutors: ReadonlyMap; +} + /** - * Run a node's unconditional branches together and settle them ALL before - * answering, so a second suspension cannot be dropped behind the first. + * Whether a branch entered at `entryId` of `flow` may still pause the run: a + * node reachable from it (along any edge of `flow`) whose executor declares + * `supportsPause` or whose type always pauses, or a `subflow` / `map` node + * whose child flow can suspend — read by `suspendingNode`, the reading the + * arming gate's region and save-notice halves take, so a call whose child + * never pauses does not count. A container's region body is not walked: a + * pause there is the region refusal, a failure, never a suspension. + */ +export function branchMayPause(reader: BranchPauseReader, flow: FlowParsed, entryId: string): boolean { + const seen = new Set(); + const stack = [entryId]; + while (stack.length > 0) { + const id = stack.pop() as string; + if (seen.has(id)) continue; + seen.add(id); + const node = flow.nodes.find((n) => n.id === id); + if (!node) continue; + if (node.type === 'subflow' || node.type === 'map') { + const child = (node.config as { flowName?: unknown } | undefined)?.flowName; + if (typeof child === 'string' && child) { + const caller = typeof flow.name === 'string' ? flow.name : ''; + const key = reader.flowCallKey(caller, child); + if (suspendingNode(reader.flows, key, undefined, reader.flowCallKey) !== undefined) return true; + } + } else if ( + FLOW_PAUSE_CAPABLE_NODE_TYPES.includes(node.type) + || reader.nodeExecutors.get(node.type)?.descriptor?.supportsPause === true + ) { + return true; + } + for (const e of flow.edges) if (e.source === id) stack.push(e.target); + } + return false; +} + +/** + * Run a node's unconditional branches together, and keep a second suspension + * from being dropped behind the first. * - * What is thrown is what `Promise.all` threw — the FIRST rejection to arrive — - * except when two or more branches suspended: that is the concurrent refusal, - * thrown once every branch has settled and each parked child run is cancelled. + * What is thrown is what `Promise.all` threw — the FIRST rejection to arrive, + * at the moment it arrives — with one exception. When that first rejection is + * a suspension and a branch still running MAY pause too (`mayPause`, the + * reading {@link branchMayPause} gives), the node waits for every branch to + * settle: two or more suspensions are the concurrent refusal, thrown once each + * parked child run is cancelled; one is the first suspension, re-thrown. * - * The one change to a traversal that is not refused: the node no longer - * answers before its slower branches have settled. A synchronous sibling of - * the one pausing branch used to finish after the run had already answered - * `paused`; it now finishes first. + * So a fan-out whose other branches cannot pause answers exactly when it did + * (its synchronous siblings still finish after the run has answered `paused`, + * the timing the run-end readings of the approvals plugin are built on); only a + * fan-out with a second branch that may pause waits for it — the population + * that loses a branch when it does. */ export async function runConcurrentBranches( host: Pick, node: FlowNodeParsed, flow: FlowParsed, - branches: ReadonlyArray>, + branches: ReadonlyArray<{ readonly entryId: string; readonly run: Promise }>, + mayPause: (entryId: string) => boolean, ): Promise { + const done = branches.map(() => false); const rejections: unknown[] = []; - await Promise.all(branches.map((branch) => branch.catch((err: unknown) => { rejections.push(err); }))); + let remaining = branches.length; + let wake: () => void = () => {}; + const changed = (): Promise => new Promise((resolve) => { wake = resolve; }); + branches.forEach(({ run }, index) => { + run.then( + () => { done[index] = true; remaining--; wake(); }, + (err: unknown) => { done[index] = true; rejections.push(err); remaining--; wake(); }, + ); + }); + while (remaining > 0 && rejections.length === 0) await changed(); if (rejections.length === 0) return; + const first = rejections[0]; + if (!isSuspendSignal(first)) throw first; + // Branches that settled before this frame resumed are already in + // `rejections`; only one still running that may pause is waited for. + if (branches.some(({ entryId }, index) => !done[index] && mayPause(entryId))) { + while (remaining > 0) await changed(); + } const signals = rejections.filter(isSuspendSignal); - if (signals.length < 2) throw rejections[0]; + if (signals.length < 2) throw first; throw await refuse(host, signals, new FlowBranchSuspensionRefusalError({ shape: 'concurrent', forkNodeId: node.id, diff --git a/packages/services/service-automation/src/dag-traversal.ts b/packages/services/service-automation/src/dag-traversal.ts index c8fb2cb879a..b406ad9531e 100644 --- a/packages/services/service-automation/src/dag-traversal.ts +++ b/packages/services/service-automation/src/dag-traversal.ts @@ -213,6 +213,8 @@ export interface DagTraversalHost { readonly renderFlowTerminalMessage: AutomationEngine['renderFlowTerminalMessage']; readonly resolveSuspensionChainForCancel: AutomationEngine['resolveSuspensionChainForCancel']; readonly cancelRun: AutomationEngine['cancelRun']; + /** [#38876] Whether the branch entered at a node of `flow` may still pause (`branchMayPause`). */ + readonly branchMayPause: (flow: FlowParsed, entryId: string) => boolean; } /** @@ -665,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, @@ -869,18 +871,18 @@ export async function traverseNext( } } - // Unconditional edges: execute in parallel. [#38876] Every branch is - // settled before the node answers, and two suspensions are the + // Unconditional edges: execute in parallel. [#38876] The first rejection + // is thrown as `Promise.all` threw it, except that a suspension waits for + // the branches that may still pause, and two suspensions are the // concurrent refusal rather than one kept and one dropped - // (`branch-suspension-refusal.ts`); otherwise the first rejection is - // thrown, as `Promise.all` threw it. + // (`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)); + .map(nextNode => ({ entryId: nextNode.id, run: this.executeNode(nextNode, flow, variables, context, steps) })); - await runConcurrentBranches(this, node, flow, parallelTasks); + await runConcurrentBranches(this, node, flow, parallelTasks, (entryId) => this.branchMayPause(flow, entryId)); } } diff --git a/packages/services/service-automation/src/dry-run.ts b/packages/services/service-automation/src/dry-run.ts index b026de3191f..282a3f7d492 100644 --- a/packages/services/service-automation/src/dry-run.ts +++ b/packages/services/service-automation/src/dry-run.ts @@ -454,6 +454,9 @@ function traverseHost(state: DryRunState): ThisParameterType 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')), + // A dry run stops at its first pausing node and starts no child run, + // so a fan-out answers at its first stop, as it always has. + branchMayPause: () => false, }; } diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index a9867df7863..a179c24d17a 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 { branchMayPause } from './branch-suspension-refusal.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 @@ -6862,6 +6863,12 @@ export class AutomationEngine implements IAutomationService { executeNode: (...a) => this.executeNode(...a), resolveSuspensionChainForCancel: (...a) => this.resolveSuspensionChainForCancel(...a), cancelRun: (...a) => this.cancelRun(...a), + // [#38876] The body lives in ./branch-suspension-refusal.ts. + branchMayPause: (branchFlow, entryId) => branchMayPause( + { flows: this.flows, flowCallKey: this.flowCallKey, nodeExecutors: this.nodeExecutors }, + branchFlow, + entryId, + ), }; return traverseNext.call(host, node, flow, variables, context, steps, branchLabel); } From b7cd09f37a79dbae54b4e2d672dc126fb450acdb Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 02:45:09 +0000 Subject: [PATCH 04/14] docs(automation): flows teach the run-time branch refusal; changeset Claude-Session: https://claude.ai/code/session_01QSeKYnrQ7UMtHofKQVjcH2 Co-authored-by: Claude --- .../38876-subflow-branch-pause-refusal.md | 24 +++++++++++++ content/docs/automation/flows.mdx | 36 +++++++++++++++++-- 2 files changed, 57 insertions(+), 3 deletions(-) create mode 100644 .changeset/38876-subflow-branch-pause-refusal.md diff --git a/.changeset/38876-subflow-branch-pause-refusal.md b/.changeset/38876-subflow-branch-pause-refusal.md new file mode 100644 index 00000000000..0ead1800a7e --- /dev/null +++ b/.changeset/38876-subflow-branch-pause-refusal.md @@ -0,0 +1,24 @@ +--- +'@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 the first time the shape happens, with a named error, 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, and it keeps the `EXECUTION_ERROR` step code every thrown failure carries. Inside a `loop`, `parallel` or `try_catch` body the region error is raised instead, as for any pause there. + +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 fan-out answers as soon as its first branch pauses, as before, unless another branch still running may pause too (it reaches a step that pauses, or a `subflow` / `map` whose child flow can): only then does it wait for its branches to settle, to see whether a second one pauses. + +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`, and an administrator recalls it to release the record. diff --git a/content/docs/automation/flows.mdx b/content/docs/automation/flows.mdx index 3d2e387f90c..2327d2970e3 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,35 @@ 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 the first time a branch actually +pauses, a child flow that parks included, 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. + +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`; +an administrator recalls it to release the record. 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 From 5c0793ad6b53783ff7ff8f53ae974ab316e4ffa5 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 03:00:06 +0000 Subject: [PATCH 05/14] fix(automation): the engine hands the branch reader over in one forwarding call Claude-Session: https://claude.ai/code/session_01QSeKYnrQ7UMtHofKQVjcH2 Co-authored-by: Claude --- .../src/branch-suspension-refusal.ts | 24 +++++++++---------- .../services/service-automation/src/engine.ts | 6 +---- 2 files changed, 13 insertions(+), 17 deletions(-) diff --git a/packages/services/service-automation/src/branch-suspension-refusal.ts b/packages/services/service-automation/src/branch-suspension-refusal.ts index ffc5f64e1cf..9fca4ac366b 100644 --- a/packages/services/service-automation/src/branch-suspension-refusal.ts +++ b/packages/services/service-automation/src/branch-suspension-refusal.ts @@ -223,15 +223,9 @@ async function refuse( return refusal; } -/** What {@link branchMayPause} reads: the engine's flows, the call-key resolver and the executor registry. */ -export interface BranchPauseReader { - readonly flows: ReadonlyMap; - readonly flowCallKey: FlowCallKey; - readonly nodeExecutors: ReadonlyMap; -} - /** - * Whether a branch entered at `entryId` of `flow` may still pause the run: a + * Whether a branch entered at `entryId` of `flow` may still pause the run, read + * over the engine's `flows`, its call-key resolver and its executor registry: a * node reachable from it (along any edge of `flow`) whose executor declares * `supportsPause` or whose type always pauses, or a `subflow` / `map` node * whose child flow can suspend — read by `suspendingNode`, the reading the @@ -239,7 +233,13 @@ export interface BranchPauseReader { * never pauses does not count. A container's region body is not walked: a * pause there is the region refusal, a failure, never a suspension. */ -export function branchMayPause(reader: BranchPauseReader, flow: FlowParsed, entryId: string): boolean { +export function branchMayPause( + flows: ReadonlyMap, + flowCallKey: FlowCallKey, + nodeExecutors: ReadonlyMap, + flow: FlowParsed, + entryId: string, +): boolean { const seen = new Set(); const stack = [entryId]; while (stack.length > 0) { @@ -252,12 +252,12 @@ export function branchMayPause(reader: BranchPauseReader, flow: FlowParsed, entr const child = (node.config as { flowName?: unknown } | undefined)?.flowName; if (typeof child === 'string' && child) { const caller = typeof flow.name === 'string' ? flow.name : ''; - const key = reader.flowCallKey(caller, child); - if (suspendingNode(reader.flows, key, undefined, reader.flowCallKey) !== undefined) return true; + const key = flowCallKey(caller, child); + if (suspendingNode(flows, key, undefined, flowCallKey) !== undefined) return true; } } else if ( FLOW_PAUSE_CAPABLE_NODE_TYPES.includes(node.type) - || reader.nodeExecutors.get(node.type)?.descriptor?.supportsPause === true + || nodeExecutors.get(node.type)?.descriptor?.supportsPause === true ) { return true; } diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index a179c24d17a..0a4c9a41f58 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -6864,11 +6864,7 @@ export class AutomationEngine implements IAutomationService { resolveSuspensionChainForCancel: (...a) => this.resolveSuspensionChainForCancel(...a), cancelRun: (...a) => this.cancelRun(...a), // [#38876] The body lives in ./branch-suspension-refusal.ts. - branchMayPause: (branchFlow, entryId) => branchMayPause( - { flows: this.flows, flowCallKey: this.flowCallKey, nodeExecutors: this.nodeExecutors }, - branchFlow, - entryId, - ), + branchMayPause: (branchFlow, entryId) => branchMayPause(this.flows, this.flowCallKey, this.nodeExecutors, branchFlow, entryId), }; return traverseNext.call(host, node, flow, variables, context, steps, branchLabel); } From 90d4d51cb59e1affbc500ca15cbc1959eb56e3a1 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 03:26:48 +0000 Subject: [PATCH 06/14] test: type the request read's query options in the branch-pause pins Claude-Session: https://claude.ai/code/session_01QSeKYnrQ7UMtHofKQVjcH2 Co-authored-by: Claude --- .../plugins/plugin-approvals/src/flow-route.integration.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 0741e1d0a20..713c4d72955 100644 --- a/packages/plugins/plugin-approvals/src/flow-route.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/flow-route.integration.test.ts @@ -1088,7 +1088,7 @@ describe('[#38876] a branch whose subflow child parks, where the run cannot park return { record, result }; }; const requests = async (recordId: string): Promise => - (await engine.find('sys_approval_request', { where: { record_id: recordId }, context: SYSTEM } as any)) as any[]; + (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(); From db709f51fe20b751a40803b5aa4d05ca4d789e37 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 04:41:41 +0000 Subject: [PATCH 07/14] fix(automation): a branch pause never waits on its siblings; a late second pause fails the parked run Claude-Session: https://claude.ai/code/session_01QSeKYnrQ7UMtHofKQVjcH2 Co-authored-by: Claude --- .../src/branch-suspension-refusal.ts | 378 +++++++++++++----- .../service-automation/src/dag-traversal.ts | 29 +- .../service-automation/src/dry-run.ts | 3 - .../src/engine-run-facet.ts | 6 +- .../services/service-automation/src/engine.ts | 33 +- .../service-automation/src/run-resume.ts | 6 +- 6 files changed, 343 insertions(+), 112 deletions(-) diff --git a/packages/services/service-automation/src/branch-suspension-refusal.ts b/packages/services/service-automation/src/branch-suspension-refusal.ts index 9fca4ac366b..31fca24970c 100644 --- a/packages/services/service-automation/src/branch-suspension-refusal.ts +++ b/packages/services/service-automation/src/branch-suspension-refusal.ts @@ -1,13 +1,13 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -import { FLOW_PAUSE_CAPABLE_NODE_TYPES } from '@objectstack/spec/automation'; import type { FlowEdgeParsed, FlowNodeParsed, FlowParsed } from '@objectstack/spec/automation'; import type { DagTraversalHost } from './dag-traversal.js'; -import type { NodeExecutor } from './engine-node-contract.js'; +import type { AutomationEngine, SuspendedRun } from './engine.js'; +import { waitOfPausedRun } from './engine-resume.js'; +import { buildRunTrigger } from './engine-run-trigger.js'; import { isSuspendSignal, type FlowSuspendSignal } from './engine-signals.js'; import { markGuardRefusal } from './guard-refusal.js'; import { cancelParkedChild } from './parked-child-cancel.js'; -import { suspendingNode, type FlowCallKey } from './subflow-notice-guard.js'; +import { isRegionSuspensionRefusal } from './region-suspension-refusal.js'; +import { describeThrownForLog } from './thrown-cause-diagnostics.js'; /** * The "a branch's durable pause would drop another branch" refusal (#38876), @@ -45,29 +45,49 @@ import { suspendingNode, type FlowCallKey } from './subflow-notice-guard.js'; * `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, at the traversal, the first time - * a branch actually pauses where the run cannot park. + * 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 + * ## 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 first (`parked-child-cancel.ts`, the one copy the region refusal - * calls too), so no run is left parked under a caller that failed. + * 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 ({@link watchLateBranches}, armed by the + * three places that store a pause): when one of them later suspends too, or + * ends in this refusal or a region refusal, the PARKED run is failed after the + * fact — its suspension claimed as a resume claims it, a `failed` record + * written from its pause, its ancestors failed as a failed child fails them, + * and every child run the suspensions parked cancelled. A run a decision has + * already moved on is not touched; that is said at `error`, and the late + * child is cancelled. A sibling that never settles keeps nothing waiting: the + * run stays parked, as on base. 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. * - * ⛔ It does not make the engine resume the dropped continuation, nor - * serialise concurrent branches: that would change what a fan-out means. + * 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 have completed (concurrent), or the + * 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 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. + * 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 @@ -81,10 +101,12 @@ import { suspendingNode, type FlowCallKey } from './subflow-notice-guard.js'; * 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: the failed run keeps the - * `EXECUTION_ERROR` code every thrown failure carries, and the closed - * ADR-0112 ledger in `packages/spec` is not widened for it — the region - * refusal's choice, for its reason. + * ⛔ 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. */ @@ -167,8 +189,9 @@ function describeBranchSuspensionRefusal(facts: BranchSuspensionRefusalFacts): s `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 rather than parked at one of them, and every ' - + 'child run a `subflow` / `map` node of these branches parked is cancelled. Chain the pausing steps one ' + + '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.' ); @@ -219,105 +242,274 @@ async function refuse( const reason = `the run that started it failed at a branch that could not carry the pause: ${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 branches of one fan-out still running when its first suspension answered for it. */ +interface LateBranches { + readonly forkNodeId: string; + readonly flow: FlowParsed; + /** Every rejection after the first, in arrival order, once every branch has settled. */ + readonly rejections: Promise; +} + /** - * Whether a branch entered at `entryId` of `flow` may still pause the run, read - * over the engine's `flows`, its call-key resolver and its executor registry: a - * node reachable from it (along any edge of `flow`) whose executor declares - * `supportsPause` or whose type always pauses, or a `subflow` / `map` node - * whose child flow can suspend — read by `suspendingNode`, the reading the - * arming gate's region and save-notice halves take, so a call whose child - * never pauses does not count. A container's region body is not walked: a - * pause there is the region refusal, a failure, never a suspension. + * 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. */ -export function branchMayPause( - flows: ReadonlyMap, - flowCallKey: FlowCallKey, - nodeExecutors: ReadonlyMap, - flow: FlowParsed, - entryId: string, -): boolean { - const seen = new Set(); - const stack = [entryId]; - while (stack.length > 0) { - const id = stack.pop() as string; - if (seen.has(id)) continue; - seen.add(id); - const node = flow.nodes.find((n) => n.id === id); - if (!node) continue; - if (node.type === 'subflow' || node.type === 'map') { - const child = (node.config as { flowName?: unknown } | undefined)?.flowName; - if (typeof child === 'string' && child) { - const caller = typeof flow.name === 'string' ? flow.name : ''; - const key = flowCallKey(caller, child); - if (suspendingNode(flows, key, undefined, flowCallKey) !== undefined) return true; - } - } else if ( - FLOW_PAUSE_CAPABLE_NODE_TYPES.includes(node.type) - || nodeExecutors.get(node.type)?.descriptor?.supportsPause === true - ) { - return true; +const LATE_BRANCHES = new WeakMap(); + +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. 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 LATE_BRANCHES.get(signal) ?? []) cancelLateSuspensions(host, late.rejections, late.forkNodeId, reason); +} + +function cancelLateSuspensions( + host: CancelHost, + rejections: Promise, + forkNodeId: string, + reason: string, +): void { + void rejections.then(async (late) => { + for (const err of late) { + if (!isSuspendSignal(err)) continue; + await cancelParkedChild(host, err, `on a branch of node '${forkNodeId}' after the run had failed`, reason); + drainLateBranches(host, err, reason); } - for (const e of flow.edges) if (e.source === id) stack.push(e.target); - } - return false; + }); } /** - * Run a node's unconditional branches together, and keep a second suspension - * from being dropped behind the first. + * Run a node's unconditional branches together. * - * What is thrown is what `Promise.all` threw — the FIRST rejection to arrive, - * at the moment it arrives — with one exception. When that first rejection is - * a suspension and a branch still running MAY pause too (`mayPause`, the - * reading {@link branchMayPause} gives), the node waits for every branch to - * settle: two or more suspensions are the concurrent refusal, thrown once each - * parked child run is cancelled; one is the first suspension, re-thrown. + * 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: * - * So a fan-out whose other branches cannot pause answers exactly when it did - * (its synchronous siblings still finish after the run has answered `paused`, - * the timing the run-end readings of the approvals plugin are built on); only a - * fan-out with a second branch that may pause waits for it — the population - * that loses a branch when it does. + * - 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 {@link watchLateBranches}, which fails the parked run if one + * of them 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: Pick, + host: CancelHost, node: FlowNodeParsed, flow: FlowParsed, - branches: ReadonlyArray<{ readonly entryId: string; readonly run: Promise }>, - mayPause: (entryId: string) => boolean, + branches: ReadonlyArray>, ): Promise { - const done = branches.map(() => false); const rejections: unknown[] = []; let remaining = branches.length; let wake: () => void = () => {}; + let allSettled: () => void = () => {}; + const settled = new Promise((resolve) => { allSettled = resolve; }); const changed = (): Promise => new Promise((resolve) => { wake = resolve; }); - branches.forEach(({ run }, index) => { - run.then( - () => { done[index] = true; remaining--; wake(); }, - (err: unknown) => { done[index] = true; rejections.push(err); remaining--; wake(); }, - ); - }); + const settle = (): void => { + remaining--; + if (remaining === 0) allSettled(); + wake(); + }; + for (const run of branches) { + run.then(settle, (err: unknown) => { rejections.push(err); settle(); }); + } + if (branches.length === 0) allSettled(); while (remaining > 0 && rejections.length === 0) await changed(); if (rejections.length === 0) return; const first = rejections[0]; - if (!isSuspendSignal(first)) throw first; - // Branches that settled before this frame resumed are already in - // `rejections`; only one still running that may pause is waited for. - if (branches.some(({ entryId }, index) => !done[index] && mayPause(entryId))) { - while (remaining > 0) await changed(); + const collected = rejections.slice(1); + const rest = settled.then(() => rejections.slice(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, settled.then(() => rejections.slice(1)), node.id, reason(message)); + throw first; } - const signals = rejections.filter(isSuspendSignal); - if (signals.length < 2) throw first; - throw await refuse(host, signals, new FlowBranchSuspensionRefusalError({ + 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 once they settle. + const late = LATE_BRANCHES.get(first) ?? []; + late.push({ forkNodeId: node.id, flow, rejections: settled.then(() => rejections.slice(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: Promise, +): 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; +} + +/** What {@link watchLateBranches} reads and writes: the claim a resume takes, the failed record, the ancestor walk. */ +export interface LateBranchHost extends CancelHost { + readonly loadSuspendedRunStrict: AutomationEngine['loadSuspendedRunStrict']; + readonly claimAdvance: AutomationEngine['claimAdvance']; + readonly evictConsumedSuspension: AutomationEngine['evictConsumedSuspension']; + readonly forgetSuspendedRun: AutomationEngine['forgetSuspendedRun']; + readonly recordLog: AutomationEngine['recordLog']; + readonly failAncestors: AutomationEngine['failAncestors']; +} + +/** + * The body of `AutomationEngine.watchLateBranches`, armed by every place that + * stores a pause (`execute`, a retry attempt, a resume that parks again) right + * after it has stored it — so it never delays the pause, and a sibling that + * never settles leaves the run parked as base did. + * + * When a branch that was still running behind `signal` later suspends, or + * ends in a pause refusal (a branch or region refusal raised inside it), the + * parked run `runId` cannot carry it, and is failed: + * + * 1. the suspension is CLAIMED as a resume claims it; a run a decision has + * already moved on (`lost`, or no row) is not touched, and an `error` + * says the late branch's work was not carried; an unreadable store says + * so at `error` too; + * 2. a `failed` record is written from the stored pause (its step log ends + * at the node it parked on, as a run failed where it waited does), with + * the concurrent refusal — or the late refusal — as its error, and the + * run's ancestors are failed as a failed child run fails them; + * 3. every child run the suspensions parked, the stored one's included, is + * cancelled. + * + * #4632 verdict: the caller was answered `paused` and the run is now + * `failed`, so the answer it holds is stale: said once at `error`, naming the + * run and the refusal. + */ +export async function watchLateBranches(this: LateBranchHost, runId: string, signal: FlowSuspendSignal): Promise { + const entries = LATE_BRANCHES.get(signal); + if (!entries || entries.length === 0) return; + const settled = await Promise.all(entries.map(async (e) => ({ entry: e, late: await e.rejections }))); + const lateSignals: Array<{ entry: LateBranches; signal: FlowSuspendSignal }> = []; + let lateRefusal: Error | undefined; + for (const { entry, late } of settled) { + for (const err of late) { + if (isSuspendSignal(err)) lateSignals.push({ entry, signal: err }); + else if (lateRefusal === undefined && isPauseRefusal(err)) lateRefusal = err as Error; + } + } + if (lateSignals.length === 0 && lateRefusal === undefined) return; + const message = lateSignals.length > 0 + ? new FlowBranchSuspensionRefusalError({ + shape: 'concurrent', + forkNodeId: lateSignals[0].entry.forkNodeId, + suspended: [signal, ...lateSignals.map((l) => l.signal)].map((s) => suspendedNodeOf(lateSignals[0].entry.flow, s)), + untakenEdges: [], + }).message + : (lateRefusal as Error).message; + const reason = `the run that started it failed at a branch that could not carry the pause: ${message}`; + const failed = await failParkedRun(this, runId, message); + if (failed) { + await cancelParkedChild(this, signal, `on a branch of the run '${runId}'`, reason); + } + for (const { entry, signal: late } of lateSignals) { + await cancelParkedChild(this, late, `on a branch of node '${entry.forkNodeId}'`, reason); + drainLateBranches(this, late, reason); + } + this.logger.error( + failed + ? `[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: ${message}` + : `[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 moved on from that pause (a decision resumed it), so ` + + `nothing was failed and that branch's work is lost; its child run was cancelled: ${message}`, + ); +} + +/** Claim the stored pause of `runId` and fail the run where it waited; `false` when there is no pause left to fail. */ +async function failParkedRun(host: LateBranchHost, runId: string, error: string): Promise { + 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 false; + } + if (!run) return false; + const claim = await host.claimAdvance(run); + if (claim.kind === 'lost') { + host.evictConsumedSuspension(runId); + return false; + } + 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 false; + } + await host.forgetSuspendedRun(run, 'failed', claim.kind === 'claimed'); + 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); + await host.failAncestors(run.context, error); + return true; } /** diff --git a/packages/services/service-automation/src/dag-traversal.ts b/packages/services/service-automation/src/dag-traversal.ts index b406ad9531e..fd5c590c582 100644 --- a/packages/services/service-automation/src/dag-traversal.ts +++ b/packages/services/service-automation/src/dag-traversal.ts @@ -66,7 +66,7 @@ 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 { isBranchSuspensionRefusal, runConcurrentBranches, runSequentialBranch } from './branch-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'; @@ -213,8 +213,8 @@ export interface DagTraversalHost { readonly renderFlowTerminalMessage: AutomationEngine['renderFlowTerminalMessage']; readonly resolveSuspensionChainForCancel: AutomationEngine['resolveSuspensionChainForCancel']; readonly cancelRun: AutomationEngine['cancelRun']; - /** [#38876] Whether the branch entered at a node of `flow` may still pause (`branchMayPause`). */ - readonly branchMayPause: (flow: FlowParsed, entryId: string) => boolean; + /** [#38876] Arm the late-branch watch on a pause just stored (`watchLateBranches`). */ + readonly watchLateBranches: AutomationEngine['watchLateBranches']; } /** @@ -667,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, @@ -872,17 +872,17 @@ export async function traverseNext( } // Unconditional edges: execute in parallel. [#38876] The first rejection - // is thrown as `Promise.all` threw it, except that a suspension waits for - // the branches that may still pause, and two suspensions are the - // concurrent refusal rather than one kept and one dropped - // (`branch-suspension-refusal.ts`). + // 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 => ({ entryId: nextNode.id, run: this.executeNode(nextNode, flow, variables, context, steps) })); + .map(nextNode => this.executeNode(nextNode, flow, variables, context, steps)); - await runConcurrentBranches(this, node, flow, parallelTasks, (entryId) => this.branchMayPause(flow, entryId)); + await runConcurrentBranches(this, node, flow, parallelTasks); } } @@ -1013,6 +1013,10 @@ export async function runRegion( `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 @@ -1388,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 }, @@ -1689,6 +1693,9 @@ export async function executeWithoutRetry( steps, variables: variablesSnapshot, }, context); + // [#38876] Stored first; a branch still running beside the pause + // is judged once 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 282a3f7d492..b026de3191f 100644 --- a/packages/services/service-automation/src/dry-run.ts +++ b/packages/services/service-automation/src/dry-run.ts @@ -454,9 +454,6 @@ function traverseHost(state: DryRunState): ThisParameterType 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')), - // A dry run stops at its first pausing node and starts no child run, - // so a fan-out answers at its first stop, as it always has. - branchMayPause: () => false, }; } diff --git a/packages/services/service-automation/src/engine-run-facet.ts b/packages/services/service-automation/src/engine-run-facet.ts index 51c7ee85e8e..bd29ccb8c71 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 once 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 0a4c9a41f58..cb95cde9887 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -197,7 +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 { branchMayPause } from './branch-suspension-refusal.js'; +import { watchLateBranches } from './branch-suspension-refusal.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 @@ -308,6 +308,7 @@ export { missedRunId, } from './engine-run-trigger.js'; import { + type FlowSuspendSignal, type RefusalI18nService, type FlowTextSlotTranslation, type ChildRunRefusal, @@ -1220,6 +1221,31 @@ 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). 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. + */ + private watchLateBranches(runId: string, signal: FlowSuspendSignal): Promise { + // The body lives in ./branch-suspension-refusal.ts. + const host: ThisParameterType = { + loadSuspendedRunStrict: (...a) => this.loadSuspendedRunStrict(...a), + claimAdvance: (...a) => this.claimAdvance(...a), + evictConsumedSuspension: (...a) => this.evictConsumedSuspension(...a), + forgetSuspendedRun: (...a) => this.forgetSuspendedRun(...a), + recordLog: (...a) => this.recordLog(...a), + failAncestors: (...a) => this.failAncestors(...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 @@ -5182,6 +5208,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), @@ -6863,8 +6890,6 @@ export class AutomationEngine implements IAutomationService { executeNode: (...a) => this.executeNode(...a), resolveSuspensionChainForCancel: (...a) => this.resolveSuspensionChainForCancel(...a), cancelRun: (...a) => this.cancelRun(...a), - // [#38876] The body lives in ./branch-suspension-refusal.ts. - branchMayPause: (branchFlow, entryId) => branchMayPause(this.flows, this.flowCallKey, this.nodeExecutors, branchFlow, entryId), }; return traverseNext.call(host, node, flow, variables, context, steps, branchLabel); } @@ -7465,6 +7490,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), @@ -7703,6 +7729,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/run-resume.ts b/packages/services/service-automation/src/run-resume.ts index 33d45593028..1308595c367 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 @@ -2322,6 +2323,9 @@ export async function resumeInternal( steps, variables: variablesSnapshot, }, context); + // [#38876] Stored first; a branch still running beside the + // pause is judged once it settles, never waited on here. + void this.watchLateBranches(runId, err); return { success: true, status: 'paused', runId, durationMs, screen: err.screen, flowLabel: flow.label }; } From ec5911fd3b3de55acbe15efbafe1dceabb470a1a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 04:44:27 +0000 Subject: [PATCH 08/14] test(automation): pin the late branch refusal on the reviewer's shapes (N1, N2 both orders, P1b, N4, late region refusal) Claude-Session: https://claude.ai/code/session_01QSeKYnrQ7UMtHofKQVjcH2 Co-authored-by: Claude --- .../src/branch-suspension-refusal.test.ts | 208 ++++++++++++++++-- 1 file changed, 192 insertions(+), 16 deletions(-) diff --git a/packages/services/service-automation/src/branch-suspension-refusal.test.ts b/packages/services/service-automation/src/branch-suspension-refusal.test.ts index e6204301500..a32557ed8c8 100644 --- a/packages/services/service-automation/src/branch-suspension-refusal.test.ts +++ b/packages/services/service-automation/src/branch-suspension-refusal.test.ts @@ -4,12 +4,20 @@ // `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 a timer child: 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. +// 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 { @@ -29,7 +37,8 @@ function rig() { const logger: any = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; logger.child = () => logger; const engine = withLoaderSetFromPull(new AutomationEngine(logger)); - engine.setSuspendedRunStore(new InMemorySuspendedRunStore()); + const store = new InMemorySuspendedRunStore(); + engine.setSuspendedRunStore(store); const ctx = { logger, getService: () => undefined } as any; for (const register of [ registerSubflowNode, registerMapNode, registerLoopNode, registerParallelNode, @@ -37,7 +46,27 @@ function rig() { ]) { (register as (e: AutomationEngine, c: unknown) => void)(engine, ctx); } - return { engine, logger }; + // `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); + return { engine, logger, store, release }; } type Node = Record; @@ -47,13 +76,20 @@ 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, { id: 'hold', type: 'wait', label: 'Hold', waitEventConfig: { eventType: 'timer', timerDuration: 'PT1H' } }, end('done')], + nodes: [START, WAIT('hold'), end('done')], edges: [edge('h1', 'start', 'hold'), edge('h2', 'hold', 'done')], }; +/** A child that runs straight through. */ +const PLAIN = { + name: 'deal_plain', label: 'Plain', type: 'autolaunched', + nodes: [START, node('p1'), end('done')], + edges: [edge('p0', 'start', 'p1'), edge('p2', 'p1', 'done')], +}; const flow = (name: string, nodes: Node[], edges: Array>) => ({ name, label: name, type: 'autolaunched', nodes, edges }); @@ -70,6 +106,41 @@ const SEQUENTIAL = flow('deal_sequential', [START, node('x1'), call('sub'), node 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 = { @@ -82,20 +153,44 @@ const inRegion = (kind: 'parallel' | 'try_catch') => { 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 result: any = await engine.execute(FAN_OUT.name, {} as any); - expect(result).toMatchObject({ success: false, status: 'failed' }); - expect(result.error).toContain("durable pause on concurrent branches: node 'start'"); - expect(result.error).toContain("node 'sub_a' (sub-flow 'deal_hold')"); - expect(result.error).toContain("node 'sub_b' (sub-flow 'deal_hold')"); - expect(await engine.listSuspendedRunsDurable(), 'nothing is left parked').toEqual([]); + 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, and the sibling never runs', async () => { + 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); @@ -103,7 +198,7 @@ describe('[#38876] the branch refusal on the engine', () => { 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 engine.listSuspendedRunsDurable()).toEqual([]); + 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)', () => { @@ -128,7 +223,86 @@ describe('[#38876] the branch refusal on the engine', () => { 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 engine.listSuspendedRunsDurable(), 'both children are cancelled').toEqual([]); + 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('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 may pause and does not parks with the step log ending at the wait, as on base', async () => { + const { engine, store } = rig(); + engine.registerFlow(PLAIN.name, PLAIN); + const shape = flow('deal_p1b', [START, node('fork'), WAIT('hold'), call('sub', 'deal_plain'), 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 () => { @@ -140,7 +314,9 @@ describe('[#38876] the branch refusal on the engine', () => { 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'])); }); From 4d410241a1ad8be6ab53a299d44fc1f7133d518b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 04:45:06 +0000 Subject: [PATCH 09/14] test(automation): P1b's child can park and does not Claude-Session: https://claude.ai/code/session_01QSeKYnrQ7UMtHofKQVjcH2 Co-authored-by: Claude --- .../src/branch-suspension-refusal.test.ts | 21 ++++++++++++------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/packages/services/service-automation/src/branch-suspension-refusal.test.ts b/packages/services/service-automation/src/branch-suspension-refusal.test.ts index a32557ed8c8..d0e4a9b14c3 100644 --- a/packages/services/service-automation/src/branch-suspension-refusal.test.ts +++ b/packages/services/service-automation/src/branch-suspension-refusal.test.ts @@ -84,11 +84,16 @@ const HOLD = { nodes: [START, WAIT('hold'), end('done')], edges: [edge('h1', 'start', 'hold'), edge('h2', 'hold', 'done')], }; -/** A child that runs straight through. */ -const PLAIN = { - name: 'deal_plain', label: 'Plain', type: 'autolaunched', - nodes: [START, node('p1'), end('done')], - edges: [edge('p0', 'start', 'p1'), edge('p2', 'p1', '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 }); @@ -277,10 +282,10 @@ describe('[#38876] the branch refusal on the engine', () => { expect(await parkedAfterSettling(engine)).toEqual([]); }); - it('P1b: a wait beside a call whose child may pause and does not parks with the step log ending at the wait, as on base', async () => { + 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(PLAIN.name, PLAIN); - const shape = flow('deal_p1b', [START, node('fork'), WAIT('hold'), call('sub', 'deal_plain'), node('s_after'), end('h_done'), end('s_done')], [ + 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'), ]); From 25fe7cd61c90ac7734528d9f4c4aff9aa0fa180c Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 04:47:04 +0000 Subject: [PATCH 10/14] test(plugin-approvals): the approval rig reads a late refusal, and pins the reviewer's M1 in both arrival orders Claude-Session: https://claude.ai/code/session_01QSeKYnrQ7UMtHofKQVjcH2 Co-authored-by: Claude --- .../src/flow-route.integration.test.ts | 121 +++++++++++++++--- 1 file changed, 103 insertions(+), 18 deletions(-) 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 713c4d72955..f03a37b47d7 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'; @@ -1078,6 +1079,15 @@ describe('[#38876] a branch whose subflow child parks, where the run cannot park automation.setSuspendedRunStore(new InMemorySuspendedRunStore()); 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); for (const flow of flows) automation.registerFlow(flow.name, flow); return { svc, automation }; }; @@ -1098,16 +1108,32 @@ describe('[#38876] a branch whose subflow child parks, where the run cannot park 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) => { - expect(result.success).toBe(false); - expect(result.status).toBe('failed'); - expect(result.error).toContain(lead); + 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) { - expect(await automation.hasSuspendedRun(runId), `run ${runId} is not left parked`).toBe(false); + 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; + return { runs, error: String(run.error) }; }; /** One approval, run as the `subflow` / `map` body: the child parks on it. */ @@ -1224,13 +1250,48 @@ describe('[#38876] a branch whose subflow child parks, where the run cannot park ], }); + /** + * 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' }, + ], + }); + 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'); - await expectRefused(automation, record.id, result, CONCURRENT); - expect(result.error).toContain("node 'a_review', node 'sub' (sub-flow 'branch_parking_child')"); + 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'); }); @@ -1238,8 +1299,8 @@ describe('[#38876] a branch whose subflow child parks, where the run cannot park 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'); - await expectRefused(automation, record.id, result, CONCURRENT); - expect(result.error).toContain("node 'sub' (sub-flow 'branch_parking_child')"); + 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'); }); @@ -1247,28 +1308,52 @@ describe('[#38876] a branch whose subflow child parks, where the run cannot park 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 [approvalChild] = await expectRefused(automation, record.id, result, CONCURRENT); - expect(result.error).toContain("(sub-flow 'branch_parking_child')"); - expect(result.error).toContain("(sub-flow 'branch_waiting_child')"); + 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'); - const parked = (await automation.listSuspendedRunsDurable()).map((r) => r.flowName); + 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 [child] = await expectRefused(automation, record.id, result, "durable pause before a later branch: node 'x1' took edge 'c1'"); - expect(result.error).toContain("node 'sub' (sub-flow 'branch_parking_child') suspended on that branch"); - expect(result.error).toContain("edge 'c2' ('x1' → 's_sync')"); + 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'); - await expectRefused(automation, record.id, result, "durable pause before a later branch: node 'x1' took edge 'c1'"); - expect(result.error).toContain("edge 'c2' ('x1' → 's_sync')"); + 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('CONTROL: one pausing branch (the subflow) beside a synchronous one parks, and the child\'s decision runs the work after it', async () => { From b37738319cd39a12c1819e83ff3acac69d78dd43 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 04:48:36 +0000 Subject: [PATCH 11/14] docs(automation): say when the branch refusal fires; correct the step-code and plugin-type sentences Claude-Session: https://claude.ai/code/session_01QSeKYnrQ7UMtHofKQVjcH2 Co-authored-by: Claude --- .../38876-subflow-branch-pause-refusal.md | 10 ++++--- content/docs/automation/flows.mdx | 30 ++++++++++++------- .../src/branch-suspension-refusal.test.ts | 17 +++++++++++ 3 files changed, 43 insertions(+), 14 deletions(-) diff --git a/.changeset/38876-subflow-branch-pause-refusal.md b/.changeset/38876-subflow-branch-pause-refusal.md index 0ead1800a7e..acdf474a067 100644 --- a/.changeset/38876-subflow-branch-pause-refusal.md +++ b/.changeset/38876-subflow-branch-pause-refusal.md @@ -12,13 +12,15 @@ A run parks at one place, and a resumed run continues from the step that parked, - **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 the first time the shape happens, with a named error, and cancels every child run a refused `subflow` / `map` started, so nothing is left parked: +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, and it keeps the `EXECUTION_ERROR` step code every thrown failure carries. Inside a `loop`, `parallel` or `try_catch` body the region error is raised instead, as for any pause there. +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. -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 fan-out answers as soon as its first branch pauses, as before, unless another branch still running may pause too (it reaches a step that pauses, or a `subflow` / `map` whose child flow can): only then does it wait for its branches to settle, to see whether a second one pauses. +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. A branch that pauses too afterwards, or ends in this error or the region error, fails the run that had answered `paused`: its pause is withdrawn the way a resume claims it, 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, and the child runs are cancelled. A pause the run had already resumed from by then is left alone, and the lost branch is logged at `error`. 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. -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`, and an administrator recalls it to release the record. +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 2327d2970e3..d5830d963f2 100644 --- a/content/docs/automation/flows.mdx +++ b/content/docs/automation/flows.mdx @@ -1791,9 +1791,9 @@ 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 the first time a branch actually -pauses, a child flow that parks included, and fails the run with a named error -instead of keeping one pause and dropping the rest: +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 @@ -1806,16 +1806,26 @@ instead of keeping one pause and dropping the rest: 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. When one of +them pauses too afterwards, or meets one of these errors or the region error, +the run that had answered `paused` is failed then: its pause is withdrawn, its +record turns `failed` with the error, and a parent flow waiting on it as a +`subflow` fails with it. A pause the run had already resumed from by then is +left alone, and the engine logs the lost branch at `error`. + 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`; -an administrator recalls it to release the record. 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. +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/services/service-automation/src/branch-suspension-refusal.test.ts b/packages/services/service-automation/src/branch-suspension-refusal.test.ts index d0e4a9b14c3..1a3cab34546 100644 --- a/packages/services/service-automation/src/branch-suspension-refusal.test.ts +++ b/packages/services/service-automation/src/branch-suspension-refusal.test.ts @@ -248,6 +248,23 @@ describe('[#38876] the branch refusal on the engine', () => { .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); From f7912ecccffdaa8372243e0504570211d04e0c06 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 06:51:00 +0000 Subject: [PATCH 12/14] fix(automation): the late branch failure binds to the pause it watched The watch that fails a run after it answered `paused` now acts on the pause it was armed for, not on the run id: it enters the in-process resume gate (waiting its turn), leaves a run no longer parked at the watched node and correlation alone, and claims against that pause. It acts on the first late suspension or pause refusal instead of once every branch has settled. A parent whose own pause is not yet stored when the ancestor walk reads it is handed the failure and fails itself from its store step. The watch never rejects, its terminal write is guarded, and its log line says what happened. Pins: re-park on a wait and on a call, resume wins, two late branches, a never-settling sibling, the gate with no store, a parent and grandparent under a slow save, ObjectStore-shaped jitter, a throwing history sink, a store that cannot be read or claimed; on the approval rig the b_review re-park in both late shapes and resume wins. Claude-Session: https://claude.ai/code/session_01QSeKYnrQ7UMtHofKQVjcH2 Co-authored-by: Claude --- .../38876-subflow-branch-pause-refusal.md | 2 +- content/docs/automation/flows.mdx | 16 +- .../src/flow-route.integration.test.ts | 104 ++++- .../src/branch-suspension-refusal.test.ts | 301 +++++++++++++- .../src/branch-suspension-refusal.ts | 246 ++++------- .../service-automation/src/dag-traversal.ts | 2 +- .../src/engine-run-facet.ts | 2 +- .../services/service-automation/src/engine.ts | 47 ++- .../src/late-branch-watch.ts | 391 ++++++++++++++++++ .../service-automation/src/run-resume.ts | 2 +- 10 files changed, 917 insertions(+), 196 deletions(-) create mode 100644 packages/services/service-automation/src/late-branch-watch.ts diff --git a/.changeset/38876-subflow-branch-pause-refusal.md b/.changeset/38876-subflow-branch-pause-refusal.md index acdf474a067..3c6ae93895c 100644 --- a/.changeset/38876-subflow-branch-pause-refusal.md +++ b/.changeset/38876-subflow-branch-pause-refusal.md @@ -19,7 +19,7 @@ The engine now fails such a run with a named error on the pauses that actually h 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. A branch that pauses too afterwards, or ends in this error or the region error, fails the run that had answered `paused`: its pause is withdrawn the way a resume claims it, 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, and the child runs are cancelled. A pause the run had already resumed from by then is left alone, and the lost branch is logged at `error`. 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. +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. 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. diff --git a/content/docs/automation/flows.mdx b/content/docs/automation/flows.mdx index d5830d963f2..cc4243e2d67 100644 --- a/content/docs/automation/flows.mdx +++ b/content/docs/automation/flows.mdx @@ -1807,12 +1807,16 @@ run with a named error instead of keeping one pause and dropping the rest: 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. When one of -them pauses too afterwards, or meets one of these errors or the region error, -the run that had answered `paused` is failed then: its pause is withdrawn, its -record turns `failed` with the error, and a parent flow waiting on it as a -`subflow` fails with it. A pause the run had already resumed from by then is -left alone, and the engine logs the lost branch at `error`. +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. 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 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 f03a37b47d7..334445f0b9b 100644 --- a/packages/plugins/plugin-approvals/src/flow-route.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/flow-route.integration.test.ts @@ -1074,7 +1074,8 @@ describe('[#38876] a branch whose subflow child parks, where the run cannot park /** A fresh engine with the built-ins, the approval node and `flows` registered: the door a published flow reaches. */ const bootEngine = (...flows: any[]) => { const svc = new ApprovalService({ engine: engine as any, clock: { now: () => new Date(now += 1000) }, logger: silent }); - const automation = new AutomationEngine(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(new InMemorySuspendedRunStore()); svc.attachAutomation(automation as any); @@ -1088,8 +1089,19 @@ describe('[#38876] a branch whose subflow child parks, where the run cannot park 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 }; + 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 }; @@ -1284,6 +1296,60 @@ describe('[#38876] a branch whose subflow child parks, where the run cannot park ], }); + /** + * 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 () => { @@ -1356,6 +1422,40 @@ describe('[#38876] a branch whose subflow child parks, where the run cannot park } }); + 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('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)); diff --git a/packages/services/service-automation/src/branch-suspension-refusal.test.ts b/packages/services/service-automation/src/branch-suspension-refusal.test.ts index 1a3cab34546..8399d1cbfbb 100644 --- a/packages/services/service-automation/src/branch-suspension-refusal.test.ts +++ b/packages/services/service-automation/src/branch-suspension-refusal.test.ts @@ -33,12 +33,12 @@ import { FlowBranchSuspensionRefusalError, isBranchSuspensionRefusal } from './b import { isGuardRefusal } from './guard-refusal.js'; import { withLoaderSetFromPull } from './loader-set.test-support.js'; -function rig() { +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 = new InMemorySuspendedRunStore(); - engine.setSuspendedRunStore(store); + 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, @@ -66,7 +66,30 @@ function rig() { return { success: true }; }, } as any); - return { engine, logger, store, release }; + // `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; @@ -343,3 +366,273 @@ describe('[#38876] the branch refusal on the engine', () => { .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 Set; + 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); + }); +}); + +/** 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.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 index 31fca24970c..743a77d7085 100644 --- a/packages/services/service-automation/src/branch-suspension-refusal.ts +++ b/packages/services/service-automation/src/branch-suspension-refusal.ts @@ -1,13 +1,9 @@ import type { FlowEdgeParsed, FlowNodeParsed, FlowParsed } from '@objectstack/spec/automation'; import type { DagTraversalHost } from './dag-traversal.js'; -import type { AutomationEngine, SuspendedRun } from './engine.js'; -import { waitOfPausedRun } from './engine-resume.js'; -import { buildRunTrigger } from './engine-run-trigger.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'; -import { describeThrownForLog } from './thrown-cause-diagnostics.js'; /** * The "a branch's durable pause would drop another branch" refusal (#38876), @@ -62,19 +58,24 @@ import { describeThrownForLog } from './thrown-cause-diagnostics.js'; * 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 ({@link watchLateBranches}, armed by the - * three places that store a pause): when one of them later suspends too, or - * ends in this refusal or a region refusal, the PARKED run is failed after the - * fact — its suspension claimed as a resume claims it, a `failed` record - * written from its pause, its ancestors failed as a failed child fails them, - * and every child run the suspensions parked cancelled. A run a decision has - * already moved on is not touched; that is said at `error`, and the late - * child is cancelled. A sibling that never settles keeps nothing waiting: the - * run stays parked, as on base. 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. + * 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 @@ -254,12 +255,20 @@ 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. */ -interface LateBranches { +export interface LateBranches { readonly forkNodeId: string; readonly flow: FlowParsed; - /** Every rejection after the first, in arrival order, once every branch has settled. */ - readonly rejections: Promise; + /** Every rejection after the first, each as it arrives. */ + readonly feed: LateFeed; } /** @@ -269,30 +278,29 @@ interface LateBranches { */ const LATE_BRANCHES = new WeakMap(); -type CancelHost = Pick; +/** 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. Never awaited by the traversal; every failure inside - * is logged by {@link cancelParkedChild}. + * 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 LATE_BRANCHES.get(signal) ?? []) cancelLateSuspensions(host, late.rejections, late.forkNodeId, reason); + for (const late of lateBranchesOf(signal)) cancelLateSuspensions(host, late.feed, late.forkNodeId, reason); } -function cancelLateSuspensions( - host: CancelHost, - rejections: Promise, - forkNodeId: string, - reason: string, -): void { - void rejections.then(async (late) => { - for (const err of late) { - if (!isSuspendSignal(err)) continue; - await cancelParkedChild(host, err, `on a branch of node '${forkNodeId}' after the run had failed`, reason); - drainLateBranches(host, err, 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)); }); } @@ -305,8 +313,9 @@ function cancelLateSuspensions( * * - 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 {@link watchLateBranches}, which fails the parked run if one - * of them later suspends or ends in a pause refusal; + * 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 @@ -321,31 +330,40 @@ export async function runConcurrentBranches( branches: ReadonlyArray>, ): Promise { const rejections: unknown[] = []; + const listeners: Array<(err: unknown) => void> = []; let remaining = branches.length; let wake: () => void = () => {}; - let allSettled: () => void = () => {}; - const settled = new Promise((resolve) => { allSettled = resolve; }); const changed = (): Promise => new Promise((resolve) => { wake = resolve; }); const settle = (): void => { remaining--; - if (remaining === 0) allSettled(); wake(); }; for (const run of branches) { - run.then(settle, (err: unknown) => { rejections.push(err); settle(); }); + run.then(settle, (err: unknown) => { + rejections.push(err); + for (const listener of listeners) listener(err); + settle(); + }); } - if (branches.length === 0) allSettled(); + /** 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 = settled.then(() => rejections.slice(1 + collected.length)); + 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, settled.then(() => rejections.slice(1)), node.id, reason(message)); + 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); @@ -361,9 +379,9 @@ export async function runConcurrentBranches( throw collectedRefusal; } // Nothing collected but the suspension: the run parks on it now, and the - // branches still running are judged once they settle. + // branches still running are judged as they settle. const late = LATE_BRANCHES.get(first) ?? []; - late.push({ forkNodeId: node.id, flow, rejections: settled.then(() => rejections.slice(1)) }); + late.push({ forkNodeId: node.id, flow, feed: feedFrom(1) }); LATE_BRANCHES.set(first, late); throw first; } @@ -374,7 +392,7 @@ async function refuseConcurrent( node: FlowNodeParsed, flow: FlowParsed, signals: readonly FlowSuspendSignal[], - rest: Promise, + rest: LateFeed, ): Promise { const refusal = await refuse(host, signals, new FlowBranchSuspensionRefusalError({ shape: 'concurrent', @@ -386,130 +404,14 @@ async function refuseConcurrent( return refusal; } -/** What {@link watchLateBranches} reads and writes: the claim a resume takes, the failed record, the ancestor walk. */ -export interface LateBranchHost extends CancelHost { - readonly loadSuspendedRunStrict: AutomationEngine['loadSuspendedRunStrict']; - readonly claimAdvance: AutomationEngine['claimAdvance']; - readonly evictConsumedSuspension: AutomationEngine['evictConsumedSuspension']; - readonly forgetSuspendedRun: AutomationEngine['forgetSuspendedRun']; - readonly recordLog: AutomationEngine['recordLog']; - readonly failAncestors: AutomationEngine['failAncestors']; -} - -/** - * The body of `AutomationEngine.watchLateBranches`, armed by every place that - * stores a pause (`execute`, a retry attempt, a resume that parks again) right - * after it has stored it — so it never delays the pause, and a sibling that - * never settles leaves the run parked as base did. - * - * When a branch that was still running behind `signal` later suspends, or - * ends in a pause refusal (a branch or region refusal raised inside it), the - * parked run `runId` cannot carry it, and is failed: - * - * 1. the suspension is CLAIMED as a resume claims it; a run a decision has - * already moved on (`lost`, or no row) is not touched, and an `error` - * says the late branch's work was not carried; an unreadable store says - * so at `error` too; - * 2. a `failed` record is written from the stored pause (its step log ends - * at the node it parked on, as a run failed where it waited does), with - * the concurrent refusal — or the late refusal — as its error, and the - * run's ancestors are failed as a failed child run fails them; - * 3. every child run the suspensions parked, the stored one's included, is - * cancelled. - * - * #4632 verdict: the caller was answered `paused` and the run is now - * `failed`, so the answer it holds is stale: said once at `error`, naming the - * run and the refusal. - */ -export async function watchLateBranches(this: LateBranchHost, runId: string, signal: FlowSuspendSignal): Promise { - const entries = LATE_BRANCHES.get(signal); - if (!entries || entries.length === 0) return; - const settled = await Promise.all(entries.map(async (e) => ({ entry: e, late: await e.rejections }))); - const lateSignals: Array<{ entry: LateBranches; signal: FlowSuspendSignal }> = []; - let lateRefusal: Error | undefined; - for (const { entry, late } of settled) { - for (const err of late) { - if (isSuspendSignal(err)) lateSignals.push({ entry, signal: err }); - else if (lateRefusal === undefined && isPauseRefusal(err)) lateRefusal = err as Error; - } - } - if (lateSignals.length === 0 && lateRefusal === undefined) return; - const message = lateSignals.length > 0 - ? new FlowBranchSuspensionRefusalError({ - shape: 'concurrent', - forkNodeId: lateSignals[0].entry.forkNodeId, - suspended: [signal, ...lateSignals.map((l) => l.signal)].map((s) => suspendedNodeOf(lateSignals[0].entry.flow, s)), - untakenEdges: [], - }).message - : (lateRefusal as Error).message; - const reason = `the run that started it failed at a branch that could not carry the pause: ${message}`; - const failed = await failParkedRun(this, runId, message); - if (failed) { - await cancelParkedChild(this, signal, `on a branch of the run '${runId}'`, reason); - } - for (const { entry, signal: late } of lateSignals) { - await cancelParkedChild(this, late, `on a branch of node '${entry.forkNodeId}'`, reason); - drainLateBranches(this, late, reason); - } - this.logger.error( - failed - ? `[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: ${message}` - : `[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 moved on from that pause (a decision resumed it), so ` + - `nothing was failed and that branch's work is lost; its child run was cancelled: ${message}`, - ); -} - -/** Claim the stored pause of `runId` and fail the run where it waited; `false` when there is no pause left to fail. */ -async function failParkedRun(host: LateBranchHost, runId: string, error: string): Promise { - 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 false; - } - if (!run) return false; - const claim = await host.claimAdvance(run); - if (claim.kind === 'lost') { - host.evictConsumedSuspension(runId); - return false; - } - 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 false; - } - await host.forgetSuspendedRun(run, 'failed', claim.kind === 'claimed'); - 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); - await host.failAncestors(run.context, error); - return true; +/** 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; } /** diff --git a/packages/services/service-automation/src/dag-traversal.ts b/packages/services/service-automation/src/dag-traversal.ts index fd5c590c582..5a6cdad716b 100644 --- a/packages/services/service-automation/src/dag-traversal.ts +++ b/packages/services/service-automation/src/dag-traversal.ts @@ -1694,7 +1694,7 @@ export async function executeWithoutRetry( variables: variablesSnapshot, }, context); // [#38876] Stored first; a branch still running beside the pause - // is judged once it settles, never waited on here. + // is judged as it settles, never waited on here. void this.watchLateBranches(runId, err); return { success: true, diff --git a/packages/services/service-automation/src/engine-run-facet.ts b/packages/services/service-automation/src/engine-run-facet.ts index bd29ccb8c71..4af013bae7a 100644 --- a/packages/services/service-automation/src/engine-run-facet.ts +++ b/packages/services/service-automation/src/engine-run-facet.ts @@ -612,7 +612,7 @@ export class RunFacet { variables: variablesSnapshot, }, context); // [#38876] Stored first; a branch still running beside the - // pause is judged once it settles, never waited on here. + // pause is judged as it settles, never waited on here. void this.watchLateBranches(runId, err); return { success: true, diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index cb95cde9887..589f3c877b8 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -197,7 +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 { watchLateBranches } from './branch-suspension-refusal.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 @@ -888,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 @@ -1226,24 +1234,47 @@ export class AutomationEngine implements IAutomationService { * 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). 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. + * 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 ./branch-suspension-refusal.ts. + // 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), - failAncestors: (...a) => this.failAncestors(...a), resolveSuspensionChainForCancel: (...a) => this.resolveSuspensionChainForCancel(...a), cancelRun: (...a) => this.cancelRun(...a), logger: this.logger, }; - return watchLateBranches.call(host, runId, signal); + 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 watchLateBranches.call(host, runId, signal).catch(fault); + } catch (err) { + fault(err); + return Promise.resolve(); + } } /** 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..6f5ffbe2911 --- /dev/null +++ b/packages/services/service-automation/src/late-branch-watch.ts @@ -0,0 +1,391 @@ +// 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); + * 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; + * 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, as before, plus a way to wait for one to be let + * go. `resume` still only asks `has` and answers `RESUME_IN_PROGRESS`; the + * late-branch watch waits its turn instead, since nobody retries it. + */ +export class ResumeGate extends Set { + private readonly waiters = new Map void>>(); + + override delete(runId: string): boolean { + const held = super.delete(runId); + const waiting = this.waiters.get(runId); + if (waiting) { + this.waiters.delete(runId); + for (const wake of waiting) wake(); + } + return held; + } + + /** Resolves once `runId` is not held (at once when it is not). */ + whenFree(runId: string): Promise { + if (!this.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`, 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.add(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. + */ +export function watchLateBranches(this: LateBranchHost, runId: string, signal: FlowSuspendSignal): Promise { + const work: Array> = []; + const descendant = takePendingAncestorFailure(this, runId, signal); + if (descendant !== undefined) work.push(failForDescendant(this, runId, signal, descendant)); + const entries = lateBranchesOf(signal); + if (entries.length > 0) work.push(watchEntries(this, 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'; + } + 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); + } + await failAncestorsAfterLateFailure(host, failedRun, ancestorError); + 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/run-resume.ts b/packages/services/service-automation/src/run-resume.ts index 1308595c367..598c6e1bffa 100644 --- a/packages/services/service-automation/src/run-resume.ts +++ b/packages/services/service-automation/src/run-resume.ts @@ -2324,7 +2324,7 @@ export async function resumeInternal( variables: variablesSnapshot, }, context); // [#38876] Stored first; a branch still running beside the - // pause is judged once it settles, never waited on here. + // 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 }; } From 162712650aca6f32d314d5fba81f78f11bf2d735 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 07:29:25 +0000 Subject: [PATCH 13/14] fix(automation): the engine's watch member is one forwarding call again; the resume gate holds its set The fault handler of the late-branch watch moves into late-branch-watch.ts, so `AutomationEngine.watchLateBranches` delegates in one call (check:facade-delegation-only). `ResumeGate` keeps its run ids in a set of its own instead of extending `Set`, so no `super.delete()` reads as an unplaced write (check-tenant-audit-census). Claude-Session: https://claude.ai/code/session_01QSeKYnrQ7UMtHofKQVjcH2 Co-authored-by: Claude --- .../src/branch-suspension-refusal.test.ts | 2 +- .../services/service-automation/src/engine.ts | 18 +----- .../src/late-branch-watch.ts | 56 +++++++++++++++---- 3 files changed, 46 insertions(+), 30 deletions(-) diff --git a/packages/services/service-automation/src/branch-suspension-refusal.test.ts b/packages/services/service-automation/src/branch-suspension-refusal.test.ts index 8399d1cbfbb..0b6dc2a598e 100644 --- a/packages/services/service-automation/src/branch-suspension-refusal.test.ts +++ b/packages/services/service-automation/src/branch-suspension-refusal.test.ts @@ -483,7 +483,7 @@ describe('[#38876] the late failure binds to the pause it watched (race arms, pi 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 Set; + 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); diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index 589f3c877b8..e5f5ef04e0f 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -1258,23 +1258,7 @@ export class AutomationEngine implements IAutomationService { cancelRun: (...a) => this.cancelRun(...a), logger: this.logger, }; - 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 watchLateBranches.call(host, runId, signal).catch(fault); - } catch (err) { - fault(err); - return Promise.resolve(); - } + return watchLateBranches.call(host, runId, signal); } /** diff --git a/packages/services/service-automation/src/late-branch-watch.ts b/packages/services/service-automation/src/late-branch-watch.ts index 6f5ffbe2911..e7d9d4e6f7a 100644 --- a/packages/services/service-automation/src/late-branch-watch.ts +++ b/packages/services/service-automation/src/late-branch-watch.ts @@ -75,27 +75,37 @@ import { cancelParkedChild, type ParkedChildSuspension } from './parked-child-ca 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, as before, plus a way to wait for one to be let - * go. `resume` still only asks `has` and answers `RESUME_IN_PROGRESS`; the + * 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. `resume` still only asks `has` and answers `RESUME_IN_PROGRESS`; the * late-branch watch waits its turn instead, since nobody retries it. */ -export class ResumeGate extends Set { +export class ResumeGate { + private readonly held = new Set(); private readonly waiters = new Map void>>(); - override delete(runId: string): boolean { - const held = super.delete(runId); + 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); const waiting = this.waiters.get(runId); if (waiting) { this.waiters.delete(runId); for (const wake of waiting) wake(); } - return held; + return wasHeld; } /** Resolves once `runId` is not held (at once when it is not). */ whenFree(runId: string): Promise { - if (!this.has(runId)) return Promise.resolve(); + if (!this.held.has(runId)) return Promise.resolve(); return new Promise((resolve) => { const waiting = this.waiters.get(runId) ?? []; waiting.push(resolve); @@ -144,14 +154,36 @@ export interface LateBranchHost extends CancelHost { * 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. + * 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(this, runId, signal); - if (descendant !== undefined) work.push(failForDescendant(this, runId, signal, descendant)); + 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(this, runId, signal, entries)); + if (entries.length > 0) work.push(watchEntries(host, runId, signal, entries)); return Promise.all(work).then(() => undefined); } From bb04e46ae6ce41029fe996701a4afa64700babad Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 08:29:22 +0000 Subject: [PATCH 14/14] fix(automation): a resume that meets the late watch mid-read waits instead of being refused The late-branch watch takes the run's resume gate before it has read whether the run is still at the pause it watched. A resume that met it there was answered RESUME_IN_PROGRESS and never retried, so a child's bubble or an approval decision on a run the watch then left alone was lost: the parent stayed parked on a completed child, the decided request's flow never moved. The gate now knows when the watch holds it undecided. A resume that meets it then waits for the watch's read and claim (never for a release hook), goes on when the watch leaves the run alone, and is refused as before once the watch has claimed the pause. The ancestor walk's failure no longer skips the late child cancels, and a refused branch's child is cancelled with a reason that stays true when the run has moved on. Pins: the child's bubble and the b_review decision with the watch's store read held in flight, the at-pause arm under the same hold, and a sink that throws on the parent's terminal write only. Claude-Session: https://claude.ai/code/session_01QSeKYnrQ7UMtHofKQVjcH2 Co-authored-by: Claude --- .../38876-subflow-branch-pause-refusal.md | 2 +- content/docs/automation/flows.mdx | 4 +- .../src/flow-route.integration.test.ts | 50 +++++++++- .../src/branch-suspension-refusal.test.ts | 96 +++++++++++++++++++ .../src/branch-suspension-refusal.ts | 6 +- .../src/late-branch-watch.ts | 76 +++++++++++++-- .../service-automation/src/run-resume.ts | 5 + 7 files changed, 227 insertions(+), 12 deletions(-) diff --git a/.changeset/38876-subflow-branch-pause-refusal.md b/.changeset/38876-subflow-branch-pause-refusal.md index 3c6ae93895c..1d55ee8c8f1 100644 --- a/.changeset/38876-subflow-branch-pause-refusal.md +++ b/.changeset/38876-subflow-branch-pause-refusal.md @@ -19,7 +19,7 @@ The engine now fails such a run with a named error on the pauses that actually h 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. 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. +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. diff --git a/content/docs/automation/flows.mdx b/content/docs/automation/flows.mdx index cc4243e2d67..46bc7ff3f74 100644 --- a/content/docs/automation/flows.mdx +++ b/content/docs/automation/flows.mdx @@ -1815,7 +1815,9 @@ 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. This check runs in the engine's memory, so an engine restarted +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 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 334445f0b9b..2ad42cd7a9f 100644 --- a/packages/plugins/plugin-approvals/src/flow-route.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/flow-route.integration.test.ts @@ -1018,6 +1018,28 @@ describe('[#38875] a branch that parks the run, taken before a sibling, is refus }); }); +/** 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 @@ -1072,12 +1094,13 @@ describe('[#38876] a branch whose subflow child parks, where the run cannot park } /** A fresh engine with the built-ins, the approval node and `flows` registered: the door a published flow reaches. */ - const bootEngine = (...flows: any[]) => { + 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(new InMemorySuspendedRunStore()); + 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. @@ -1441,6 +1464,29 @@ describe('[#38876] a branch whose subflow child parks, where the run cannot park 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'); diff --git a/packages/services/service-automation/src/branch-suspension-refusal.test.ts b/packages/services/service-automation/src/branch-suspension-refusal.test.ts index 0b6dc2a598e..5dcff28a163 100644 --- a/packages/services/service-automation/src/branch-suspension-refusal.test.ts +++ b/packages/services/service-automation/src/branch-suspension-refusal.test.ts @@ -513,8 +513,76 @@ describe('[#38876] the late failure binds to the pause it watched (race arms, pi 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 = () => {}; @@ -606,6 +674,34 @@ describe('[#38876] the watch says what happened, and nothing it does escapes it' 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; diff --git a/packages/services/service-automation/src/branch-suspension-refusal.ts b/packages/services/service-automation/src/branch-suspension-refusal.ts index 743a77d7085..499fe282f1e 100644 --- a/packages/services/service-automation/src/branch-suspension-refusal.ts +++ b/packages/services/service-automation/src/branch-suspension-refusal.ts @@ -240,7 +240,11 @@ async function refuse( refusal: FlowBranchSuspensionRefusalError, ): Promise { const where = `on a branch of node '${refusal.forkNodeId}'`; - const reason = `the run that started it failed at a branch that could not carry the pause: ${refusal.message}`; + // 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 diff --git a/packages/services/service-automation/src/late-branch-watch.ts b/packages/services/service-automation/src/late-branch-watch.ts index e7d9d4e6f7a..4460eb50c08 100644 --- a/packages/services/service-automation/src/late-branch-watch.ts +++ b/packages/services/service-automation/src/late-branch-watch.ts @@ -20,11 +20,14 @@ * `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); + * 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; + * 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 @@ -77,12 +80,24 @@ 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. `resume` still only asks `has` and answers `RESUME_IN_PROGRESS`; the - * late-branch watch waits its turn instead, since nobody retries 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); @@ -95,6 +110,9 @@ export class ResumeGate { 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); @@ -103,6 +121,32 @@ export class ResumeGate { 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(); @@ -114,10 +158,10 @@ export class ResumeGate { } } -/** Take the gate for `runId`, waiting while anything in this process holds it. */ +/** 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.add(runId); + gate.holdUndecided(runId); } /** A failed descendant handed to an ancestor whose pause was not readable as stored when the walk reached it. */ @@ -333,6 +377,11 @@ async function failParkedRun( ); 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; @@ -348,7 +397,20 @@ async function failParkedRun( } finally { host.resuming.delete(runId); } - await failAncestorsAfterLateFailure(host, failedRun, ancestorError); + 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'; } diff --git a/packages/services/service-automation/src/run-resume.ts b/packages/services/service-automation/src/run-resume.ts index 598c6e1bffa..0a64ddcdaf8 100644 --- a/packages/services/service-automation/src/run-resume.ts +++ b/packages/services/service-automation/src/run-resume.ts @@ -1430,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` }; }