From 0087d5cce6eff981566d59c87e5cec4ec2cf037b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 06:17:54 +0000 Subject: [PATCH 1/8] fix(spec)!: refuse two durable pauses on concurrent branches of one flow fan-out (WIP) Claude-Session: https://claude.ai/code/session_01QSeKYnrQ7UMtHofKQVjcH2 Co-authored-by: Claude --- .../src/automation/flow-concurrent-pause.ts | 224 ++++++++++++++++++ packages/spec/src/automation/flow.zod.ts | 14 ++ 2 files changed, 238 insertions(+) create mode 100644 packages/spec/src/automation/flow-concurrent-pause.ts diff --git a/packages/spec/src/automation/flow-concurrent-pause.ts b/packages/spec/src/automation/flow-concurrent-pause.ts new file mode 100644 index 00000000000..95a1b4e7117 --- /dev/null +++ b/packages/spec/src/automation/flow-concurrent-pause.ts @@ -0,0 +1,224 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Two durable pauses on concurrent branches of one fan-out — refused at the + * flow parse, so `objectstack validate`, the metadata save and publish, and + * `registerFlow` all refuse it before any run (#38838). + * + * ## The limit + * + * A run parks at ONE place. When a node's unconditional out-edges are taken, + * the engine runs their targets together (`traverseNext`, the unconditional + * bucket under `Promise.all`). If two of those concurrent branches each reach + * a node that parks the run, both nodes do their on-entry work — an approval + * opens its request, a screen or wait arms itself — and both ask to suspend. + * Only the first suspension is kept; the other is dropped without a word. An + * approval request opened there stays `pending` with no suspension behind it: + * its approver can decide it and the run never moves (or the decision lands on + * the other branch's suspension and resumes the run from the wrong node). + * + * This is the limit #3267 ruled 禁 for a region body — a durable pause where + * the run cannot park — met on the top-level graph: the region rule beside the + * call site refuses the same four node types inside a `loop` / `parallel` / + * `try_catch` body by TYPE; this refuses them on two concurrent branches of a + * fan-out. The card's invariant is the bar: no `pending` approval request may + * exist whose decision cannot resume its run. The engine is deliberately NOT + * made to serialise the branches: that would make a parallel shape pause, + * which the same ruling forbids. + * + * ## Measured shapes (`plugin-approvals`, real engine + approval service) + * + * Broken — refused here: + * - two approvals as the direct targets of one node's two unconditional edges; + * - an approval two hops down one branch, an approval on the other; + * - two synchronous branches that MERGE into one approval node (there is no + * join: the merge node runs once per arriving branch, so the approval opens + * twice); + * - an approval beside a `wait` or a `screen` (the run parks at the other + * node, and the approval's decision resumes it from there); + * - two edges carrying the same label out of an `approval`, to two approvals + * (the decision takes every edge with its label, together); + * - two branches each reaching an approval through an edge `condition`, both + * conditions holding. + * + * Correct — not refused: + * - one pausing branch beside branches that run synchronously, ending or not, + * reconverging after the pause or not (the synchronous work completes in + * line and the run parks at the one pause); + * - an approval after a `parallel` region (the region joins before it); + * - an `approval`'s `approve` / `reject` edges, or a `decision`'s branches, + * each to its own approval (one branch is taken); + * - edge conditions on the fan-out node itself (they are evaluated one after + * another, never together). + * + * ## What "concurrent" and "reaches" mean here — mirrored from the engine + * + * A node's CONCURRENT edges are its out-edges with no `condition`, not + * `isDefault` and not `type: 'fault'` — exactly the edges `traverseNext` runs + * under `Promise.all`. A node whose executor always picks a branch by label (an + * `approval`, an `approval_revise`, a `decision` that declares + * `config.conditions`) runs only the edges carrying the picked label, so its + * concurrent edges are grouped by `label`; every other node's are one group. + * + * A branch REACHES a pausing node along ANY path of the flow's edges from the + * branch's target, conditions, defaults, faults and back-edges included — the + * reading `save-notice-placement.ts` takes for the same reason: the parse + * cannot evaluate a condition, so two branches each guarded by a condition are + * judged as if both may hold. A branch that pauses is not walked past its first + * pausing node; the same node reached by two branches counts for both. + * + * ## Boundaries, declared rather than discovered + * + * - The population is the caller's {@link FLOW_PAUSE_CAPABLE_NODE_TYPES}: the + * four types that park on EVERY execution. `subflow` and `map` pause only + * when the child flow they name does (a different record), and are ⛔ not + * judged by type here, by the same ruling the region rule keeps; a fan-out + * to a `subflow` whose child pauses is met only at run time. + * - A plugin-registered pausing type is invisible to a parse (ADR-0018). + * - The top-level graph only: a region body may not hold a pausing node at + * all (the region rule), so a fan-out inside one cannot reach one. + * - A label-picking node whose picked label no out-edge carries runs every + * out-edge (the engine warns); that misauthoring is not modelled here. + * + * Reads the parsed top-level `nodes` / `edges` defensively: this runs inside + * the `FlowSchema` parse, so a malformed member (no string `id`, an edge with + * no string `source` / `target`) is skipped, never read through. + */ + +import { APPROVAL_NODE_TYPE, APPROVAL_REVISE_NODE_TYPE } from './approval.zod'; + +/** One refusal, anchored on the edge that opens a further pausing branch. */ +export interface ConcurrentPauseRefusal { + readonly path: ReadonlyArray; + readonly message: string; +} + +interface NodeView { readonly id: string; readonly type: string; readonly config?: unknown } +interface EdgeView { + readonly index: number; + readonly id?: string; + readonly source: string; + readonly target: string; + readonly label?: string; + readonly condition?: unknown; + readonly isDefault?: unknown; + readonly type?: unknown; +} + +function nodeView(node: unknown): NodeView | undefined { + if (node === null || typeof node !== 'object') return undefined; + const { id, type, config } = node as { id?: unknown; type?: unknown; config?: unknown }; + return typeof id === 'string' && typeof type === 'string' ? { id, type, config } : undefined; +} + +function edgeView(edge: unknown, index: number): EdgeView | undefined { + if (edge === null || typeof edge !== 'object') return undefined; + const e = edge as Record; + if (typeof e.source !== 'string' || typeof e.target !== 'string') return undefined; + return { + index, + source: e.source, + target: e.target, + ...(typeof e.id === 'string' ? { id: e.id } : {}), + ...(typeof e.label === 'string' ? { label: e.label } : {}), + condition: e.condition, + isDefault: e.isDefault, + type: e.type, + }; +} + +/** True for a node whose executor always resumes or continues down ONE label. */ +function picksBranchByLabel(node: NodeView): boolean { + if (node.type === APPROVAL_NODE_TYPE || node.type === APPROVAL_REVISE_NODE_TYPE) return true; + if (node.type !== 'decision') return false; + const conditions = (node.config as { conditions?: unknown } | undefined)?.conditions; + return Array.isArray(conditions) && conditions.length > 0; +} + +/** The groups of `node`'s out-edges the engine runs together, as `traverseNext` buckets them. */ +function concurrentGroups(node: NodeView, outEdges: readonly EdgeView[]): EdgeView[][] { + const unconditional = outEdges.filter((e) => e.type !== 'fault' && !e.condition && e.isDefault !== true); + if (!picksBranchByLabel(node)) return [unconditional]; + const byLabel = new Map(); + for (const edge of unconditional) { + const group = byLabel.get(edge.label); + if (group) group.push(edge); + else byLabel.set(edge.label, [edge]); + } + return [...byLabel.values()]; +} + +const named = (edge: EdgeView): string => + edge.id !== undefined ? `\`${edge.id}\` (\`${edge.source}\` → \`${edge.target}\`)` : `\`${edge.source}\` → \`${edge.target}\``; + +/** + * Every fan-out of `flow`'s top-level graph whose concurrent edges lead two or + * more branches to a node whose type is in `pauseCapableTypes`, one refusal per + * fan-out group, anchored at the second such branch's edge. + */ +export function concurrentPauseRefusals( + flow: { nodes?: unknown; edges?: unknown }, + pauseCapableTypes: readonly string[], +): ConcurrentPauseRefusal[] { + const out: ConcurrentPauseRefusal[] = []; + const nodes = (Array.isArray(flow.nodes) ? flow.nodes : []).map(nodeView).filter((n) => n !== undefined); + if (!nodes.some((n) => pauseCapableTypes.includes(n.type))) return out; + const byId = new Map(nodes.map((n) => [n.id, n] as const)); + const outEdges = new Map(); + (Array.isArray(flow.edges) ? flow.edges : []).forEach((raw, index) => { + const edge = edgeView(raw, index); + if (!edge) return; + const list = outEdges.get(edge.source); + if (list) list.push(edge); + else outEdges.set(edge.source, [edge]); + }); + + /** The pausing nodes a branch entered at `target` may reach, each walk stopping at its first. */ + const pausesFrom = (target: string): NodeView[] => { + const found: NodeView[] = []; + const seen = new Set(); + const stack = [target]; + while (stack.length > 0) { + const id = stack.pop() as string; + if (seen.has(id)) continue; + seen.add(id); + const node = byId.get(id); + if (!node) continue; + if (pauseCapableTypes.includes(node.type)) { + found.push(node); + continue; + } + for (const edge of outEdges.get(id) ?? []) stack.push(edge.target); + } + return found; + }; + + for (const node of nodes) { + for (const group of concurrentGroups(node, outEdges.get(node.id) ?? [])) { + if (group.length < 2) continue; + const pausing = group + .map((edge) => ({ edge, pauses: pausesFrom(edge.target) })) + .filter((branch) => branch.pauses.length > 0); + if (pausing.length < 2) continue; + const branches = pausing + .map(({ edge, pauses }) => + `edge ${named(edge)} reaches ${pauses.map((p) => `\`${p.id}\` (\`${p.type}\`)`).join(', ')}`) + .join('; '); + out.push({ + path: ['edges', pausing[1].edge.index], + message: + `Node \`${node.id}\` fans out to concurrent branches that each reach a node that parks the run — ` + + `${branches}. The engine runs a node's unconditional out-edges together, and a run parks at one ` + + 'place only: the first branch to pause holds the run, and the pause on the other branch is left ' + + 'with nothing to resume — an approval request opened there stays pending, and deciding it never ' + + 'moves the run. Chain the pausing steps one after another on a single branch; to have several ' + + 'people approve at once, use one `approval` step with several approver groups (`behavior: ' + + "'unanimous'`); where only one of the branches should run, route them through one `decision` so " + + 'exactly one is taken. A `condition` further down a branch does not exempt it, because the flow ' + + 'cannot be checked for which conditions may hold together; and a `parallel` region is no way out ' + + 'either, because a region body cannot pause.', + }); + } + } + return out; +} diff --git a/packages/spec/src/automation/flow.zod.ts b/packages/spec/src/automation/flow.zod.ts index 7682527736d..869dbe9d507 100644 --- a/packages/spec/src/automation/flow.zod.ts +++ b/packages/spec/src/automation/flow.zod.ts @@ -31,6 +31,7 @@ import { apiTriggerSecretRefRefusals } from './api-trigger-secret-ref.zod'; import { apiTriggerSignatureRefusals } from './api-trigger-signature.zod'; import { flowStartConfigRefusals } from './flow-start-config-refusals'; import { saveNoticePlacementRefusals } from './save-notice-placement'; +import { concurrentPauseRefusals } from './flow-concurrent-pause'; // [#23543 F3] The loose `config` keys of the two sibling-block node types — one // table, shared with the two D2 lifts that still run at rehydration. import { siblingBlockLooseConfigRefusals } from './flow-sibling-block-loose-keys'; @@ -1641,6 +1642,19 @@ export const FlowSchema = lazySchema(() => strictObject( }); } + // The same limit on the TOP-LEVEL graph (#38838): two durable pauses on + // concurrent branches of one fan-out. A node's unconditional out-edges run + // together, and a run parks at one place, so the second branch's pause is + // dropped — an approval opened there stays pending and its decision never + // moves the run. Refused when two or more concurrent branches may reach a + // node of the same population as the region rule above, by the same ruling + // (#3267 禁; the engine is not made to serialise the branches). What counts + // as concurrent, what "reach" means, the measured shapes and the boundaries + // (`subflow` / `map`, plugin types) are `flow-concurrent-pause.ts`'s header. + for (const refusal of concurrentPauseRefusals(flow, FLOW_PAUSE_CAPABLE_NODE_TYPES)) { + ctx.addIssue({ code: 'custom', path: [...refusal.path], message: refusal.message }); + } + // A blank string in a ledger `predicate` slot (#17493, ruling A) — // `decision`'s `config.conditions[].expression` and `screen`'s // `config.fields[].visibleWhen`, the slots `FLOW_NODE_EXPRESSION_PATHS` From e229813b278d683ea7e00b67ba4f6b2a66efec65 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 06:20:35 +0000 Subject: [PATCH 2/8] test: pin the fan-out pause refusal at the schema and the publish door (WIP) Claude-Session: https://claude.ai/code/session_01QSeKYnrQ7UMtHofKQVjcH2 Co-authored-by: Claude --- .../src/flow-route.integration.test.ts | 176 +++++++++++--- .../automation/flow-concurrent-pause.test.ts | 217 ++++++++++++++++++ packages/spec/src/automation/flow.zod.ts | 4 +- 3 files changed, 362 insertions(+), 35 deletions(-) create mode 100644 packages/spec/src/automation/flow-concurrent-pause.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 c682a30865d..4d29b5bf568 100644 --- a/packages/plugins/plugin-approvals/src/flow-route.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/flow-route.integration.test.ts @@ -45,10 +45,11 @@ * both sides on purpose: the trunk is served unchanged. */ -import { describe, it, expect, beforeAll, beforeEach, afterAll } from 'vitest'; -import { ObjectQL } from '@objectstack/objectql'; +import { describe, it, expect, beforeAll, beforeEach, afterAll, afterEach } from 'vitest'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQL, ObjectQLPlugin } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; -import { AutomationEngine, InMemorySuspendedRunStore, installBuiltinNodes } from '@objectstack/service-automation'; +import { AutomationEngine, AutomationServicePlugin, InMemorySuspendedRunStore, installBuiltinNodes } from '@objectstack/service-automation'; import type { EngineQueryOptions } from '@objectstack/spec/data'; import { ApprovalService } from './approval-service.js'; import { ApprovalsServicePlugin } from './approvals-plugin.js'; @@ -223,6 +224,45 @@ const REVIEWED_THEN_LEGAL = { ], }; +/** + * [#38838] One node fanning out over two UNCONDITIONAL edges to two approval + * steps: the engine runs both targets together, both open a request, and only + * the first holds the run's suspension — the second's decision never moves the + * run. Refused at authoring now; the refusal is pinned at the publish door below. + */ +/** Each step's decision routed by its exact label, as the metadata door requires. */ +const ROUTED_DECISIONS = [ + { id: 'f3', source: 'a_review', target: 'ok', label: 'approve' }, + { id: 'f4', source: 'a_review', target: 'no', label: 'reject' }, + { id: 'f5', source: 'b_review', target: 'ok', label: 'approve' }, + { id: 'f6', source: 'b_review', target: 'no', label: 'reject' }, +]; +const unconditionalFanOut = (name: string) => ({ + name, label: 'Fan out', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + step('a_review', 'A', 'u_mgr'), + step('b_review', 'B', 'u_dir'), + { id: 'ok', type: 'end', label: 'Ok' }, + { id: 'no', type: 'end', label: 'Rejected' }, + ], + edges: [ + { id: 'f1', source: 'start', target: 'a_review' }, + { id: 'f2', source: 'start', target: 'b_review' }, + ...ROUTED_DECISIONS, + ], +}); + +/** [#38838] The same two steps behind two edge conditions out of one node: one is taken. */ +const conditionalFanOut = (name: string) => ({ + ...unconditionalFanOut(name), + edges: [ + { id: 'f1', source: 'start', target: 'a_review', condition: 'record.amount < 1000' }, + { id: 'f2', source: 'start', target: 'b_review', condition: 'record.amount >= 1000' }, + ...ROUTED_DECISIONS, + ], +}); + /** What `flow_steps` serves for every `contract_approval` request: its trunk. */ const CONTRACT_TRUNK = ['manager_review', 'legal_finance_joint', 'executive_signoff', 'gm_signoff']; @@ -698,40 +738,20 @@ describe('the approval-ended witness is the content of the body the run ran, dur expect('outcome' in (await read(runner, manager)).flow_route).toBe(false); }); - it('[N2] a node fanning out to two approval steps opens two requests of one run; the sibling is not where the decided one went', async () => { + it('[#38838] CONTROL: a conditional fan-out (one edge taken) still registers, and its one request resumes the run', async () => { + // The shape the fan-out refusal below must leave alone: the conditions out + // of one node are evaluated one after another, so one branch runs, one + // request opens, and that request's decision moves the run to its end. const svc = newService(); - const fan = { - name: 'witness_fan_out', label: 'Fan out', type: 'autolaunched', - nodes: [ - { id: 'start', type: 'start', label: 'Start' }, - step('a_review', 'A', 'u_mgr'), - step('b_review', 'B', 'u_dir'), - { id: 'ok', type: 'end', label: 'Ok' }, - ], - // Two unconditional edges out of one node: the engine runs both targets together. - edges: [ - { id: 'f1', source: 'start', target: 'a_review' }, - { id: 'f2', source: 'start', target: 'b_review' }, - { id: 'f3', source: 'a_review', target: 'ok', label: 'approve' }, - { id: 'f4', source: 'b_review', target: 'ok', label: 'approve' }, - ], - }; - const automation = bootEngine(svc, fan); - const first = await submit(automation, fan.name); + const name = 'witness_conditional_fan_out'; + const automation = bootEngine(svc, conditionalFanOut(name)); + const a = await submit(automation, name); const opened: any[] = await engine.find('sys_approval_request', { - where: { flow_run_id: first.flow_run_id }, context: SYSTEM, + where: { flow_run_id: a.flow_run_id }, context: SYSTEM, } satisfies EngineQueryOptions); - // Measured, not assumed: the flow parses and both steps open, pending side by side in ONE run. - expect(opened.map((r) => [r.flow_node_id, r.status]).sort()).toEqual([['a_review', 'pending'], ['b_review', 'pending']]); - const a = opened.find((r) => r.flow_node_id === 'a_review'); - const b = opened.find((r) => r.flow_node_id === 'b_review'); - expect(b.created_at > a.created_at, 'b opened after a, while a was pending').toBe(true); - - await decide(svc, a, 'u_mgr', 'approve'); - const outcome = (await read(svc, a)).flow_route.outcome; - // Read from the opening, b (opened after a opened) would be served as where a's approval went. - expect(outcome?.step, 'the sibling opened before a was decided is not a later step').toBeUndefined(); - expect(outcome?.status).toBe('approved'); + expect(opened.map((r) => [r.flow_node_id, r.status])).toEqual([['a_review', 'pending']]); + expect(await decide(svc, a, 'u_mgr', 'approve'), 'nothing pending after the one decision').toBeUndefined(); + expect((await automation.getRun(a.flow_run_id))?.status, 'the decision moved the run to its end').toBe('completed'); }); it('CONTROL: a run of the edited body itself, read on a replica that holds that body, serves "ended"', async () => { @@ -746,3 +766,91 @@ describe('the approval-ended witness is the content of the body the run ran, dur expect((await read(reader, manager)).flow_route.outcome).toEqual({ status: 'approved', ended: true }); }); }); + +/** + * [#38838] A node fanning out to two approval steps over unconditional edges is + * refused at publish, the authoring-time half of the limit #3267 ruled 禁 for a + * region body: a durable pause where the run cannot park. Measured before the + * rule on this file's own rig: the flow registered and ran, ONE run held two + * `pending` requests, only the first held the run's suspension, and deciding + * the second answered `RESUME_TARGET_LOST`. The rule lives in the flow schema + * (`flow-concurrent-pause.ts`, beside the region rule), so every door that + * parses a flow refuses it; pinned here at the metadata door a Studio save and + * publish reach, with the ADR-0112 envelope, and at `registerFlow`. + * + * ⚠️ Direction, measured: on the unfixed schema the active save, the publish + * and the registration below all succeed (RED); the control is green on both. + * The read-side guard for a sibling request (`routeOutcome` measures "later" + * from the decision) keeps its own unit pin in `approval-route.test.ts`. + */ +describe('[#38838] a fan-out to two approval steps is refused at publish', () => { + const PKG = 'app.crm'; + let kernel: ObjectKernel; + let ql: ObjectQL; + let protocol: any; + + afterEach(async () => { + try { await kernel?.shutdown(); } catch { /* noop */ } + }); + + /** Real kernel, real ObjectQL engine and metadata protocol, real automation engine, the real approvals plugin. */ + async function boot() { + kernel = new ObjectKernel({ logger: { level: 'silent' } } as any); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(new AutomationServicePlugin()); + await kernel.use(new ApprovalsServicePlugin()); + await kernel.bootstrap(); + ql = kernel.getService('objectql'); + protocol = kernel.getService('protocol'); + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + await driver.connect(); + ql.registerDriver(driver, true); + (ql.registry as any).installPackage({ id: PKG, name: PKG, version: '1.0.0', type: 'app', namespace: 'crm' }, 'authored'); + await ql.syncSchemas(); + } + const activeRows = async (name: string) => + ((await ql.find('sys_metadata', { where: { type: 'flow', name }, context: { isSystem: true } })) as any[]) + .filter((r) => r.state === 'active'); + const refusalText = (err: any) => JSON.stringify({ message: err?.message, issues: err?.issues ?? err?.details }); + const LEAD = 'Node `start` fans out to concurrent branches that each reach a node that parks the run'; + + it('an active save is refused with 422 INVALID_METADATA, naming the fan-out and both branches', async () => { + await boot(); + const err = await protocol.saveMetaItem({ + type: 'flow', name: 'fan_out_active', item: unconditionalFanOut('fan_out_active'), packageId: PKG, + }).catch((e: any) => e); + expect(err).toBeInstanceOf(Error); + expect(err).toMatchObject({ code: 'INVALID_METADATA', status: 422 }); + expect(refusalText(err)).toContain(LEAD); + expect(refusalText(err)).toContain('edge `f2` (`start` → `b_review`) reaches `b_review` (`approval`)'); + expect(await activeRows('fan_out_active')).toEqual([]); + }); + + it('a draft is not refused; its publish is, with the same envelope', async () => { + await boot(); + const saved = await protocol.saveMetaItem({ + type: 'flow', name: 'fan_out_draft', item: unconditionalFanOut('fan_out_draft'), packageId: PKG, mode: 'draft', + }); + expect(saved.success).toBe(true); + const err = await protocol.publishMetaItem({ type: 'flow', name: 'fan_out_draft', packageId: PKG }).catch((e: any) => e); + expect(err).toBeInstanceOf(Error); + expect(err).toMatchObject({ code: 'INVALID_METADATA', status: 422 }); + expect(refusalText(err)).toContain(LEAD); + expect(await activeRows('fan_out_draft')).toEqual([]); + }); + + it('the engine refuses to register it, so a stored copy never runs either', () => { + const automation = new AutomationEngine(silent); + installBuiltinNodes(automation, { logger: silent, getService() { throw new Error('none'); } } as any); + expect(() => automation.registerFlow('fan_out_engine', unconditionalFanOut('fan_out_engine'))).toThrow(LEAD); + }); + + it('CONTROL: the conditional fan-out (one edge taken) publishes', async () => { + await boot(); + const out = await protocol.saveMetaItem({ + type: 'flow', name: 'fan_out_conditional', item: conditionalFanOut('fan_out_conditional'), packageId: PKG, + }); + expect(out.success).toBe(true); + expect(await activeRows('fan_out_conditional')).toHaveLength(1); + }); +}); diff --git a/packages/spec/src/automation/flow-concurrent-pause.test.ts b/packages/spec/src/automation/flow-concurrent-pause.test.ts new file mode 100644 index 00000000000..66bd2205cfb --- /dev/null +++ b/packages/spec/src/automation/flow-concurrent-pause.test.ts @@ -0,0 +1,217 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Two durable pauses on concurrent branches of one fan-out are refused at the + * flow parse (#38838) — the top-level-graph sibling of the region rule in + * `flow-region-pause-and-end.test.ts`, by the same ruling (#3267 禁: a + * durable pause where the run cannot park). + * + * Every refused shape below was measured BROKEN on the real engine with the + * real approval service (an approval request left `pending` whose decision + * cannot resume its run, or resumes it from the other branch's node), and + * every accepted shape was measured to park and resume correctly; the + * measurements are in the PR. The served path over the real engine is the + * fan-out pin in `plugin-approvals/src/flow-route.integration.test.ts`. + * + * Every refusal case here fails without the rule: the shapes all parsed green + * before it. + */ +import { describe, it, expect } from 'vitest'; +import { FlowSchema, FLOW_PAUSE_CAPABLE_NODE_TYPES, type Flow, type FlowNode, type FlowEdge } from './flow.zod'; +import { concurrentPauseRefusals } from './flow-concurrent-pause'; + +const approval = (id: string): FlowNode => ({ id, type: 'approval', label: id, config: { approvers: [{ type: 'user', value: 'u1' }] } }); +const wait = (id: string): FlowNode => ({ id, type: 'wait', label: id, waitEventConfig: { eventType: 'timer', timerDuration: 'PT1H' } }); +const screen = (id: string): FlowNode => ({ id, type: 'screen', label: id, config: { fields: [{ name: 'note', label: 'Note', type: 'text' }] } }); +const step = (id: string): FlowNode => ({ id, type: 'assignment', label: id }); +const end = (id: string): FlowNode => ({ id, type: 'end', label: id }); +const START: FlowNode = { id: 'start', type: 'start', label: 'Start' }; + +type E = [string, string, Partial?]; +const flowOf = (nodes: FlowNode[], edges: E[]): Flow => ({ + name: 'fan_out', label: 'Fan out', type: 'autolaunched', + nodes: [START, ...nodes], + edges: edges.map(([source, target, extra], i) => ({ id: `e${i}`, source, target, ...(extra ?? {}) })), +}); + +/** The fan-out refusals of `flow` as `[path, message]`, judged through the real parse. */ +const refusalsOf = (flow: Flow): Array<[string, string]> => { + const result = FlowSchema.safeParse(flow); + if (result.success) return []; + return result.error.issues + .filter((i) => i.message.includes('fans out to concurrent branches')) + .map((i) => [i.path.join('.'), i.message]); +}; + +/** Every issue of `flow`'s parse, so a control proves the WHOLE flow parses, not only this rule. */ +const parses = (flow: Flow): boolean => { + const result = FlowSchema.safeParse(flow); + if (!result.success) throw new Error(result.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('\n')); + return true; +}; + +describe('a fan-out whose concurrent branches both reach a node that parks the run is refused', () => { + it('two approvals as the direct targets of one node\'s two unconditional edges (the measured card shape)', () => { + const flow = flowOf([approval('a_review'), approval('b_review'), end('ok')], [ + ['start', 'a_review'], ['start', 'b_review'], + ['a_review', 'ok', { label: 'approve' }], ['b_review', 'ok', { label: 'approve' }], + ]); + const refusals = refusalsOf(flow); + expect(refusals).toHaveLength(1); + // Anchored on the edge that opens the SECOND pausing branch: the one to remove or redirect. + expect(refusals[0][0]).toBe('edges.1'); + expect(refusals[0][1]).toContain( + 'Node `start` fans out to concurrent branches that each reach a node that parks the run — ' + + 'edge `e0` (`start` → `a_review`) reaches `a_review` (`approval`); ' + + 'edge `e1` (`start` → `b_review`) reaches `b_review` (`approval`).', + ); + // The prescription: what to write instead, never a `parallel` region. + expect(refusals[0][1]).toContain('Chain the pausing steps one after another on a single branch'); + expect(refusals[0][1]).toContain('a `parallel` region is no way out'); + }); + + it.each(FLOW_PAUSE_CAPABLE_NODE_TYPES.filter((t) => t !== 'approval_revise'))( + 'an approval beside a `%s` on the other branch', + (type) => { + const other = type === 'wait' ? wait('other') : type === 'screen' ? screen('other') : approval('other'); + const flow = flowOf([approval('a_review'), other, end('ok'), end('ok2')], [ + ['start', 'a_review'], ['start', 'other'], ['a_review', 'ok', { label: 'approve' }], ['other', 'ok2'], + ]); + expect(refusalsOf(flow).map(([path]) => path)).toEqual(['edges.1']); + }, + ); + + it('a pause two hops down one branch, an approval on the other', () => { + const flow = flowOf([step('x1'), approval('a_review'), approval('b_review'), end('ok')], [ + ['start', 'x1'], ['start', 'b_review'], ['x1', 'a_review'], + ['a_review', 'ok', { label: 'approve' }], ['b_review', 'ok', { label: 'approve' }], + ]); + expect(refusalsOf(flow).map(([path]) => path)).toEqual(['edges.1']); + }); + + it('two synchronous branches that merge into ONE approval: the merge node runs once per branch', () => { + const flow = flowOf([step('x1'), step('y1'), approval('a_review'), end('ok')], [ + ['start', 'x1'], ['start', 'y1'], ['x1', 'a_review'], ['y1', 'a_review'], ['a_review', 'ok', { label: 'approve' }], + ]); + const refusals = refusalsOf(flow); + expect(refusals.map(([path]) => path)).toEqual(['edges.1']); + expect(refusals[0][1]).toContain('edge `e0` (`start` → `x1`) reaches `a_review` (`approval`); edge `e1` (`start` → `y1`) reaches `a_review` (`approval`)'); + }); + + it('two edges carrying the SAME label out of an approval: the decision takes both together', () => { + const flow = flowOf([approval('m_review'), approval('a_review'), approval('b_review'), end('ok'), end('no')], [ + ['start', 'm_review'], + ['m_review', 'a_review', { label: 'approve' }], ['m_review', 'b_review', { label: 'approve' }], + ['m_review', 'no', { label: 'reject' }], + ['a_review', 'ok', { label: 'approve' }], ['b_review', 'ok', { label: 'approve' }], + ]); + const refusals = refusalsOf(flow); + expect(refusals.map(([path]) => path)).toEqual(['edges.2']); + expect(refusals[0][1]).toContain('Node `m_review` fans out'); + }); + + it('two branches each guarded by an edge condition: the parse cannot tell whether both may hold', () => { + // Measured broken with both conditions holding; measured correct with + // exclusive ones. The parse cannot evaluate a condition, so it judges the + // shape as if both may hold — the reading save-notice-placement takes — + // and the prescription names the `decision` that makes the choice explicit. + const flow = flowOf([step('x1'), step('y1'), approval('a_review'), approval('b_review'), end('ok')], [ + ['start', 'x1'], ['start', 'y1'], + ['x1', 'a_review', { condition: 'record.amount > 5' }], ['y1', 'b_review', { condition: 'record.amount <= 5' }], + ['a_review', 'ok', { label: 'approve' }], ['b_review', 'ok', { label: 'approve' }], + ]); + expect(refusalsOf(flow).map(([path]) => path)).toEqual(['edges.1']); + expect(refusalsOf(flow)[0][1]).toContain('route them through one `decision` so exactly one is taken'); + }); + + it('three branches, two of which pause: one refusal, anchored on the second pausing branch', () => { + const flow = flowOf([step('x1'), approval('a_review'), approval('b_review'), end('ok'), end('ok2')], [ + ['start', 'x1'], ['start', 'a_review'], ['start', 'b_review'], ['x1', 'ok2'], + ['a_review', 'ok', { label: 'approve' }], ['b_review', 'ok', { label: 'approve' }], + ]); + expect(refusalsOf(flow).map(([path]) => path)).toEqual(['edges.2']); + }); +}); + +describe('controls: shapes that park at one place are accepted', () => { + it('one pausing branch beside a synchronous branch that runs to its own end', () => { + expect(parses(flowOf([approval('a_review'), step('x1'), step('x2'), end('ok'), end('ok2')], [ + ['start', 'a_review'], ['start', 'x1'], ['x1', 'x2'], ['x2', 'ok2'], ['a_review', 'ok', { label: 'approve' }], + ]))).toBe(true); + }); + + it('one pausing branch beside a synchronous branch that reconverges after the pause', () => { + expect(parses(flowOf([approval('a_review'), step('x1'), step('after'), end('ok')], [ + ['start', 'a_review'], ['start', 'x1'], ['a_review', 'after', { label: 'approve' }], ['x1', 'after'], ['after', 'ok'], + ]))).toBe(true); + }); + + it('an approval after a `parallel` region: the region joins before it', () => { + expect(parses(flowOf([ + { id: 'par', type: 'parallel', label: 'Par', config: { branches: [ + { name: 'a', nodes: [step('p1')], edges: [] }, { name: 'b', nodes: [step('p2')], edges: [] }, + ] } }, + approval('a_review'), end('ok'), + ], [['start', 'par'], ['par', 'a_review'], ['a_review', 'ok', { label: 'approve' }]]))).toBe(true); + }); + + it('an approval\'s `approve` and `reject` edges, each to its own approval: one is taken', () => { + expect(parses(flowOf([approval('m_review'), approval('a_review'), approval('b_review'), end('ok')], [ + ['start', 'm_review'], + ['m_review', 'a_review', { label: 'approve' }], ['m_review', 'b_review', { label: 'reject' }], + ['a_review', 'ok', { label: 'approve' }], ['b_review', 'ok', { label: 'approve' }], + ]))).toBe(true); + }); + + it('a `decision` that declares its branches, each to its own approval: one is taken', () => { + expect(parses(flowOf([ + { id: 'route', type: 'decision', label: 'Route', config: { conditions: [{ label: 'big', expression: 'record.amount > 5' }] } }, + approval('a_review'), approval('b_review'), end('ok'), + ], [ + ['start', 'route'], ['route', 'a_review', { label: 'big' }], ['route', 'b_review', { label: 'default' }], + ['a_review', 'ok', { label: 'approve' }], ['b_review', 'ok', { label: 'approve' }], + ]))).toBe(true); + }); + + it('a conditional fan-out: edge conditions out of one node are evaluated one after another, never together', () => { + expect(parses(flowOf([step('x1'), approval('a_review'), approval('b_review'), end('ok')], [ + ['start', 'x1'], + ['x1', 'a_review', { condition: 'record.amount > 5' }], ['x1', 'b_review', { condition: 'record.amount <= 5' }], + ['a_review', 'ok', { label: 'approve' }], ['b_review', 'ok', { label: 'approve' }], + ]))).toBe(true); + }); + + it('a default edge beside a conditional one is an "otherwise", not a concurrent branch', () => { + expect(parses(flowOf([step('x1'), approval('a_review'), approval('b_review'), end('ok')], [ + ['start', 'x1'], + ['x1', 'a_review', { condition: 'record.amount > 5' }], ['x1', 'b_review', { isDefault: true }], + ['a_review', 'ok', { label: 'approve' }], ['b_review', 'ok', { label: 'approve' }], + ]))).toBe(true); + }); +}); + +describe('the declared boundaries', () => { + it('⛔ a `subflow` on a concurrent branch is not judged by type (its child is another record)', () => { + // Measured broken on the real engine when the child pauses — but whether it + // pauses is decided by the flow `config.flowName` names, which is not in + // hand here: the same ruling keeps `subflow` / `map` out of the region + // rule's population. That case is met at run time, not by this parse. + expect(parses(flowOf([approval('a_review'), { id: 'sub', type: 'subflow', label: 'Sub', config: { flowName: 'child' } }, end('ok'), end('ok2')], [ + ['start', 'a_review'], ['start', 'sub'], ['a_review', 'ok', { label: 'approve' }], ['sub', 'ok2'], + ]))).toBe(true); + }); + + it('judges the population it is handed: an empty one refuses nothing', () => { + const flow = flowOf([approval('a_review'), approval('b_review')], [['start', 'a_review'], ['start', 'b_review']]); + expect(concurrentPauseRefusals(flow, [])).toEqual([]); + expect(concurrentPauseRefusals(flow, FLOW_PAUSE_CAPABLE_NODE_TYPES)).toHaveLength(1); + }); + + it('skips malformed members rather than reading through them', () => { + expect(concurrentPauseRefusals( + { nodes: [null, { id: 'start', type: 'start' }, { id: 'a', type: 'approval' }, { id: 'b', type: 'approval' }], + edges: [null, { source: 'start', target: 'a' }, { source: 'start' }, { source: 'start', target: 'b' }] }, + FLOW_PAUSE_CAPABLE_NODE_TYPES, + ).map((r) => r.path)).toEqual([['edges', 3]]); + }); +}); diff --git a/packages/spec/src/automation/flow.zod.ts b/packages/spec/src/automation/flow.zod.ts index 869dbe9d507..248e5b101eb 100644 --- a/packages/spec/src/automation/flow.zod.ts +++ b/packages/spec/src/automation/flow.zod.ts @@ -92,7 +92,9 @@ export const FLOW_STRUCTURAL_NODE_TYPES: readonly string[] = ['start', 'end']; /** * The node types a structured region body may not contain — the population the - * `FlowSchema.superRefine` region rule below keys on. + * `FlowSchema.superRefine` region rule below keys on, and the one its sibling, + * the concurrent-branch rule (`flow-concurrent-pause.ts`), keys on too: two of + * these on concurrent branches of one fan-out are refused for the same reason. * * ⚠️ **Read the contents, not the name.** This is NOT every type that can * pause; it is the four that pause UNCONDITIONALLY, on every execution, decided From 2a28e201129197092b011e2e425c75641728ce42 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 06:23:18 +0000 Subject: [PATCH 3/8] test(approvals): the fan-out draft save is refused by the schema half of the door (WIP) Claude-Session: https://claude.ai/code/session_01QSeKYnrQ7UMtHofKQVjcH2 Co-authored-by: Claude --- .../src/flow-route.integration.test.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 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 4d29b5bf568..abdfa434c64 100644 --- a/packages/plugins/plugin-approvals/src/flow-route.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/flow-route.integration.test.ts @@ -769,7 +769,7 @@ describe('the approval-ended witness is the content of the body the run ran, dur /** * [#38838] A node fanning out to two approval steps over unconditional edges is - * refused at publish, the authoring-time half of the limit #3267 ruled 禁 for a + * refused at save and publish, the authoring-time half of the limit #3267 ruled 禁 for a * region body: a durable pause where the run cannot park. Measured before the * rule on this file's own rig: the flow registered and ran, ONE run held two * `pending` requests, only the first held the run's suspension, and deciding @@ -778,8 +778,8 @@ describe('the approval-ended witness is the content of the body the run ran, dur * parses a flow refuses it; pinned here at the metadata door a Studio save and * publish reach, with the ADR-0112 envelope, and at `registerFlow`. * - * ⚠️ Direction, measured: on the unfixed schema the active save, the publish - * and the registration below all succeed (RED); the control is green on both. + * ⚠️ Direction, measured: on the unfixed schema the active save, the draft + * save and the registration below all succeed (RED); the control is green on both. * The read-side guard for a sibling request (`routeOutcome` measures "later" * from the decision) keeps its own unit pin in `approval-route.test.ts`. */ @@ -826,17 +826,17 @@ describe('[#38838] a fan-out to two approval steps is refused at publish', () => expect(await activeRows('fan_out_active')).toEqual([]); }); - it('a draft is not refused; its publish is, with the same envelope', async () => { + it('a draft save is refused too: the flow schema is judged at every save, a draft included', async () => { + // Measured: the schema half of the door runs on a draft (only the author-time + // lint waits for the promotion), so this never reaches the publish step. await boot(); - const saved = await protocol.saveMetaItem({ + const err = await protocol.saveMetaItem({ type: 'flow', name: 'fan_out_draft', item: unconditionalFanOut('fan_out_draft'), packageId: PKG, mode: 'draft', - }); - expect(saved.success).toBe(true); - const err = await protocol.publishMetaItem({ type: 'flow', name: 'fan_out_draft', packageId: PKG }).catch((e: any) => e); + }).catch((e: any) => e); expect(err).toBeInstanceOf(Error); expect(err).toMatchObject({ code: 'INVALID_METADATA', status: 422 }); expect(refusalText(err)).toContain(LEAD); - expect(await activeRows('fan_out_draft')).toEqual([]); + expect(await ql.find('sys_metadata', { where: { type: 'flow', name: 'fan_out_draft' }, context: { isSystem: true } })).toEqual([]); }); it('the engine refuses to register it, so a stored copy never runs either', () => { From 931008016d982d6b05ba7dc9ccbc97c9154d76cb Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 06:46:27 +0000 Subject: [PATCH 4/8] docs+changeset: the fan-out pause refusal, its ADR-0087 semantic entry and its changeset (WIP) Claude-Session: https://claude.ai/code/session_01QSeKYnrQ7UMtHofKQVjcH2 Co-authored-by: Claude --- .changeset/38838-fanout-pause-refusal.md | 20 +++++++ content/docs/automation/flows.mdx | 29 ++++++++++ ...concurrent-branch-durable-pause-refused.ts | 54 +++++++++++++++++++ 3 files changed, 103 insertions(+) create mode 100644 .changeset/38838-fanout-pause-refusal.md create mode 100644 packages/spec/src/migrations/entries/semantic/19.flow-concurrent-branch-durable-pause-refused.ts diff --git a/.changeset/38838-fanout-pause-refusal.md b/.changeset/38838-fanout-pause-refusal.md new file mode 100644 index 00000000000..99755378903 --- /dev/null +++ b/.changeset/38838-fanout-pause-refusal.md @@ -0,0 +1,20 @@ +--- +'@objectstack/spec': minor +--- + +fix(spec)!: a flow whose node fans out to two or more branches that each reach a step that parks the run is refused at authoring + +Clause-②: no (narrowing) +Metadata-protocol: narrowed + +**BREAKING** for a flow author: FROM a flow in which one node's out-edges with no `condition` (not `isDefault`, not `fault`) lead two or more branches, along any path, to an `approval`, `approval_revise`, `screen` or `wait` node registering and running, TO that flow refused by the flow schema, at every door (`objectstack validate`, the metadata save, draft or active, and publish with `422 INVALID_METADATA`, and `registerFlow`), with one message naming the fan-out node and each pausing branch. The one-line fix: chain the pausing steps one after another on a single branch; where several people must approve at once, use one `approval` step with several approver groups and `behavior: 'unanimous'`; where only one branch should run, put a `decision` in front of them. + +Why. The engine runs a node's unconditional out-edges together and a run parks at one place. Two concurrent pauses both did their on-entry work and only the first was kept: a start node fanning out to two approval steps opened two `pending` requests in one run, only the first held the run's suspension, and deciding the second answered `RESUME_TARGET_LOST`, so the approver decided and the run never moved. Beside a `wait` or a `screen`, the approval's decision resumed the run from the other node. This is the limit already refused by type inside a `loop` / `parallel` / `try_catch` body, now refused on the top-level graph; the engine is not made to serialise the branches. + +What is refused: two branches that each reach a pausing node, through any path, `condition`s, `decision`s and back-edges included (the parse cannot tell which conditions can hold together), and two branches merging into one pausing node, which the engine runs once per arriving branch. On an `approval` / `approval_revise` node, and on a `decision` that declares `config.conditions`, only out-edges sharing one `label` run together, so two edges labelled `approve` to two steps are refused and `approve` / `reject` edges to two steps are not. + +Still accepted: one pausing branch beside branches that never pause, an approval after a `parallel` region, an approval's `approve` / `reject` edges each to its own step, a `decision`'s branches each to its own step, and conditioned out-edges of one node, which run one after another. Not judged: a `subflow` or `map` on a concurrent branch (whether it pauses is decided by the child flow it names) and a pausing node type a plugin registers. + +A stored flow carrying the shape no longer registers until it is rewritten. No conversion rewrites it (which shape the author meant is not recorded); the ADR-0087 semantic entry `flow-concurrent-branch-durable-pause-refused` carries the rewrite to the upgrade guide. + + diff --git a/content/docs/automation/flows.mdx b/content/docs/automation/flows.mdx index a745d16ea27..af43d5fbc4b 100644 --- a/content/docs/automation/flows.mdx +++ b/content/docs/automation/flows.mdx @@ -1707,6 +1707,35 @@ is a separate, larger capability ([ADR-0039](https://github.com/objectstack-ai/o Track B); the aggregating node covers the common parallel/batch-approval demand without it. Worked example: `showcase_invoice_signoff` in the showcase app. +**Two pausing steps on concurrent branches are refused.** A node's out-edges +that carry no `condition` (and are not `isDefault` or `fault` edges) run +**together**, and a run parks at one place only. So when one node fans out +over such edges and two or more of the branches reach a step that parks the +run (`approval`, `approval_revise`, `screen`, `wait`), only the first branch +to pause holds the run: the other step still opens its request, which stays +`pending`, and deciding it never moves the run. The flow schema refuses that +shape at every door (a `422 INVALID_METADATA` at the metadata save, draft or +active, a refused registration at the engine, an error at +`objectstack validate`), naming the fan-out node and each branch. It counts +every path down a branch, through `condition`s, `decision`s and back-edges, +since which conditions can hold together cannot be checked; two branches that +merge into **one** approval are refused too, because the merged step runs once +per arriving branch. Write instead: + +- the steps **one after another** on a single branch (`a_review` → `approve` → + `b_review`); +- **one** `approval` step with several approver groups and + `behavior: 'unanimous'`, as above, when several people must sign off at + once; +- a `decision` in front of the steps when only **one** of them should run. + +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, an approval's `approve` / +`reject` edges each to its own step, and conditioned edges out of one node, +which run one after another. Not judged here: a `subflow` or `map` on a +concurrent branch, whose pause is decided by the child flow it names. + ### Batch approval — a `map` node, one item at a time "Sign off **every** task in the release, in turn" is a **`map` node**: it runs a diff --git a/packages/spec/src/migrations/entries/semantic/19.flow-concurrent-branch-durable-pause-refused.ts b/packages/spec/src/migrations/entries/semantic/19.flow-concurrent-branch-durable-pause-refused.ts new file mode 100644 index 00000000000..034270823ba --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/19.flow-concurrent-branch-durable-pause-refused.ts @@ -0,0 +1,54 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// Two durable pauses on concurrent branches of one fan-out are refused at the +// flow parse. A structured TODO, not a D2 conversion: whether the author meant +// the steps in sequence, one step with several approver groups, or one branch +// of a choice is not recorded, and the platform does not guess. +export const entry: SemanticMigration = { + id: 'flow-concurrent-branch-durable-pause-refused', + surface: + 'The TOP-LEVEL graph of every flow: a node whose out-edges with no `condition` (and not `isDefault`, ' + + 'not `type: \'fault\'`) lead two or more branches, along any path of the flow\'s edges, to a node of ' + + 'a type that parks the run on every execution (`approval`, `approval_revise`, `screen`, `wait`). ' + + 'The engine runs those out-edges together. On an `approval` / `approval_revise` node, and on a ' + + '`decision` that declares `config.conditions`, only the out-edges sharing ONE `label` run together, ' + + 'so `approve` / `reject` edges to two steps are not the shape. Two branches merging into one pausing ' + + 'node are the shape (the merged node runs once per arriving branch). ⛔ `subflow` and `map` are not ' + + 'in the population: whether they pause is decided by the child flow they name, a different record.', + replacement: + 'Chain the pausing steps one after another on a single branch (`start → a_review → approve → ' + + 'b_review`); where several people must approve at once, use ONE `approval` step with several approver ' + + 'groups and `behavior: \'unanimous\'`; where only one of the branches should run, put a `decision` in ' + + 'front of them so exactly one is taken. A `parallel` region is not a replacement: a region body may ' + + 'not hold a pausing node at all.', + reason: + 'A run parks at ONE place. The engine runs a node\'s unconditional out-edges under `Promise.all`; when ' + + 'two concurrent branches each reach a pausing node, both do their on-entry work and both ask to ' + + 'suspend, and only the first suspension is kept. Measured on the real engine with the real approval ' + + 'service: a start node fanning out to two approval steps registered and ran, ONE run then held two ' + + '`pending` requests, only the first held the run\'s suspension, and deciding the second answered ' + + '`RESUME_TARGET_LOST` — the approver decides and the run never moves. Beside a `wait` or a `screen` ' + + 'the run parked at the other node, and the approval\'s decision resumed it from THERE. The same limit ' + + 'was ruled 禁 for a structured region body (a durable pause where the run cannot park), refused there ' + + 'by type at authoring; this is that limit\'s authoring-time enforcement on the top-level graph. The ' + + 'engine is deliberately not made to serialise the branches, which would make a parallel shape pause. ' + + 'Judged on ANY path down a branch, conditions included: the parse cannot tell which conditions can ' + + 'hold together, and two branches each reaching an approval through a condition broke exactly the same ' + + 'way when both held. ⛔ NOT losslessly convertible: the rewrite is a graph rewrite whose intended shape ' + + 'no artifact records, so this is a D3 structured TODO naming the fan-out node and each branch. Not ' + + 'reached by this parse, and met at run time only: a `subflow` / `map` on a concurrent branch whose ' + + 'child pauses, and a pausing node type contributed by a plugin.', + acceptanceCriteria: + 'No node of the stack\'s flows fans out over unconditional edges to two or more branches that each reach ' + + 'an `approval`, `approval_revise`, `screen` or `wait` node. `FlowSchema.parse` (and therefore ' + + '`defineFlow`, `registerFlow`, `os validate` and a Studio save or publish) accepts every flow; a flow ' + + 'still carrying the shape is refused with one message naming the fan-out node and each pausing branch ' + + '(`Node \\`start\\` fans out to concurrent branches that each reach a node that parks the run — edge ' + + '\\`f1\\` (\\`start\\` → \\`a_review\\`) reaches \\`a_review\\` (\\`approval\\`); …`), anchored at the ' + + 'edge that opens the second pausing branch. A stored flow carrying the shape no longer registers until ' + + 'it is rewritten. Behaviour to re-check after the rewrite, because it changes on purpose: chained steps ' + + 'now open their requests one after the other, and a single `unanimous` step opens one request for all ' + + 'approver groups.', +}; From e96346dacb249a14726a650e407f90c50d5299c6 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 08:33:58 +0000 Subject: [PATCH 5/8] fix(spec): a label-routed decision with no fallback edge is one more concurrent group; fault and isDefault filters pinned Claude-Session: https://claude.ai/code/session_01QSeKYnrQ7UMtHofKQVjcH2 Co-authored-by: Claude --- .../automation/flow-concurrent-pause.test.ts | 65 ++++++++++++-- .../src/automation/flow-concurrent-pause.ts | 89 +++++++++++++++---- 2 files changed, 134 insertions(+), 20 deletions(-) diff --git a/packages/spec/src/automation/flow-concurrent-pause.test.ts b/packages/spec/src/automation/flow-concurrent-pause.test.ts index 66bd2205cfb..8d7382dd7a3 100644 --- a/packages/spec/src/automation/flow-concurrent-pause.test.ts +++ b/packages/spec/src/automation/flow-concurrent-pause.test.ts @@ -121,7 +121,7 @@ describe('a fan-out whose concurrent branches both reach a node that parks the r ['a_review', 'ok', { label: 'approve' }], ['b_review', 'ok', { label: 'approve' }], ]); expect(refusalsOf(flow).map(([path]) => path)).toEqual(['edges.1']); - expect(refusalsOf(flow)[0][1]).toContain('route them through one `decision` so exactly one is taken'); + expect(refusalsOf(flow)[0][1]).toContain('route them through one `decision` whose fallback edge is marked `isDefault: true`, so exactly one is taken'); }); it('three branches, two of which pause: one refusal, anchored on the second pausing branch', () => { @@ -133,6 +133,50 @@ describe('a fan-out whose concurrent branches both reach a node that parks the r }); }); +describe('a `decision` routing by label with no fallback edge runs every branch on a no-match run', () => { + // Measured in review on the real engine and the built-in `decision` + // executor: a record that matches no condition gets the `default` label, no + // out-edge claims it, and `traverseNext` runs every out-edge together. + const routed = (fallback: E[] = []) => flowOf([ + { id: 'route', type: 'decision', label: 'Route', config: { conditions: [ + { label: 'high', expression: 'record.amount > 1000' }, { label: 'low', expression: 'record.amount < 10' }, + ] } }, + approval('a_review'), approval('b_review'), end('ok'), end('other'), + ], [ + ['start', 'route'], ['route', 'a_review', { label: 'high' }], ['route', 'b_review', { label: 'low' }], + ['a_review', 'ok', { label: 'approve' }], ['b_review', 'ok', { label: 'approve' }], + ...fallback, + ]); + const unclaimed = (flow: Flow): Array<[string, string]> => { + const result = FlowSchema.safeParse(flow); + if (result.success) return []; + return result.error.issues + .filter((i) => i.message.includes('declares `config.conditions` but no fallback edge')) + .map((i) => [i.path.join('.'), i.message]); + }; + + it('is refused, anchored on the second pausing branch, prescribing the fallback edge', () => { + const refusals = unclaimed(routed()); + expect(refusals.map(([path]) => path)).toEqual(['edges.2']); + expect(refusals[0][1]).toContain( + 'Decision `route` declares `config.conditions` but no fallback edge — none of its out-edges is labelled ' + + '`default` or marked `isDefault: true` — and its branches reach nodes that park the run: ' + + 'edge `e1` (`route` → `a_review`) reaches `a_review` (`approval`); edge `e2` (`route` → `b_review`) reaches `b_review` (`approval`).', + ); + expect(refusals[0][1]).toContain('Mark the fallback edge `isDefault: true` (or label it `default`)'); + // The plain fan-out sentence does not fire as well: the label groups hold one edge each. + expect(refusalsOf(routed())).toEqual([]); + }); + + it('CONTROL: the same decision with its fallback edge marked `isDefault: true` parses', () => { + expect(parses(routed([['route', 'other', { isDefault: true }]]))).toBe(true); + }); + + it('CONTROL: the same decision with its fallback edge labelled `default` parses', () => { + expect(parses(routed([['route', 'other', { label: 'default' }]]))).toBe(true); + }); +}); + describe('controls: shapes that park at one place are accepted', () => { it('one pausing branch beside a synchronous branch that runs to its own end', () => { expect(parses(flowOf([approval('a_review'), step('x1'), step('x2'), end('ok'), end('ok2')], [ @@ -181,12 +225,23 @@ describe('controls: shapes that park at one place are accepted', () => { ]))).toBe(true); }); - it('a default edge beside a conditional one is an "otherwise", not a concurrent branch', () => { - expect(parses(flowOf([step('x1'), approval('a_review'), approval('b_review'), end('ok')], [ + it('an `isDefault` edge beside an UNCONDITIONAL sibling is taken on its own, never with it', () => { + // `traverseNext` awaits the default bucket before the unconditional one, so + // the two never run together; only the filter on `isDefault` keeps this + // node's concurrent set at one edge. + expect(refusalsOf(flowOf([step('x1'), approval('a_review'), approval('b_review'), end('ok')], [ ['start', 'x1'], - ['x1', 'a_review', { condition: 'record.amount > 5' }], ['x1', 'b_review', { isDefault: true }], + ['x1', 'a_review'], ['x1', 'b_review', { isDefault: true }], ['a_review', 'ok', { label: 'approve' }], ['b_review', 'ok', { label: 'approve' }], - ]))).toBe(true); + ]))).toEqual([]); + }); + + it('a `fault` edge beside a success edge to a second pausing node: the fault edge runs only instead', () => { + expect(refusalsOf(flowOf([step('x1'), approval('a_review'), approval('b_review'), end('ok')], [ + ['start', 'x1'], + ['x1', 'a_review'], ['x1', 'b_review', { type: 'fault' }], + ['a_review', 'ok', { label: 'approve' }], ['b_review', 'ok', { label: 'approve' }], + ]))).toEqual([]); }); }); diff --git a/packages/spec/src/automation/flow-concurrent-pause.ts b/packages/spec/src/automation/flow-concurrent-pause.ts index 95a1b4e7117..78673f96ea6 100644 --- a/packages/spec/src/automation/flow-concurrent-pause.ts +++ b/packages/spec/src/automation/flow-concurrent-pause.ts @@ -39,17 +39,34 @@ * - two edges carrying the same label out of an `approval`, to two approvals * (the decision takes every edge with its label, together); * - two branches each reaching an approval through an edge `condition`, both - * conditions holding. + * conditions holding; + * - a `decision` that declares `config.conditions` but no fallback edge (none + * labelled `default`, none `isDefault: true`), whose labelled branches reach + * two pausing nodes: when no condition matches, the executor picks the + * `default` label, no edge claims it, and `traverseNext` runs EVERY out-edge + * together (measured in review on the real engine and the built-in + * `decision` executor). * * Correct — not refused: * - one pausing branch beside branches that run synchronously, ending or not, * reconverging after the pause or not (the synchronous work completes in * line and the run parks at the one pause); * - an approval after a `parallel` region (the region joins before it); - * - an `approval`'s `approve` / `reject` edges, or a `decision`'s branches, - * each to its own approval (one branch is taken); - * - edge conditions on the fan-out node itself (they are evaluated one after - * another, never together). + * - an `approval`'s `approve` / `reject` edges, or the branches of a + * `decision` that has a fallback edge, each to its own approval (one branch + * is taken); + * - a `fault` edge beside a success edge (the fault edge is taken only when + * the node fails, instead of its success edges). + * + * Accepted — leaves no orphan request, though not every branch runs: + * - edge conditions on the fan-out node itself. They are evaluated one after + * another, never together, so two pauses never open; but when an earlier + * true branch pauses, a later true sibling never runs (measured) — a + * different defect from this one, not refused here; + * - an `isDefault` edge beside an unconditional one. `traverseNext` takes the + * default edge, awaited, before the unconditional bucket (read, not + * measured): one pause at most, and a pausing default edge unwinds the + * traversal before its unconditional sibling starts. * * ## What "concurrent" and "reaches" mean here — mirrored from the engine * @@ -59,6 +76,11 @@ * `approval`, an `approval_revise`, a `decision` that declares * `config.conditions`) runs only the edges carrying the picked label, so its * concurrent edges are grouped by `label`; every other node's are one group. + * One more group, for a `decision` that declares `config.conditions` and has + * no out-edge labelled `default` nor marked `isDefault`: the executor picks + * `default` when no condition matches, nothing claims it, and the engine then + * runs EVERY unconditional out-edge together — so that whole set is a group, + * and its refusal prescribes the fallback edge. * * A branch REACHES a pausing node along ANY path of the flow's edges from the * branch's target, conditions, defaults, faults and back-edges included — the @@ -77,8 +99,12 @@ * - A plugin-registered pausing type is invisible to a parse (ADR-0018). * - The top-level graph only: a region body may not hold a pausing node at * all (the region rule), so a fan-out inside one cannot reach one. - * - A label-picking node whose picked label no out-edge carries runs every - * out-edge (the engine warns); that misauthoring is not modelled here. + * - Any OTHER label a node picks that no out-edge carries also runs every + * out-edge (the engine warns); that is not modelled here, because the + * metadata door already refuses both shapes it can come from: a `decision` + * condition label no edge carries (`flow-branch-label-unmatched`) and an + * approval without exact `approve` / `reject` edges + * (`flow-approval-decision-unrouted`). * * Reads the parsed top-level `nodes` / `edges` defensively: this runs inside * the `FlowSchema` parse, so a malformed member (no string `id`, an edge with @@ -86,6 +112,7 @@ */ import { APPROVAL_NODE_TYPE, APPROVAL_REVISE_NODE_TYPE } from './approval.zod'; +import { FLOW_DECISION_DEFAULT_BRANCH_LABEL } from './flow-altitude'; /** One refusal, anchored on the edge that opens a further pausing branch. */ export interface ConcurrentPauseRefusal { @@ -135,17 +162,34 @@ function picksBranchByLabel(node: NodeView): boolean { return Array.isArray(conditions) && conditions.length > 0; } +/** One set of a node's out-edges the engine runs together; `unclaimedDefault` marks the decision fallback group. */ +interface ConcurrentGroup { readonly edges: EdgeView[]; readonly unclaimedDefault?: true } + +/** + * True for a `decision` that picks a branch by label (it declares + * `config.conditions`) and has no out-edge to claim its no-match pick: none + * labelled `default`, none marked `isDefault`. `traverseNext` then considers + * every out-edge for a run that matches no condition. + */ +function decisionDefaultUnclaimed(node: NodeView, outEdges: readonly EdgeView[]): boolean { + if (node.type !== 'decision' || !picksBranchByLabel(node)) return false; + return !outEdges.some((e) => e.type !== 'fault' && (e.label === FLOW_DECISION_DEFAULT_BRANCH_LABEL || e.isDefault === true)); +} + /** The groups of `node`'s out-edges the engine runs together, as `traverseNext` buckets them. */ -function concurrentGroups(node: NodeView, outEdges: readonly EdgeView[]): EdgeView[][] { +function concurrentGroups(node: NodeView, outEdges: readonly EdgeView[]): ConcurrentGroup[] { const unconditional = outEdges.filter((e) => e.type !== 'fault' && !e.condition && e.isDefault !== true); - if (!picksBranchByLabel(node)) return [unconditional]; + if (!picksBranchByLabel(node)) return [{ edges: unconditional }]; const byLabel = new Map(); for (const edge of unconditional) { const group = byLabel.get(edge.label); if (group) group.push(edge); else byLabel.set(edge.label, [edge]); } - return [...byLabel.values()]; + const groups: ConcurrentGroup[] = [...byLabel.values()].map((edges) => ({ edges })); + // A no-match run claims nothing, so every unconditional out-edge runs together. + if (decisionDefaultUnclaimed(node, outEdges)) groups.push({ edges: unconditional, unclaimedDefault: true }); + return groups; } const named = (edge: EdgeView): string => @@ -194,7 +238,7 @@ export function concurrentPauseRefusals( }; for (const node of nodes) { - for (const group of concurrentGroups(node, outEdges.get(node.id) ?? [])) { + for (const { edges: group, unclaimedDefault } of concurrentGroups(node, outEdges.get(node.id) ?? [])) { if (group.length < 2) continue; const pausing = group .map((edge) => ({ edge, pauses: pausesFrom(edge.target) })) @@ -204,6 +248,21 @@ export function concurrentPauseRefusals( .map(({ edge, pauses }) => `edge ${named(edge)} reaches ${pauses.map((p) => `\`${p.id}\` (\`${p.type}\`)`).join(', ')}`) .join('; '); + if (unclaimedDefault) { + out.push({ + path: ['edges', pausing[1].edge.index], + message: + `Decision \`${node.id}\` declares \`config.conditions\` but no fallback edge — none of its out-edges is ` + + `labelled \`${FLOW_DECISION_DEFAULT_BRANCH_LABEL}\` or marked \`isDefault: true\` — and its branches reach ` + + `nodes that park the run: ${branches}. When a run matches none of the conditions, the decision picks the ` + + `\`${FLOW_DECISION_DEFAULT_BRANCH_LABEL}\` branch, no edge claims it, and the engine runs EVERY out-edge ` + + 'together; a run parks at one place only, so the pause on the other branch is left with nothing to ' + + 'resume — an approval request opened there stays pending, and deciding it never moves the run. Mark ' + + `the fallback edge \`isDefault: true\` (or label it \`${FLOW_DECISION_DEFAULT_BRANCH_LABEL}\`), so a run ` + + 'that matches no condition takes exactly one branch.', + }); + continue; + } out.push({ path: ['edges', pausing[1].edge.index], message: @@ -213,10 +272,10 @@ export function concurrentPauseRefusals( + 'with nothing to resume — an approval request opened there stays pending, and deciding it never ' + 'moves the run. Chain the pausing steps one after another on a single branch; to have several ' + 'people approve at once, use one `approval` step with several approver groups (`behavior: ' - + "'unanimous'`); where only one of the branches should run, route them through one `decision` so " - + 'exactly one is taken. A `condition` further down a branch does not exempt it, because the flow ' - + 'cannot be checked for which conditions may hold together; and a `parallel` region is no way out ' - + 'either, because a region body cannot pause.', + + "'unanimous'`); where only one of the branches should run, route them through one `decision` whose " + + 'fallback edge is marked `isDefault: true`, so exactly one is taken. A `condition` further down a ' + + 'branch does not exempt it, because the flow cannot be checked for which conditions may hold ' + + 'together; and a `parallel` region is no way out either, because a region body cannot pause.', }); } } From 0ff60730c66b843e8ddd56932ecb36320be209ba Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 08:36:00 +0000 Subject: [PATCH 6/8] docs+changeset: a decision routes to exactly one branch only with its fallback edge marked Claude-Session: https://claude.ai/code/session_01QSeKYnrQ7UMtHofKQVjcH2 Co-authored-by: Claude --- .changeset/38838-fanout-pause-refusal.md | 6 +++--- content/docs/automation/flows.mdx | 10 ++++++++-- .../19.flow-concurrent-branch-durable-pause-refused.ts | 8 ++++++-- 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/.changeset/38838-fanout-pause-refusal.md b/.changeset/38838-fanout-pause-refusal.md index 99755378903..52e4e53f68c 100644 --- a/.changeset/38838-fanout-pause-refusal.md +++ b/.changeset/38838-fanout-pause-refusal.md @@ -7,13 +7,13 @@ fix(spec)!: a flow whose node fans out to two or more branches that each reach a Clause-②: no (narrowing) Metadata-protocol: narrowed -**BREAKING** for a flow author: FROM a flow in which one node's out-edges with no `condition` (not `isDefault`, not `fault`) lead two or more branches, along any path, to an `approval`, `approval_revise`, `screen` or `wait` node registering and running, TO that flow refused by the flow schema, at every door (`objectstack validate`, the metadata save, draft or active, and publish with `422 INVALID_METADATA`, and `registerFlow`), with one message naming the fan-out node and each pausing branch. The one-line fix: chain the pausing steps one after another on a single branch; where several people must approve at once, use one `approval` step with several approver groups and `behavior: 'unanimous'`; where only one branch should run, put a `decision` in front of them. +**BREAKING** for a flow author: FROM a flow in which one node's out-edges with no `condition` (not `isDefault`, not `fault`) lead two or more branches, along any path, to an `approval`, `approval_revise`, `screen` or `wait` node registering and running, TO that flow refused by the flow schema, at every door (`objectstack validate`, the metadata save, draft or active, and publish with `422 INVALID_METADATA`, and `registerFlow`), with one message naming the fan-out node and each pausing branch. The one-line fix: chain the pausing steps one after another on a single branch; where several people must approve at once, use one `approval` step with several approver groups and `behavior: 'unanimous'`; where only one branch should run, put a `decision` in front of them with its fallback edge marked `isDefault: true`. Why. The engine runs a node's unconditional out-edges together and a run parks at one place. Two concurrent pauses both did their on-entry work and only the first was kept: a start node fanning out to two approval steps opened two `pending` requests in one run, only the first held the run's suspension, and deciding the second answered `RESUME_TARGET_LOST`, so the approver decided and the run never moved. Beside a `wait` or a `screen`, the approval's decision resumed the run from the other node. This is the limit already refused by type inside a `loop` / `parallel` / `try_catch` body, now refused on the top-level graph; the engine is not made to serialise the branches. -What is refused: two branches that each reach a pausing node, through any path, `condition`s, `decision`s and back-edges included (the parse cannot tell which conditions can hold together), and two branches merging into one pausing node, which the engine runs once per arriving branch. On an `approval` / `approval_revise` node, and on a `decision` that declares `config.conditions`, only out-edges sharing one `label` run together, so two edges labelled `approve` to two steps are refused and `approve` / `reject` edges to two steps are not. +What is refused: two branches that each reach a pausing node, through any path, `condition`s, `decision`s and back-edges included (the parse cannot tell which conditions can hold together), and two branches merging into one pausing node, which the engine runs once per arriving branch. On an `approval` / `approval_revise` node, and on a `decision` that declares `config.conditions`, only out-edges sharing one `label` run together, so two edges labelled `approve` to two steps are refused and `approve` / `reject` edges to two steps are not. A `decision` that declares `config.conditions` but no fallback edge (none labelled `default`, none `isDefault: true`) is refused when two of its branches reach a pausing node: a run matching no condition picks the `default` branch, no edge claims it, and the engine runs every out-edge together. The fix there: mark the fallback edge `isDefault: true` (or label it `default`). -Still accepted: one pausing branch beside branches that never pause, an approval after a `parallel` region, an approval's `approve` / `reject` edges each to its own step, a `decision`'s branches each to its own step, and conditioned out-edges of one node, which run one after another. Not judged: a `subflow` or `map` on a concurrent branch (whether it pauses is decided by the child flow it names) and a pausing node type a plugin registers. +Still accepted: one pausing branch beside branches that never pause, an approval after a `parallel` region, an approval's `approve` / `reject` edges each to its own step, the branches of a `decision` that has a fallback edge, each to its own step, and conditioned out-edges of one node, which run one after another. Not judged: a `subflow` or `map` on a concurrent branch (whether it pauses is decided by the child flow it names) and a pausing node type a plugin registers. A stored flow carrying the shape no longer registers until it is rewritten. No conversion rewrites it (which shape the author meant is not recorded); the ADR-0087 semantic entry `flow-concurrent-branch-durable-pause-refused` carries the rewrite to the upgrade guide. diff --git a/content/docs/automation/flows.mdx b/content/docs/automation/flows.mdx index af43d5fbc4b..40cba7994ef 100644 --- a/content/docs/automation/flows.mdx +++ b/content/docs/automation/flows.mdx @@ -1720,14 +1720,20 @@ active, a refused registration at the engine, an error at every path down a branch, through `condition`s, `decision`s and back-edges, since which conditions can hold together cannot be checked; two branches that merge into **one** approval are refused too, because the merged step runs once -per arriving branch. Write instead: +per arriving branch. So is a `decision` that declares `config.conditions` but +no fallback edge (none labelled `default`, none `isDefault: true`) when two of +its branches reach such a step: a run that matches no condition picks the +`default` branch, no edge claims it, and every out-edge runs together. Mark the +fallback edge `isDefault: true` (or label it `default`). Write instead: - the steps **one after another** on a single branch (`a_review` → `approve` → `b_review`); - **one** `approval` step with several approver groups and `behavior: 'unanimous'`, as above, when several people must sign off at once; -- a `decision` in front of the steps when only **one** of them should run. +- a `decision` in front of the steps when only **one** of them should run, + with its fallback edge marked `isDefault: true`, so a run that matches no + condition still takes exactly one branch. 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 diff --git a/packages/spec/src/migrations/entries/semantic/19.flow-concurrent-branch-durable-pause-refused.ts b/packages/spec/src/migrations/entries/semantic/19.flow-concurrent-branch-durable-pause-refused.ts index 034270823ba..22dc0818220 100644 --- a/packages/spec/src/migrations/entries/semantic/19.flow-concurrent-branch-durable-pause-refused.ts +++ b/packages/spec/src/migrations/entries/semantic/19.flow-concurrent-branch-durable-pause-refused.ts @@ -14,14 +14,18 @@ export const entry: SemanticMigration = { + 'a type that parks the run on every execution (`approval`, `approval_revise`, `screen`, `wait`). ' + 'The engine runs those out-edges together. On an `approval` / `approval_revise` node, and on a ' + '`decision` that declares `config.conditions`, only the out-edges sharing ONE `label` run together, ' - + 'so `approve` / `reject` edges to two steps are not the shape. Two branches merging into one pausing ' + + 'so `approve` / `reject` edges to two steps are not the shape — unless the `decision` declares no fallback ' + + 'edge (none labelled `default`, none `isDefault: true`): a run matching no condition picks `default`, no edge ' + + 'claims it, and every out-edge runs together, so its branches are judged as one group. Two branches merging into one pausing ' + 'node are the shape (the merged node runs once per arriving branch). ⛔ `subflow` and `map` are not ' + 'in the population: whether they pause is decided by the child flow they name, a different record.', replacement: 'Chain the pausing steps one after another on a single branch (`start → a_review → approve → ' + 'b_review`); where several people must approve at once, use ONE `approval` step with several approver ' + 'groups and `behavior: \'unanimous\'`; where only one of the branches should run, put a `decision` in ' - + 'front of them so exactly one is taken. A `parallel` region is not a replacement: a region body may ' + + 'front of them with its fallback edge marked `isDefault: true` (or labelled `default`), so exactly one is ' + + 'taken even when no condition matches; a `decision` refused for having no fallback edge needs only that ' + + 'edge marked. A `parallel` region is not a replacement: a region body may ' + 'not hold a pausing node at all.', reason: 'A run parks at ONE place. The engine runs a node\'s unconditional out-edges under `Promise.all`; when ' From 7ce8b4c575e41655557f37f5240e00dc6402e3b9 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 09:04:05 +0000 Subject: [PATCH 7/8] fix(spec): a decision with a literal true catch-all condition is exhaustive and owes no fallback edge Claude-Session: https://claude.ai/code/session_01QSeKYnrQ7UMtHofKQVjcH2 Co-authored-by: Claude --- .../automation/flow-concurrent-pause.test.ts | 30 +++++++++++++ .../src/automation/flow-concurrent-pause.ts | 43 ++++++++++++++++--- 2 files changed, 67 insertions(+), 6 deletions(-) diff --git a/packages/spec/src/automation/flow-concurrent-pause.test.ts b/packages/spec/src/automation/flow-concurrent-pause.test.ts index 8d7382dd7a3..bac47a82748 100644 --- a/packages/spec/src/automation/flow-concurrent-pause.test.ts +++ b/packages/spec/src/automation/flow-concurrent-pause.test.ts @@ -175,6 +175,36 @@ describe('a `decision` routing by label with no fallback edge runs every branch it('CONTROL: the same decision with its fallback edge labelled `default` parses', () => { expect(parses(routed([['route', 'other', { label: 'default' }]]))).toBe(true); }); + + /** The same two branches, the second condition replaced by `expression` (a catch-all candidate). */ + const catchAll = (expression: string) => flowOf([ + { id: 'route', type: 'decision', label: 'Route', config: { conditions: [ + { label: 'high', expression: 'record.amount > 1000' }, { label: 'low', expression }, + ] } }, + approval('a_review'), approval('b_review'), end('ok'), + ], [ + ['start', 'route'], ['route', 'a_review', { label: 'high' }], ['route', 'b_review', { label: 'low' }], + ['a_review', 'ok', { label: 'approve' }], ['b_review', 'ok', { label: 'approve' }], + ]); + + it.each(['true', ' true '])( + 'CONTROL: a literal `true` catch-all condition (%j) makes the decision exhaustive, so no fallback edge is owed', + (expression) => { + // Measured in review on the real engine: a matching record pauses at + // `a_review` only, any other at `b_review` only; the no-match pick is + // unreachable. The lint suite's own control for a label-routed decision. + expect(parses(catchAll(expression))).toBe(true); + }, + ); + + it('any OTHER always-true expression is not read as exhaustive: the parse does not evaluate it', () => { + expect(unclaimed(catchAll('1 == 1')).map(([path]) => path)).toEqual(['edges.2']); + expect(unclaimed(catchAll('(true)')).map(([path]) => path)).toEqual(['edges.2']); + }); + + it('a `fault` edge labelled `default` does not claim the no-match pick', () => { + expect(unclaimed(routed([['route', 'other', { label: 'default', type: 'fault' }]])).map(([path]) => path)).toEqual(['edges.2']); + }); }); describe('controls: shapes that park at one place are accepted', () => { diff --git a/packages/spec/src/automation/flow-concurrent-pause.ts b/packages/spec/src/automation/flow-concurrent-pause.ts index 78673f96ea6..5204ea50919 100644 --- a/packages/spec/src/automation/flow-concurrent-pause.ts +++ b/packages/spec/src/automation/flow-concurrent-pause.ts @@ -53,8 +53,8 @@ * line and the run parks at the one pause); * - an approval after a `parallel` region (the region joins before it); * - an `approval`'s `approve` / `reject` edges, or the branches of a - * `decision` that has a fallback edge, each to its own approval (one branch - * is taken); + * `decision` that has a fallback edge or a literal `true` catch-all + * condition, each to its own approval (one branch is taken); * - a `fault` edge beside a success edge (the fault edge is taken only when * the node fails, instead of its success edges). * @@ -64,8 +64,8 @@ * true branch pauses, a later true sibling never runs (measured) — a * different defect from this one, not refused here; * - an `isDefault` edge beside an unconditional one. `traverseNext` takes the - * default edge, awaited, before the unconditional bucket (read, not - * measured): one pause at most, and a pausing default edge unwinds the + * default edge, awaited, before the unconditional bucket (measured in + * review): one pause at most, and a pausing default edge unwinds the * traversal before its unconditional sibling starts. * * ## What "concurrent" and "reaches" mean here — mirrored from the engine @@ -82,6 +82,22 @@ * runs EVERY unconditional out-edge together — so that whole set is a group, * and its refusal prescribes the fallback edge. * + * EXHAUSTIVE decisions add no such group. A `decision` one of whose + * `config.conditions` has the expression `true` — a string whose trimmed text + * is exactly `true`, the CEL literal the executor evaluates it as + * (`{ dialect: 'cel', source: expression }`) — always matches a condition, so + * the no-match pick is unreachable: the run takes that branch, or an earlier + * one that matched, or fails on an earlier condition that faulted, and never + * opens two pauses (measured in review on the real engine). Only that literal + * reads as exhaustive. Any other always-true expression (`1 == 1`, `(true)`, + * `!false`, a set of conditions that together cover every record) would have + * to be evaluated or proved, which the parse does not do, so it is still + * refused, and the prescription still holds for it: mark one branch edge + * `isDefault: true`. A non-string `expression` is not one either; it is + * refused at `registerFlow` and `objectstack validate` on its own. A catch-all + * whose label no edge carries runs every out-edge too, but that is the + * door's `flow-branch-label-unmatched` refusal, not this one. + * * A branch REACHES a pausing node along ANY path of the flow's edges from the * branch's target, conditions, defaults, faults and back-edges included — the * reading `save-notice-placement.ts` takes for the same reason: the parse @@ -169,13 +185,26 @@ interface ConcurrentGroup { readonly edges: EdgeView[]; readonly unclaimedDefaul * True for a `decision` that picks a branch by label (it declares * `config.conditions`) and has no out-edge to claim its no-match pick: none * labelled `default`, none marked `isDefault`. `traverseNext` then considers - * every out-edge for a run that matches no condition. + * every out-edge for a run that matches no condition. False for an exhaustive + * decision, one of whose conditions is the literal `true` (header): it never + * makes the no-match pick. */ function decisionDefaultUnclaimed(node: NodeView, outEdges: readonly EdgeView[]): boolean { if (node.type !== 'decision' || !picksBranchByLabel(node)) return false; + if (hasLiteralTrueCondition(node)) return false; return !outEdges.some((e) => e.type !== 'fault' && (e.label === FLOW_DECISION_DEFAULT_BRANCH_LABEL || e.isDefault === true)); } +/** True when one of the decision's `config.conditions` is the literal CEL `true` (trimmed string), so a condition always matches. */ +function hasLiteralTrueCondition(node: NodeView): boolean { + const conditions = (node.config as { conditions?: unknown } | undefined)?.conditions; + if (!Array.isArray(conditions)) return false; + return conditions.some((c) => { + const expression = (c as { expression?: unknown } | null)?.expression; + return typeof expression === 'string' && expression.trim() === 'true'; + }); +} + /** The groups of `node`'s out-edges the engine runs together, as `traverseNext` buckets them. */ function concurrentGroups(node: NodeView, outEdges: readonly EdgeView[]): ConcurrentGroup[] { const unconditional = outEdges.filter((e) => e.type !== 'fault' && !e.condition && e.isDefault !== true); @@ -259,7 +288,9 @@ export function concurrentPauseRefusals( + 'together; a run parks at one place only, so the pause on the other branch is left with nothing to ' + 'resume — an approval request opened there stays pending, and deciding it never moves the run. Mark ' + `the fallback edge \`isDefault: true\` (or label it \`${FLOW_DECISION_DEFAULT_BRANCH_LABEL}\`), so a run ` - + 'that matches no condition takes exactly one branch.', + + 'that matches no condition takes exactly one branch; marking one existing branch edge ' + + '`isDefault: true` is enough. Conditions that cover every record are refused all the same unless one ' + + 'of them is the literal `true`, because the flow cannot be checked for which records they cover.', }); continue; } From ddae2cf6081495018b5d1091cb7b3a3a33cc888f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 09:04:29 +0000 Subject: [PATCH 8/8] docs+changeset: a literal true catch-all makes a decision exhaustive; other always-true conditions stay refused Claude-Session: https://claude.ai/code/session_01QSeKYnrQ7UMtHofKQVjcH2 Co-authored-by: Claude --- .changeset/38838-fanout-pause-refusal.md | 2 +- content/docs/automation/flows.mdx | 7 ++++++- .../19.flow-concurrent-branch-durable-pause-refused.ts | 9 ++++++--- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/.changeset/38838-fanout-pause-refusal.md b/.changeset/38838-fanout-pause-refusal.md index 52e4e53f68c..9f18120a176 100644 --- a/.changeset/38838-fanout-pause-refusal.md +++ b/.changeset/38838-fanout-pause-refusal.md @@ -11,7 +11,7 @@ Metadata-protocol: narrowed Why. The engine runs a node's unconditional out-edges together and a run parks at one place. Two concurrent pauses both did their on-entry work and only the first was kept: a start node fanning out to two approval steps opened two `pending` requests in one run, only the first held the run's suspension, and deciding the second answered `RESUME_TARGET_LOST`, so the approver decided and the run never moved. Beside a `wait` or a `screen`, the approval's decision resumed the run from the other node. This is the limit already refused by type inside a `loop` / `parallel` / `try_catch` body, now refused on the top-level graph; the engine is not made to serialise the branches. -What is refused: two branches that each reach a pausing node, through any path, `condition`s, `decision`s and back-edges included (the parse cannot tell which conditions can hold together), and two branches merging into one pausing node, which the engine runs once per arriving branch. On an `approval` / `approval_revise` node, and on a `decision` that declares `config.conditions`, only out-edges sharing one `label` run together, so two edges labelled `approve` to two steps are refused and `approve` / `reject` edges to two steps are not. A `decision` that declares `config.conditions` but no fallback edge (none labelled `default`, none `isDefault: true`) is refused when two of its branches reach a pausing node: a run matching no condition picks the `default` branch, no edge claims it, and the engine runs every out-edge together. The fix there: mark the fallback edge `isDefault: true` (or label it `default`). +What is refused: two branches that each reach a pausing node, through any path, `condition`s, `decision`s and back-edges included (the parse cannot tell which conditions can hold together), and two branches merging into one pausing node, which the engine runs once per arriving branch. On an `approval` / `approval_revise` node, and on a `decision` that declares `config.conditions`, only out-edges sharing one `label` run together, so two edges labelled `approve` to two steps are refused and `approve` / `reject` edges to two steps are not. A `decision` that declares `config.conditions` but no fallback edge (none labelled `default`, none `isDefault: true`) is refused when two of its branches reach a pausing node: a run matching no condition picks the `default` branch, no edge claims it, and the engine runs every out-edge together. The fix there: mark the fallback edge `isDefault: true` (or label it `default`); marking one existing branch edge `isDefault: true` is enough. A decision one of whose conditions is the literal `true` (`expression: 'true'`) always matches, so it is exhaustive and is not refused; any other always-true expression, or conditions that together cover every record, is refused all the same, because the parse does not check coverage. Still accepted: one pausing branch beside branches that never pause, an approval after a `parallel` region, an approval's `approve` / `reject` edges each to its own step, the branches of a `decision` that has a fallback edge, each to its own step, and conditioned out-edges of one node, which run one after another. Not judged: a `subflow` or `map` on a concurrent branch (whether it pauses is decided by the child flow it names) and a pausing node type a plugin registers. diff --git a/content/docs/automation/flows.mdx b/content/docs/automation/flows.mdx index 40cba7994ef..2829d643fbe 100644 --- a/content/docs/automation/flows.mdx +++ b/content/docs/automation/flows.mdx @@ -1724,7 +1724,12 @@ per arriving branch. So is a `decision` that declares `config.conditions` but no fallback edge (none labelled `default`, none `isDefault: true`) when two of its branches reach such a step: a run that matches no condition picks the `default` branch, no edge claims it, and every out-edge runs together. Mark the -fallback edge `isDefault: true` (or label it `default`). Write instead: +fallback edge `isDefault: true` (or label it `default`); marking one existing +branch edge `isDefault: true` is enough. A decision one of whose conditions is +the literal `true` (`expression: 'true'`) always matches a condition, so it is +exhaustive and owes no fallback edge; any other expression or set of conditions +that covers every record is still refused, because the flow cannot be checked +for that. Write instead: - the steps **one after another** on a single branch (`a_review` → `approve` → `b_review`); diff --git a/packages/spec/src/migrations/entries/semantic/19.flow-concurrent-branch-durable-pause-refused.ts b/packages/spec/src/migrations/entries/semantic/19.flow-concurrent-branch-durable-pause-refused.ts index 22dc0818220..44d77613a0f 100644 --- a/packages/spec/src/migrations/entries/semantic/19.flow-concurrent-branch-durable-pause-refused.ts +++ b/packages/spec/src/migrations/entries/semantic/19.flow-concurrent-branch-durable-pause-refused.ts @@ -16,7 +16,9 @@ export const entry: SemanticMigration = { + '`decision` that declares `config.conditions`, only the out-edges sharing ONE `label` run together, ' + 'so `approve` / `reject` edges to two steps are not the shape — unless the `decision` declares no fallback ' + 'edge (none labelled `default`, none `isDefault: true`): a run matching no condition picks `default`, no edge ' - + 'claims it, and every out-edge runs together, so its branches are judged as one group. Two branches merging into one pausing ' + + 'claims it, and every out-edge runs together, so its branches are judged as one group — unless one of its ' + + 'conditions is the literal `true` (`expression: \'true\'`), which always matches and makes the decision ' + + 'exhaustive; any other always-true expression is not read as one. Two branches merging into one pausing ' + 'node are the shape (the merged node runs once per arriving branch). ⛔ `subflow` and `map` are not ' + 'in the population: whether they pause is decided by the child flow they name, a different record.', replacement: @@ -24,8 +26,9 @@ export const entry: SemanticMigration = { + 'b_review`); where several people must approve at once, use ONE `approval` step with several approver ' + 'groups and `behavior: \'unanimous\'`; where only one of the branches should run, put a `decision` in ' + 'front of them with its fallback edge marked `isDefault: true` (or labelled `default`), so exactly one is ' - + 'taken even when no condition matches; a `decision` refused for having no fallback edge needs only that ' - + 'edge marked. A `parallel` region is not a replacement: a region body may ' + + 'taken even when no condition matches; a `decision` refused for having no fallback edge needs only one of ' + + 'its existing branch edges marked `isDefault: true` (or a literal `true` catch-all condition). A `parallel` ' + + 'region is not a replacement: a region body may ' + 'not hold a pausing node at all.', reason: 'A run parks at ONE place. The engine runs a node\'s unconditional out-edges under `Promise.all`; when '