diff --git a/.changeset/38838-fanout-pause-refusal.md b/.changeset/38838-fanout-pause-refusal.md index 9f18120a176..38e5b429094 100644 --- a/.changeset/38838-fanout-pause-refusal.md +++ b/.changeset/38838-fanout-pause-refusal.md @@ -13,7 +13,7 @@ Why. The engine runs a node's unconditional out-edges together and a run parks a 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. +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, and the branches of a `decision` that has a fallback edge, each to its own step. Conditioned out-edges of one node run one after another, so they never pause together; a branch among them that parks before another is refused by its sibling rule, `flow-sequential-branch-durable-pause-refused`. 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/.changeset/38875-conditioned-edge-pause-drop.md b/.changeset/38875-conditioned-edge-pause-drop.md new file mode 100644 index 00000000000..e0e80534413 --- /dev/null +++ b/.changeset/38875-conditioned-edge-pause-drop.md @@ -0,0 +1,20 @@ +--- +'@objectstack/spec': minor +--- + +fix(spec)!: a flow whose node takes a branch that parks the run before another out-edge is refused at authoring + +Clause-②: no (narrowing) +Metadata-protocol: narrowed + +**BREAKING** for a flow author: FROM a flow registering and running in which one node takes an out-edge whose branch reaches, along any path, an `approval`, `approval_revise`, `screen` or `wait` node before another out-edge of the same traversal, 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 node, the edge whose branch parks the run, and the edges it leaves untaken. The one-line fix: make the branch that parks the last one the node takes (declare its edge after its conditioned siblings, with no unconditional sibling beside it), or chain the steps onto one branch; where only one branch should run, route them through a `decision` (exclusive by default), or delete `mode: 'inclusive'` from the `decision` that carries it; on a `decision` that already takes only the first true edge, mark the unconditional otherwise-branch `isDefault: true` and keep one `isDefault` edge per node. + +Why. The engine takes a node's out-edges in a fixed order, each awaited before the next: its conditioned edges in declaration order (every one whose condition holds, except on a `decision` without `mode: 'inclusive'`, which takes only the first), then its `isDefault` edges when no condition held, then its unconditional edges together. A run parks at one place, and on resume it continues from the node that parked, never back at the node it was traversing. So when an earlier branch parks, the later edges are never taken: a node with two conditioned out-edges, both true, to two approval steps ran the first, parked, and after its decision completed the run with the second step never opened and no error anywhere. No approval request is orphaned; a branch whose condition holds is silently dropped. + +What is refused, each measured on the real engine before the rule: two conditioned edges, the earlier one reaching a pausing node (the later one pausing or not), on any node but an exclusive `decision`, an inclusive `decision` included; a conditioned or `isDefault` edge reaching a pausing node beside an unconditional sibling, whichever is declared first, on any node, an exclusive `decision` included; an `isDefault` edge reaching a pausing node before a later `isDefault` edge of the same node; and, on a `decision` that declares `config.conditions`, the run matching none of them: with no edge labelled `default` every `isDefault` edge is claimed whatever its label and taken in turn, and with no claimant at all every out-edge is taken in the order above. Conditions are judged as if they may all hold, as the fan-out rule judges them, because the parse cannot tell which conditions can hold together: two conditioned edges whose conditions exclude each other are refused too, and the prescription names the `decision` that makes the choice explicit. + +Still accepted: the last conditioned branch reaching a pausing node (the earlier ones have run), an exclusive `decision`'s conditioned branches, an `isDefault` edge beside conditioned ones (it runs only when none held), a `fault` edge, and an approval's `approve` / `reject` edges, judged per label. Not judged: a `subflow` or `map` whose child pauses (whether it pauses is decided by the child flow it names; it drops the later edges at run time all the same) 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-sequential-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 2829d643fbe..3d2e387f90c 100644 --- a/content/docs/automation/flows.mdx +++ b/content/docs/automation/flows.mdx @@ -1742,11 +1742,51 @@ for that. Write instead: A `parallel` region is no way out: a region body may not hold a pausing step at all. Still accepted: one pausing branch beside branches that run without -pausing, an approval after a `parallel` region, 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 +pausing, an approval after a `parallel` region, and an approval's `approve` / +`reject` edges each to its own step. Not judged here: a `subflow` or `map` on a concurrent branch, whose pause is decided by the child flow it names. +**A branch that parks the run, taken before another out-edge, is refused.** +A node takes its out-edges in a fixed order, each one finished before the +next: its conditioned edges in the order they are declared (every one whose +condition holds, except on a `decision` without `mode: 'inclusive'`, which +takes only the first), then its `isDefault` edge when no condition held, then +its unconditional edges together. A run that parks inside an earlier branch +resumes from the step it parked at and never comes back to the node, so the +edges it had not taken yet are never taken, and nothing reports it. The flow +schema refuses that shape at the same doors, naming the node, the edge whose +branch parks the run and the edges it would leave untaken: + +- two conditioned edges out of one node, the earlier one reaching a pausing + step, on any node but an exclusive `decision` (an inclusive one included); +- a conditioned or `isDefault` edge reaching a pausing step beside an + unconditional sibling, whichever is declared first; +- an `isDefault` edge reaching a pausing step before a later `isDefault` edge + of the same node; +- on a `decision` that declares `config.conditions`, the run that matches none + of them: with no edge labelled `default`, every `isDefault` edge is claimed, + whatever its label, and taken in turn; with no claimant at all, every + out-edge is taken in the order above. + +Conditions are judged as if they may all hold, so two conditioned edges whose +conditions exclude each other are refused too. Write instead: + +- the branch that parks as the **last** one the node takes: its edge declared + after its conditioned siblings, with no unconditional sibling beside it; +- the steps **chained** onto one branch, so the work after the pause runs when + the run resumes; +- a `decision` in front of the branches when only **one** of them should run + (it takes only the first edge whose condition holds), or `mode: 'inclusive'` + deleted from the `decision` that carries it. + +Two branches that each park the run cannot both be taken from one node in any +order: chain them. On a `decision` that already takes only the first true edge, +an unconditional sibling meant as the otherwise-branch is marked +`isDefault: true` instead; keep one `isDefault` edge per node. Still accepted: +the last conditioned branch reaching a pausing step, an exclusive `decision`'s +branches, an `isDefault` edge beside conditioned ones, and a `fault` edge. A `subflow` or `map` whose child pauses +drops the later edges all the same, and is not judged here either. + ### 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 @@ -2094,9 +2134,13 @@ edges: [ ``` `e_no` runs **only** when `e_yes`'s condition was false. Drop `isDefault` and -`e_no` becomes an ordinary unconditional out-edge that runs on **every** pass — -in parallel with `abort` — so an already-converted lead sees the abort screen -*and* walks into the wizard behind it. Writing the negation of every sibling +`e_no` becomes an ordinary unconditional out-edge, taken on **every** pass +after the conditioned edges are done: with a synchronous `abort` step an +already-converted lead gets the abort step *and* then walks into the wizard +behind it; with `abort` a `screen`, the run parks there and `e_no` is never +taken, so the flow schema refuses that spelling outright (a branch that parks +the run before an unconditional sibling, see *Parallel approvals* under +*Durable pause & resume*). Writing the negation of every sibling condition by hand is the only other correct spelling; `isDefault` is the one that stays correct when a third branch is added. 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 abdfa434c64..b9652e0ddb6 100644 --- a/packages/plugins/plugin-approvals/src/flow-route.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/flow-route.integration.test.ts @@ -45,7 +45,7 @@ * both sides on purpose: the trunk is served unchanged. */ -import { describe, it, expect, beforeAll, beforeEach, afterAll, afterEach } from 'vitest'; +import { describe, it, expect, beforeAll, beforeEach, afterAll } from 'vitest'; import { ObjectKernel } from '@objectstack/core'; import { ObjectQL, ObjectQLPlugin } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; @@ -253,16 +253,72 @@ const unconditionalFanOut = (name: string) => ({ ], }); -/** [#38838] The same two steps behind two edge conditions out of one node: one is taken. */ -const conditionalFanOut = (name: string) => ({ - ...unconditionalFanOut(name), +/** + * [#38838] The same two steps behind a `decision`'s two conditioned edges: one is taken. + * [#38875] Through a `decision`, not two edge conditions out of `start`: a + * non-decision node takes every conditioned edge whose condition holds, one + * after another, and a first branch that parks leaves the second untaken — + * that shape is refused at publish (the describe at the foot of this file). + */ +const conditionalFanOut = (name: string) => { + const base = unconditionalFanOut(name); + return { + ...base, + nodes: [...base.nodes, { id: 'route', type: 'decision', label: 'Route' }], + edges: [ + { id: 'f0', source: 'start', target: 'route' }, + { id: 'f1', source: 'route', target: 'a_review', condition: 'record.amount < 1000' }, + { id: 'f2', source: 'route', target: 'b_review', condition: 'record.amount >= 1000' }, + ...ROUTED_DECISIONS, + ], + }; +}; + +/** + * [#38875] Two conditioned edges out of one non-decision node, both true: the + * card's shape. The node takes them one after another; `a_review` parks the + * run first, and on resume the run continues from `a_review`, never back at + * `x1`, so `b_review` is never taken. Refused at publish now. + */ +const conditionedBranchesBothTrue = (name: string) => ({ + name, label: 'Conditioned branches', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'x1', type: 'assignment', label: 'X1', config: { assignments: { took_x1: 'yes' } } }, + 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', condition: 'record.amount < 1000' }, - { id: 'f2', source: 'start', target: 'b_review', condition: 'record.amount >= 1000' }, + { id: 'c0', source: 'start', target: 'x1' }, + { id: 'c1', source: 'x1', target: 'a_review', condition: 'true' }, + { id: 'c2', source: 'x1', target: 'b_review', condition: 'true' }, ...ROUTED_DECISIONS, ], }); +/** [#38875] The prescription: the branch that parks is the last one `x1` takes, so the one before it has run. */ +const pausingBranchLast = (name: string) => ({ + name, label: 'Pausing branch last', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'x1', type: 'assignment', label: 'X1', config: { assignments: { took_x1: 'yes' } } }, + { id: 's_sync', type: 'assignment', label: 'Sync', config: { assignments: { took_sync: 'yes' } } }, + step('a_review', 'A', 'u_mgr'), + { id: 'ok', type: 'end', label: 'Ok' }, + { id: 'no', type: 'end', label: 'Rejected' }, + { id: 'synced', type: 'end', label: 'Synced' }, + ], + edges: [ + { id: 'c0', source: 'start', target: 'x1' }, + { id: 'c1', source: 'x1', target: 's_sync', condition: 'true' }, + { id: 'c2', source: 'x1', target: 'a_review', condition: 'true' }, + { id: 'c3', source: 's_sync', target: 'synced' }, + ...ROUTED_DECISIONS.slice(0, 2), + ], +}); + /** What `flow_steps` serves for every `contract_approval` request: its trunk. */ const CONTRACT_TRUNK = ['manager_review', 'legal_finance_joint', 'executive_signoff', 'gm_signoff']; @@ -754,6 +810,22 @@ describe('the approval-ended witness is the content of the body the run ran, dur expect((await automation.getRun(a.flow_run_id))?.status, 'the decision moved the run to its end').toBe('completed'); }); + it('[#38875] CONTROL: the branch that parks taken LAST, every earlier true branch has run, and the decision ends the run', async () => { + // The prescription the refusal at the foot of this file gives, run on the + // real engine: `s_sync` runs before `a_review` parks, one request opens, + // and its decision moves the run to its end. + const svc = newService(); + const name = 'witness_pausing_branch_last'; + const automation = bootEngine(svc, pausingBranchLast(name)); + const a = await submit(automation, name); + expect(a.flow_node_id).toBe('a_review'); + expect(await decide(svc, a, 'u_mgr', 'approve'), 'nothing pending after the one decision').toBeUndefined(); + const run = await automation.getRun(a.flow_run_id); + expect(run?.status, 'the decision moved the run to its end').toBe('completed'); + expect(run?.steps.filter((s) => s.status === 'success').map((s) => s.nodeId), 'the earlier true branch ran') + .toEqual(expect.arrayContaining(['x1', 's_sync', 'a_review'])); + }); + it('CONTROL: a run of the edited body itself, read on a replica that holds that body, serves "ended"', async () => { const runner = newService(); const reader = newService(); @@ -789,7 +861,13 @@ describe('[#38838] a fan-out to two approval steps is refused at publish', () => let ql: ObjectQL; let protocol: any; - afterEach(async () => { + // ONE kernel for the describe (#38976): a cold `kernel.bootstrap()` per case + // pushed the first case past vitest's 5 s default on loaded CI shards. The + // cases share it safely: each saves under its own flow name and reads back + // only that name; the refusals write nothing, and the one write (the + // control's publish) is a row no other case reads. + beforeAll(() => boot(), 30_000); + afterAll(async () => { try { await kernel?.shutdown(); } catch { /* noop */ } }); @@ -815,7 +893,6 @@ describe('[#38838] a fan-out to two approval steps is refused at publish', () => 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); @@ -829,7 +906,6 @@ describe('[#38838] a fan-out to two approval steps is refused at publish', () => 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 err = await protocol.saveMetaItem({ type: 'flow', name: 'fan_out_draft', item: unconditionalFanOut('fan_out_draft'), packageId: PKG, mode: 'draft', }).catch((e: any) => e); @@ -846,7 +922,6 @@ describe('[#38838] a fan-out to two approval steps is refused at publish', () => }); 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, }); @@ -854,3 +929,90 @@ describe('[#38838] a fan-out to two approval steps is refused at publish', () => expect(await activeRows('fan_out_conditional')).toHaveLength(1); }); }); + +/** + * [#38875] A node whose conditioned out-edges both hold, the first leading to + * an approval, is refused at save and publish — the sequential twin of the + * fan-out refusal above, by the same ruling. Measured before the rule on the + * witness rig: the flow registered and ran, `a_review` opened and parked the + * run, `b_review` never opened, and after `a_review`'s decision the run + * completed with `b_review` never run, no error anywhere. The rule lives + * beside the fan-out rule (`flow-concurrent-pause.ts`), so every door that + * parses a flow refuses it; pinned here at the metadata door with the ADR-0112 + * envelope, and at `registerFlow`. + * + * ⚠️ Direction, measured: on a spec built without the rule the active save, + * the draft save and the registration below all succeed (RED); the control is + * green on both. + */ +describe('[#38875] a branch that parks the run, taken before a sibling, is refused at publish', () => { + const PKG = 'app.crm'; + let kernel: ObjectKernel; + let ql: ObjectQL; + let protocol: any; + + // ONE kernel for the describe (#38976): a cold `kernel.bootstrap()` per case + // pushed the first case past vitest's 5 s default on loaded CI shards. The + // cases share it safely: each saves under its own flow name and reads back + // only that name; the refusals write nothing, and the one write (the + // control's publish) is a row no other case reads. + beforeAll(() => boot(), 30_000); + afterAll(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 rows = async (name: string) => + (await ql.find('sys_metadata', { where: { type: 'flow', name }, context: { isSystem: true } })) as any[]; + const refusalText = (err: any) => JSON.stringify({ message: err?.message, issues: err?.issues ?? err?.details }); + const LEAD = 'Node `x1` takes edge `c1` (`x1` → `a_review`) before `c2` (`x1` → `b_review`)'; + + it('an active save is refused with 422 INVALID_METADATA, naming the node, the parking branch and the untaken edge', async () => { + const err = await protocol.saveMetaItem({ + type: 'flow', name: 'branches_active', item: conditionedBranchesBothTrue('branches_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('reaches `a_review` (`approval`), a node that parks the run'); + expect(await rows('branches_active')).toEqual([]); + }); + + it('a draft save is refused too: the flow schema is judged at every save, a draft included', async () => { + const err = await protocol.saveMetaItem({ + type: 'flow', name: 'branches_draft', item: conditionedBranchesBothTrue('branches_draft'), packageId: PKG, mode: 'draft', + }).catch((e: any) => e); + expect(err).toBeInstanceOf(Error); + expect(err).toMatchObject({ code: 'INVALID_METADATA', status: 422 }); + expect(refusalText(err)).toContain(LEAD); + expect(await rows('branches_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('branches_engine', conditionedBranchesBothTrue('branches_engine'))).toThrow(LEAD); + }); + + it('CONTROL: the branch that parks taken last publishes', async () => { + const out = await protocol.saveMetaItem({ + type: 'flow', name: 'branches_last', item: pausingBranchLast('branches_last'), packageId: PKG, + }); + expect(out.success).toBe(true); + expect((await rows('branches_last')).filter((r) => r.state === 'active')).toHaveLength(1); + }); +}); diff --git a/packages/spec/src/automation/flow-concurrent-pause.test.ts b/packages/spec/src/automation/flow-concurrent-pause.test.ts index bac47a82748..52612c38680 100644 --- a/packages/spec/src/automation/flow-concurrent-pause.test.ts +++ b/packages/spec/src/automation/flow-concurrent-pause.test.ts @@ -18,7 +18,7 @@ */ 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'; +import { concurrentPauseRefusals, sequentialPauseRefusals } 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' } }); @@ -248,17 +248,23 @@ describe('controls: shapes that park at one place are accepted', () => { }); 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')], [ + // Not concurrent, so not THIS rule's. Its sequential twin refuses the shape + // all the same (the first branch parks before the second is taken): pinned + // in the describe below, and the fan-out sentence never fires on it. + 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', { condition: 'record.amount <= 5' }], ['a_review', 'ok', { label: 'approve' }], ['b_review', 'ok', { label: 'approve' }], - ]))).toBe(true); + ]))).toEqual([]); }); 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. + // node's concurrent set at one edge. Not THIS rule's — but its sequential + // twin refuses the shape at `edges.2` (the default branch parks before the + // unconditional sibling is taken): pinned in the describe below as the + // `isDefault` case, and the fan-out sentence never fires on it. expect(refusalsOf(flowOf([step('x1'), approval('a_review'), approval('b_review'), end('ok')], [ ['start', 'x1'], ['x1', 'a_review'], ['x1', 'b_review', { isDefault: true }], @@ -300,3 +306,287 @@ describe('the declared boundaries', () => { ).map((r) => r.path)).toEqual([['edges', 3]]); }); }); + +/** The sequential refusals of `flow` as `[path, message]`, judged through the real parse. */ +const droppedOf = (flow: Flow): Array<[string, string]> => { + const result = FlowSchema.safeParse(flow); + if (result.success) return []; + return result.error.issues + .filter((i) => i.message.includes('a node that parks the run. The engine takes a node\'s conditioned out-edges')) + .map((i) => [i.path.join('.'), i.message]); +}; + +/** + * Its sequential twin (#38875): a node takes its conditioned out-edges one + * after another, then its `isDefault` edge, then its unconditional edges + * together, and a run that parks inside an earlier branch resumes from the + * node it parked at, never back at the node — so every edge the node would + * have taken after a branch that parks is silently never taken. + * + * Measured on the real engine and approval service before the rule (the PR's + * table): the refused shapes below completed their run with the later branch + * never run; the controls ran every branch they should. Every refusal case + * here parsed green before the rule. + */ +describe('a branch that parks the run, taken before its siblings, is refused', () => { + const ROUTED: E[] = [['a_review', 'ok', { label: 'approve' }], ['b_review', 'ok', { label: 'approve' }]]; + const X1: FlowNode = step('x1'); + const decision = (mode?: 'exclusive' | 'inclusive'): FlowNode => + ({ id: 'x1', type: 'decision', label: 'x1', ...(mode ? { config: { mode } } : {}) }); + + it('two conditioned edges, both true, each to an approval (the measured card shape)', () => { + const flow = flowOf([X1, approval('a_review'), approval('b_review'), end('ok')], [ + ['start', 'x1'], ['x1', 'a_review', { condition: 'true' }], ['x1', 'b_review', { condition: 'true' }], ...ROUTED, + ]); + const refusals = droppedOf(flow); + // Anchored on the edge whose branch parks the run, naming the edge it leaves untaken. + expect(refusals.map(([path]) => path)).toEqual(['edges.1']); + expect(refusals[0][1]).toContain( + 'Node `x1` takes edge `e1` (`x1` → `a_review`) before `e2` (`x1` → `b_review`), and that edge\'s branch ' + + 'reaches `a_review` (`approval`), a node that parks the run.', + ); + expect(refusals[0][1]).toContain('never back at `x1`, so the edges after that branch are never taken'); + // The prescription: the pausing branch last, a chain, or a decision. + expect(refusals[0][1]).toContain('Make the branch that parks the last one the node takes'); + expect(refusals[0][1]).toContain('route them through a `decision`, which takes only the first edge whose condition holds'); + // Not the concurrent rule's: one refusal, this one. + expect(refusalsOf(flow)).toEqual([]); + }); + + it('the first conditioned branch parks, the second runs synchronously: the second is dropped', () => { + expect(droppedOf(flowOf([X1, approval('a_review'), step('s1'), end('ok'), end('ok2')], [ + ['start', 'x1'], ['x1', 'a_review', { condition: 'true' }], ['x1', 's1', { condition: 'true' }], + ['s1', 'ok2'], ['a_review', 'ok', { label: 'approve' }], + ])).map(([path]) => path)).toEqual(['edges.1']); + }); + + it('the pause two hops down the first branch', () => { + expect(droppedOf(flowOf([X1, step('h1'), approval('a_review'), step('s1'), end('ok'), end('ok2')], [ + ['start', 'x1'], ['x1', 'h1', { condition: 'true' }], ['h1', 'a_review'], ['x1', 's1', { condition: 'true' }], + ['s1', 'ok2'], ['a_review', 'ok', { label: 'approve' }], + ])).map(([path]) => path)).toEqual(['edges.1']); + }); + + it.each(FLOW_PAUSE_CAPABLE_NODE_TYPES.filter((t) => t !== 'approval_revise'))('the first branch reaches a `%s`', (type) => { + const first = type === 'wait' ? wait('p1') : type === 'screen' ? screen('p1') : approval('p1'); + expect(droppedOf(flowOf([X1, first, step('s1'), end('ok'), end('ok2')], [ + ['start', 'x1'], ['x1', 'p1', { condition: 'true' }], ['x1', 's1', { condition: 'true' }], + ['s1', 'ok2'], ['p1', 'ok', ...(type === 'approval' ? [{ label: 'approve' }] : [])] as E, + ])).map(([path]) => path)).toEqual(['edges.1']); + }); + + it('an inclusive `decision` takes every true edge the same way, and is told it can drop `mode: \'inclusive\'`', () => { + const refusals = droppedOf(flowOf([decision('inclusive'), approval('a_review'), step('s1'), end('ok'), end('ok2')], [ + ['start', 'x1'], ['x1', 'a_review', { condition: 'true' }], ['x1', 's1', { condition: 'true' }], + ['s1', 'ok2'], ['a_review', 'ok', { label: 'approve' }], + ])); + expect(refusals.map(([path]) => path)).toEqual(['edges.1']); + expect(refusals[0][1]).toContain("delete `mode: 'inclusive'`, so the decision takes only the first edge whose condition holds"); + }); + + it('mutually exclusive conditions are refused too: the parse cannot tell which conditions may hold together', () => { + const refusals = droppedOf(flowOf([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' }], + ...ROUTED, + ])); + expect(refusals.map(([path]) => path)).toEqual(['edges.1']); + expect(refusals[0][1]).toContain('A `condition` on the edges does not exempt them'); + }); + + it('a conditioned branch that parks drops an UNCONDITIONAL sibling, whichever is declared first', () => { + // The unconditional edges run last, after every conditioned edge is done — + // declaration order between the two kinds does not move that. + const shape = (unconditionalFirst: boolean): Flow => flowOf([X1, approval('a_review'), step('s1'), end('ok'), end('ok2')], [ + ['start', 'x1'], + ...((unconditionalFirst + ? [['x1', 's1'], ['x1', 'a_review', { condition: 'true' }]] + : [['x1', 'a_review', { condition: 'true' }], ['x1', 's1']]) as E[]), + ['s1', 'ok2'], ['a_review', 'ok', { label: 'approve' }], + ]); + expect(droppedOf(shape(false)).map(([path]) => path)).toEqual(['edges.1']); + expect(droppedOf(shape(true)).map(([path]) => path)).toEqual(['edges.2']); + expect(droppedOf(shape(true))[0][1]).toContain('before `e1` (`x1` → `s1`)'); + }); + + it('an exclusive `decision` with an unconditional sibling beside its conditioned branch: the sibling is dropped', () => { + const refusals = droppedOf(flowOf([decision(), approval('a_review'), step('s1'), end('ok'), end('ok2')], [ + ['start', 'x1'], ['x1', 'a_review', { condition: 'true' }], ['x1', 's1'], + ['s1', 'ok2'], ['a_review', 'ok', { label: 'approve' }], + ])); + expect(refusals.map(([path]) => path)).toEqual(['edges.1']); + // Already a first-match `decision`: the rewrite named is the `isDefault` otherwise-branch, not another decision. + expect(refusals[0][1]).toContain('where a sibling is the otherwise-branch, mark it `isDefault: true`'); + expect(refusals[0][1]).not.toContain('route them through a `decision`'); + }); + + it('an `isDefault` edge that parks before a LATER `isDefault` edge of a plain node: the later one is dropped', () => { + // Default edges are awaited one after another, like conditioned ones. + const refusals = droppedOf(flowOf([X1, approval('a_review'), step('s1'), end('ok'), end('ok2')], [ + ['start', 'x1'], ['x1', 'a_review', { isDefault: true }], ['x1', 's1', { isDefault: true }], + ['s1', 'ok2'], ['a_review', 'ok', { label: 'approve' }], + ])); + expect(refusals.map(([path]) => path)).toEqual(['edges.1']); + expect(refusals[0][1]).toContain('before `e2` (`x1` → `s1`)'); + }); + + it('an edge carrying both `condition` and `isDefault` is taken with the conditioned ones, before a later conditioned sibling', () => { + // `traverseNext` buckets on `condition` first; read as a default edge, the pair would never meet. + expect(droppedOf(flowOf([X1, approval('a_review'), step('s1'), end('ok'), end('ok2')], [ + ['start', 'x1'], ['x1', 'a_review', { condition: 'true', isDefault: true }], ['x1', 's1', { condition: 'true' }], + ['s1', 'ok2'], ['a_review', 'ok', { label: 'approve' }], + ])).map(([path]) => path)).toEqual(['edges.1']); + }); + + it('an `isDefault` branch that parks drops its unconditional sibling', () => { + const refusals = droppedOf(flowOf([X1, step('s0'), approval('a_review'), step('s1'), end('ok'), end('ok2')], [ + ['start', 'x1'], ['x1', 's0', { condition: 'false' }], ['x1', 'a_review', { isDefault: true }], ['x1', 's1'], + ['s0', 'ok2'], ['s1', 'ok2'], ['a_review', 'ok', { label: 'approve' }], + ])); + expect(refusals.map(([path]) => path)).toEqual(['edges.2']); + expect(refusals[0][1]).toContain('before `e3` (`x1` → `s1`)'); + }); + + it('three conditioned branches: one refusal, anchored on the first that parks, naming every edge after it', () => { + const refusals = droppedOf(flowOf([X1, step('s0'), approval('a_review'), approval('b_review'), end('ok'), end('ok2')], [ + ['start', 'x1'], ['x1', 's0', { condition: 'true' }], ['x1', 'a_review', { condition: 'true' }], + ['x1', 'b_review', { condition: 'true' }], ['s0', 'ok2'], ...ROUTED, + ])); + expect(refusals.map(([path]) => path)).toEqual(['edges.2']); + expect(refusals[0][1]).toContain('before `e3` (`x1` → `b_review`)'); + }); +}); + +/** + * A `decision` that declares `config.conditions` routes by label (patch round + * 1 of #38875). On a run matching none of them it picks `default`: with no + * out-edge labelled `default`, `traverseNext` claims EVERY `isDefault` edge, + * whatever its label, and awaits them in turn; with no claimant at all, it + * takes every out-edge. Measured on the real engine (no condition matching): + * the first claimed `isDefault` branch parked, the run completed after its + * decision, and the second never ran; with the first one synchronous both ran. + */ +describe('a label-routed `decision`: its no-match pick is judged as the engine claims it', () => { + const routed = (conditions = [{ label: 'hi', expression: 'record.amount > 1000' }]): FlowNode => + ({ id: 'x1', type: 'decision', label: 'x1', config: { conditions } }); + const tail: E[] = [['h', 'ok2'], ['s1', 'ok2'], ['a_review', 'ok', { label: 'approve' }]]; + const nodes = (): FlowNode[] => [routed(), approval('a_review'), step('s1'), step('h'), end('ok'), end('ok2')]; + + it.each([ + ['one labelled, one not', { label: 'x' }, {}], + ['two different labels', { label: 'x' }, { label: 'y' }], + ])('two `isDefault` edges (%s), the first parks: the second is dropped', (_, first, second) => { + const refusals = droppedOf(flowOf(nodes(), [ + ['start', 'x1'], ['x1', 'h', { label: 'hi' }], + ['x1', 'a_review', { ...first, isDefault: true }], ['x1', 's1', { ...second, isDefault: true }], ...tail, + ])); + expect(refusals.map(([path]) => path)).toEqual(['edges.2']); + expect(refusals[0][1]).toContain('before `e3` (`x1` → `s1`)'); + }); + + it('CONTROL: the claimed `isDefault` edge that parks taken last, or the only one, parses', () => { + expect(parses(flowOf(nodes(), [ + ['start', 'x1'], ['x1', 'h', { label: 'hi' }], + ['x1', 's1', { isDefault: true }], ['x1', 'a_review', { label: 'x', isDefault: true }], ...tail, + ]))).toBe(true); + expect(parses(flowOf(nodes(), [ + ['start', 'x1'], ['x1', 'h', { label: 'hi' }], ['x1', 's1'], ['s1', 'ok2'], + ['x1', 'a_review', { label: 'x', isDefault: true }], ['h', 'ok2'], ['a_review', 'ok', { label: 'approve' }], + ]))).toBe(true); + }); + + it('no fallback edge at all: a no-match run takes every out-edge, so a guarded branch that parks drops its sibling', () => { + // The label passes alone never meet `a` and `b`; only the whole-set pass does. + const refusals = droppedOf(flowOf([routed([{ label: 'a', expression: 'record.amount > 5' }, { label: 'b', expression: 'record.amount > 1' }]), + approval('a_review'), step('s1'), end('ok'), end('ok2')], [ + ['start', 'x1'], ['x1', 'a_review', { label: 'a', condition: 'true' }], ['x1', 's1', { label: 'b' }], + ['s1', 'ok2'], ['a_review', 'ok', { label: 'approve' }], + ])); + expect(refusals.map(([path]) => path)).toEqual(['edges.1']); + expect(refusals[0][1]).toContain('before `e2` (`x1` → `s1`)'); + }); + + it('one refusal when the same edge is the first to park in two passes (its label pass and the whole set)', () => { + const refusals = droppedOf(flowOf([routed([{ label: 'a', expression: 'record.amount > 5' }]), + approval('a_review'), step('s1'), end('ok'), end('ok2')], [ + ['start', 'x1'], ['x1', 'a_review', { label: 'a', condition: 'true' }], ['x1', 's1', { label: 'a' }], + ['s1', 'ok2'], ['a_review', 'ok', { label: 'approve' }], + ])); + expect(refusals.map(([path]) => path)).toEqual(['edges.1']); + }); + + it('CONTROL: branches under different labels, with a claimed fallback, are never taken together', () => { + // Judged as one pass, the guarded `a` edge would sit before the unconditional `b` edge and be refused. + expect(parses(flowOf([routed([{ label: 'a', expression: 'record.amount > 5' }, { label: 'b', expression: 'record.amount > 1' }]), + approval('a_review'), step('s1'), end('ok'), end('ok2')], [ + ['start', 'x1'], ['x1', 'a_review', { label: 'a', condition: 'true' }], ['x1', 's1', { label: 'b' }], + ['x1', 'ok2', { label: 'default' }], ['s1', 'ok2'], ['a_review', 'ok', { label: 'approve' }], + ]))).toBe(true); + }); +}); + +describe('controls: the branch that parks is the last one taken, or the only one', () => { + const X1: FlowNode = step('x1'); + + it('the LAST conditioned branch parks: every earlier one has run by then', () => { + expect(parses(flowOf([X1, step('s1'), approval('a_review'), end('ok'), end('ok2')], [ + ['start', 'x1'], ['x1', 's1', { condition: 'true' }], ['x1', 'a_review', { condition: 'true' }], + ['s1', 'ok2'], ['a_review', 'ok', { label: 'approve' }], + ]))).toBe(true); + }); + + it('an exclusive `decision` (the default) takes one conditioned edge, so nothing is left behind it', () => { + for (const config of [undefined, { mode: 'exclusive' as const }]) { + expect(parses(flowOf([ + { id: 'x1', type: 'decision', label: 'x1', ...(config ? { config } : {}) }, + approval('a_review'), approval('b_review'), end('ok'), + ], [ + ['start', 'x1'], ['x1', 'a_review', { condition: 'record.amount > 5' }], ['x1', 'b_review', { condition: 'true' }], + ['a_review', 'ok', { label: 'approve' }], ['b_review', 'ok', { label: 'approve' }], + ]))).toBe(true); + } + }); + + it('an `isDefault` edge beside the conditioned ones: it runs only when none held, never with them', () => { + expect(parses(flowOf([X1, step('s1'), approval('a_review'), approval('b_review'), end('ok'), end('ok2')], [ + ['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); + }); + + it('a `fault` edge beside a conditioned branch that parks: the fault edge runs only instead', () => { + expect(parses(flowOf([X1, step('s1'), approval('a_review'), end('ok'), end('ok2')], [ + ['start', 'x1'], ['x1', 'a_review', { condition: 'true' }], ['x1', 's1', { type: 'fault' }], + ['s1', 'ok2'], ['a_review', 'ok', { label: 'approve' }], + ]))).toBe(true); + }); + + it('an approval\'s `approve` / `reject` edges, each guarded and each to its own pause: one label 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', condition: 'true' }], ['m_review', 'b_review', { label: 'reject', condition: 'true' }], + ['a_review', 'ok', { label: 'approve' }], ['b_review', 'ok', { label: 'approve' }], + ]))).toBe(true); + }); + + it('⛔ a `subflow` on the first branch is not judged by type (its child is another record)', () => { + // Measured: a child that pauses drops the later sibling all the same. Met + // only at run time, by the boundary the region rule and the fan-out rule keep. + expect(parses(flowOf([X1, { id: 'sub', type: 'subflow', label: 'Sub', config: { flowName: 'child' } }, step('s1'), end('ok'), end('ok2')], [ + ['start', 'x1'], ['x1', 'sub', { condition: 'true' }], ['x1', 's1', { condition: 'true' }], ['sub', 'ok'], ['s1', 'ok2'], + ]))).toBe(true); + }); + + it('judges the population it is handed, and skips malformed members', () => { + const flow = flowOf([X1, approval('a_review'), approval('b_review')], [ + ['start', 'x1'], ['x1', 'a_review', { condition: 'true' }], ['x1', 'b_review', { condition: 'true' }], + ]); + expect(sequentialPauseRefusals(flow, [])).toEqual([]); + expect(sequentialPauseRefusals(flow, FLOW_PAUSE_CAPABLE_NODE_TYPES)).toHaveLength(1); + expect(sequentialPauseRefusals( + { nodes: [null, { id: 'x1', type: 'assignment' }, { id: 'a', type: 'approval' }, { id: 'b', type: 'approval' }], + edges: [null, { source: 'x1', target: 'a', condition: 'true' }, { source: 'x1' }, { source: 'x1', target: 'b', condition: 'true' }] }, + FLOW_PAUSE_CAPABLE_NODE_TYPES, + ).map((r) => r.path)).toEqual([['edges', 1]]); + }); +}); diff --git a/packages/spec/src/automation/flow-concurrent-pause.ts b/packages/spec/src/automation/flow-concurrent-pause.ts index 5204ea50919..bb1506e7703 100644 --- a/packages/spec/src/automation/flow-concurrent-pause.ts +++ b/packages/spec/src/automation/flow-concurrent-pause.ts @@ -1,9 +1,10 @@ // 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). + * Two durable pauses on concurrent branches of one fan-out (#38838), and a + * branch that parks the run taken before its siblings (#38875) — refused at + * the flow parse, so `objectstack validate`, the metadata save and publish, + * and `registerFlow` all refuse them before any run. * * ## The limit * @@ -58,15 +59,56 @@ * - 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: + * Not this rule's — never two pauses at once, but 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; + * true branch pauses, a later true sibling never runs (measured); * - an `isDefault` edge beside an unconditional one. `traverseNext` takes 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. + * Both are the sequential rule's, below. + * + * ## The sequential twin (#38875) + * + * `traverseNext` takes a node's out-edges in a fixed order within one + * traversal: its conditioned edges one after another, in declaration order — + * every one whose condition holds, except on a `decision` without + * `mode: 'inclusive'`, which takes only the first; then, when no condition + * held, its `isDefault` edges, one after another; then its unconditional + * edges, together. Each is awaited before the next. A pause unwinds that whole + * traversal, and a resumed run continues from the node that parked — never + * back at the node — so every edge the node would have taken after a branch + * that parks is silently never taken. No request is orphaned; a branch is + * lost. Refused: an edge whose branch reaches a pausing node (the same "any + * path" reading as above) when the same traversal would take another edge + * after it — one refusal per traversal, anchored at the first such edge, + * naming the edges it leaves untaken. + * + * Measured (`plugin-approvals`, real engine + approval service; the table is + * in the PR), with every condition `true`: + * - lost, refused: two conditioned edges each to an approval; the first to an + * approval and the second synchronous; the pause two hops down the first + * branch; the same on a `decision` with `mode: 'inclusive'`; a conditioned + * branch that pauses beside an unconditional sibling, whichever is declared + * first, on any node, an exclusive `decision` included; an `isDefault` + * branch that pauses beside an unconditional sibling, or before a later + * `isDefault` edge; on a `decision` that declares `config.conditions`, a + * run matching none of them: with no edge labelled `default`, every + * `isDefault` edge is claimed whatever its label and taken in turn, so the + * first that parks drops the rest (measured in patch round 1), and with no + * claimant at all every out-edge is taken in this order; + * - kept, accepted: the LAST conditioned branch pauses (the earlier ones have + * run); an exclusive `decision` (one edge is taken); an `isDefault` edge + * beside conditioned ones (it runs only when none held); a `fault` edge; + * one `isDefault` edge, or the parking one claimed last. + * Conditions are judged as if they may all hold, as above: two conditioned + * edges whose conditions exclude each other are refused too, and the + * prescription names the `decision` that makes the choice explicit. + * + * The same boundaries hold: a `subflow` / `map` whose child pauses drops the + * later siblings at run time all the same (measured), and is not judged by + * type here; a plugin-registered pausing type is invisible to a parse. * * ## What "concurrent" and "reaches" mean here — mirrored from the engine * @@ -224,18 +266,18 @@ function concurrentGroups(node: NodeView, outEdges: readonly EdgeView[]): Concur 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[] = []; +/** The top-level graph as the rules read it: nodes by id, out-edges by source, and the pause walk. */ +interface PauseGraph { + readonly nodes: readonly NodeView[]; + readonly outEdges: ReadonlyMap; + /** The pausing nodes a branch entered at `target` may reach, each walk stopping at its first. */ + readonly pausesFrom: (target: string) => NodeView[]; +} + +/** `flow`'s top-level graph, or `undefined` when no node of `pauseCapableTypes` is in it (nothing to judge). */ +function pauseGraph(flow: { nodes?: unknown; edges?: unknown }, pauseCapableTypes: readonly string[]): PauseGraph | undefined { const nodes = (Array.isArray(flow.nodes) ? flow.nodes : []).map(nodeView).filter((n) => n !== undefined); - if (!nodes.some((n) => pauseCapableTypes.includes(n.type))) return out; + if (!nodes.some((n) => pauseCapableTypes.includes(n.type))) return undefined; 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) => { @@ -246,7 +288,6 @@ export function concurrentPauseRefusals( 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(); @@ -265,6 +306,22 @@ export function concurrentPauseRefusals( } return found; }; + return { nodes, outEdges, pausesFrom }; +} + +/** + * 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 graph = pauseGraph(flow, pauseCapableTypes); + if (!graph) return out; + const { nodes, outEdges, pausesFrom } = graph; for (const node of nodes) { for (const { edges: group, unclaimedDefault } of concurrentGroups(node, outEdges.get(node.id) ?? [])) { @@ -312,3 +369,119 @@ export function concurrentPauseRefusals( } return out; } + +/** + * The out-edge sets of `node` that one traversal may take, as `traverseNext` + * narrows them: every non-fault out-edge of a node that does not pick a branch + * by label; for one that does, the edges carrying each label, plus — for a + * `decision` that declares `config.conditions`, on a run matching none of them + * (unreachable when one is the literal `true`) — what claims its `default` + * pick: the edges labelled `default` (a label pass already), else EVERY + * `isDefault` out-edge whatever its label (`traverseNext`'s own fallback + * claim), else nothing, and then the whole set. The same reading + * {@link concurrentGroups} takes, over every edge rather than the + * unconditional ones alone. + */ +function traversalPasses(node: NodeView, outEdges: readonly EdgeView[]): EdgeView[][] { + const taken = outEdges.filter((e) => e.type !== 'fault'); + if (!picksBranchByLabel(node)) return [taken]; + const byLabel = new Map(); + for (const edge of taken) { + const pass = byLabel.get(edge.label); + if (pass) pass.push(edge); + else byLabel.set(edge.label, [edge]); + } + const passes = [...byLabel.values()]; + if (decisionDefaultUnclaimed(node, outEdges)) passes.push(taken); + else if ( + node.type === 'decision' + && !hasLiteralTrueCondition(node) + && !taken.some((e) => e.label === FLOW_DECISION_DEFAULT_BRANCH_LABEL) + ) { + // No edge is labelled `default`, so the no-match pick claims every `isDefault` edge, and awaits them in turn. + passes.push(taken.filter((e) => e.isDefault === true)); + } + return passes; +} + +/** True for a `decision` that takes only the first out-edge whose condition holds (no `mode: 'inclusive'`). */ +function takesFirstConditionOnly(node: NodeView): boolean { + return node.type === 'decision' && (node.config as { mode?: unknown } | undefined)?.mode !== 'inclusive'; +} + +/** + * Each edge of one pass that the engine AWAITS before others of the same pass, + * with the edges that run only after it is done: a conditioned edge before the + * later conditioned ones (not on a first-match `decision`, which takes one) + * and before every unconditional edge; an `isDefault` edge before the later + * default edges and every unconditional edge. Conditioned and default edges + * never run in one pass together — a default edge runs only when no condition + * held — and the unconditional edges run last, together. + */ +function awaitedBefore(node: NodeView, pass: readonly EdgeView[]): Array<{ edge: EdgeView; after: EdgeView[] }> { + const conditioned = pass.filter((e) => Boolean(e.condition)); + const defaults = pass.filter((e) => !e.condition && e.isDefault === true); + const unconditional = pass.filter((e) => !e.condition && e.isDefault !== true); + const firstOnly = takesFirstConditionOnly(node); + return [ + ...conditioned.map((edge, i) => ({ edge, after: [...(firstOnly ? [] : conditioned.slice(i + 1)), ...unconditional] })), + ...defaults.map((edge, i) => ({ edge, after: [...defaults.slice(i + 1), ...unconditional] })), + ]; +} + +/** + * Every node of `flow`'s top-level graph that takes an out-edge reaching a + * node whose type is in `pauseCapableTypes` BEFORE other out-edges of the same + * traversal, which then never run (#38875). One refusal per traversal pass, + * anchored at the first such edge, naming the edges it leaves untaken. + */ +export function sequentialPauseRefusals( + flow: { nodes?: unknown; edges?: unknown }, + pauseCapableTypes: readonly string[], +): ConcurrentPauseRefusal[] { + const out: ConcurrentPauseRefusal[] = []; + const graph = pauseGraph(flow, pauseCapableTypes); + if (!graph) return out; + const { nodes, outEdges, pausesFrom } = graph; + + for (const node of nodes) { + const anchored = new Set(); + for (const pass of traversalPasses(node, outEdges.get(node.id) ?? [])) { + for (const { edge, after } of awaitedBefore(node, pass)) { + if (after.length === 0) continue; + const pauses = pausesFrom(edge.target); + if (pauses.length === 0) continue; + // The first pausing edge of the pass leaves every edge after it untaken; one refusal says so. + if (anchored.has(edge.index)) break; + anchored.add(edge.index); + const inclusive = node.type === 'decision' && !takesFirstConditionOnly(node); + out.push({ + path: ['edges', edge.index], + message: + `Node \`${node.id}\` takes edge ${named(edge)} before ${after.map(named).join(', ')}, and that edge's ` + + `branch reaches ${pauses.map((p) => `\`${p.id}\` (\`${p.type}\`)`).join(', ')}, a node that parks the ` + + 'run. The engine takes a node\'s conditioned out-edges one after another in the order they are ' + + 'declared, then its `isDefault` edge when no condition held, then its unconditional edges together; ' + + `when the run parks inside an earlier branch it later resumes from the node it parked at, never back at ` + + `\`${node.id}\`, so the edges after that branch are never taken and nothing reports it. Make the ` + + 'branch that parks the last one the node takes (declare its edge after its conditioned siblings, with ' + + 'no unconditional sibling beside it), or chain the steps onto one branch so the work after the pause ' + + 'runs on resume; ' + + (inclusive + ? "where only one of the branches should run, delete `mode: 'inclusive'`, so the decision takes only " + + 'the first edge whose condition holds. ' + : node.type === 'decision' + ? 'where a sibling is the otherwise-branch, mark it `isDefault: true` instead of leaving it ' + + 'unconditional, and keep one `isDefault` edge per node — this `decision` already takes only the ' + + 'first edge whose condition holds. ' + : 'where only one of the branches should run, route them through a `decision`, which takes only the ' + + 'first edge whose condition holds. ') + + 'A `condition` on the edges does not exempt them, because the flow cannot be checked for which ' + + 'conditions may hold together.', + }); + break; + } + } + } + return out; +} diff --git a/packages/spec/src/automation/flow.zod.ts b/packages/spec/src/automation/flow.zod.ts index 248e5b101eb..10377478745 100644 --- a/packages/spec/src/automation/flow.zod.ts +++ b/packages/spec/src/automation/flow.zod.ts @@ -31,7 +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'; +import { concurrentPauseRefusals, sequentialPauseRefusals } 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'; @@ -1657,6 +1657,16 @@ export const FlowSchema = lazySchema(() => strictObject( ctx.addIssue({ code: 'custom', path: [...refusal.path], message: refusal.message }); } + // Its sequential twin (#38875): a node takes its conditioned out-edges one + // after another, then its default edge, then its unconditional ones, and a + // run that parks inside an earlier branch resumes from where it parked, + // never back at the node — so the edges after a branch that may pause are + // silently never taken. Same population, same "any path" reading; the + // shapes and the boundaries are `flow-concurrent-pause.ts`'s header. + for (const refusal of sequentialPauseRefusals(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` diff --git a/packages/spec/src/migrations/entries/semantic/19.flow-sequential-branch-durable-pause-refused.ts b/packages/spec/src/migrations/entries/semantic/19.flow-sequential-branch-durable-pause-refused.ts new file mode 100644 index 00000000000..8b393e8aa3d --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/19.flow-sequential-branch-durable-pause-refused.ts @@ -0,0 +1,69 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// A branch that parks the run, taken before other out-edges of the same node, +// is refused at the flow parse. A structured TODO, not a D2 conversion: whether +// the author meant every branch to run (then the pausing one goes last, or the +// steps are chained) or only one (then a `decision` chooses) is not recorded, +// and the platform does not guess. +export const entry: SemanticMigration = { + id: 'flow-sequential-branch-durable-pause-refused', + surface: + 'The TOP-LEVEL graph of every flow: a node with an out-edge whose branch reaches, along any path of the ' + + 'flow\'s edges, a node of a type that parks the run on every execution (`approval`, `approval_revise`, ' + + '`screen`, `wait`), when the engine would take another out-edge of the same node AFTER it in the same ' + + 'traversal. The engine takes a node\'s out-edges in a fixed order, each awaited before the next: its ' + + 'conditioned edges in declaration order — every one whose condition holds, except on a `decision` ' + + 'without `mode: \'inclusive\'`, which takes only the first — then, when no condition held, its ' + + '`isDefault` edges, then its unconditional edges together. So the shape is: two conditioned edges, the ' + + 'earlier one reaching a pausing node, out of any node but an exclusive `decision` (an inclusive ' + + '`decision` included); a conditioned edge reaching a pausing node beside an unconditional sibling, on ' + + 'any node, whichever is declared first; an `isDefault` edge reaching a pausing node beside an ' + + 'unconditional sibling, or before a later `isDefault` edge of the same node. On an `approval` / ' + + '`approval_revise` node, and on a `decision` that declares `config.conditions`, only the out-edges ' + + 'sharing ONE `label` are taken together, and they are judged per label; such a `decision`, on a run ' + + 'matching none of its conditions, picks `default`: with no edge labelled `default` it claims EVERY ' + + '`isDefault` edge whatever its label and takes them in turn, and with no claimant at all it takes every ' + + 'out-edge in the order above, so both sets are judged too (unless a condition is the literal `true`). ' + + '⛔ `subflow` and `map` are not in the population: whether they pause is decided by the ' + + 'child flow they name, a different record.', + replacement: + 'Where every branch should run, make the branch that parks the LAST one the node takes — declare its ' + + 'edge after its conditioned siblings, with no unconditional sibling beside it — or chain the steps onto ' + + 'one branch (`x1 → sync_step → a_review`), so the work after the pause runs on resume. Where only one ' + + 'branch should run, route them through a `decision` (exclusive by default: only the first edge whose ' + + 'condition holds is taken), or delete `mode: \'inclusive\'` from the `decision` that carries it; on a ' + + '`decision` that already takes only the first, mark the unconditional otherwise-branch `isDefault: true` ' + + 'and keep one `isDefault` edge per node. Two ' + + 'branches that each park the run cannot both be taken from one node in any order: chain them.', + reason: + 'A run parks at ONE place, and a resumed run continues from the node that parked — it never goes back ' + + 'to the node it was traversing. Measured on the real engine with the real approval service: a node ' + + 'with two conditioned out-edges, both true, to two approval steps registered and ran; the first step ' + + 'opened its request and parked the run, the second never opened, and after the first step\'s decision ' + + 'the run completed with the second branch never run and no error anywhere. The same held with a ' + + 'synchronous second branch, with the pause two hops down the first branch, on an inclusive `decision`, ' + + 'and for an unconditional sibling of a conditioned or `isDefault` branch that parked. No approval ' + + 'request is orphaned; a branch whose condition holds is silently dropped. The sibling of the ' + + '`flow-concurrent-branch-durable-pause-refused` entry (two pauses on concurrent branches), by the same ' + + 'ruling: a durable pause where the run cannot continue as written is refused at authoring; the engine ' + + 'is deliberately not changed to come back for the remaining edges. Judged on ANY path down a branch, ' + + 'and conditions as if they may all hold: the parse cannot tell which conditions can hold together, so ' + + 'two conditioned edges whose conditions exclude each other are refused too. ⛔ NOT losslessly ' + + 'convertible: the rewrite is a graph rewrite whose intended shape no artifact records, so this is a D3 ' + + 'structured TODO naming the node, the pausing branch and the edges it leaves untaken. Not reached by ' + + 'this parse, and met at run time only: a `subflow` / `map` whose child pauses, and a pausing node type ' + + 'contributed by a plugin.', + acceptanceCriteria: + 'No node of the stack\'s flows takes an out-edge whose branch reaches an `approval`, `approval_revise`, ' + + '`screen` or `wait` node before another out-edge of the same traversal. `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 per node traversal, anchored at the edge ' + + 'whose branch parks the run (`Node \\`x1\\` takes edge \\`c1\\` (\\`x1\\` → \\`a_review\\`) before ' + + '\\`c2\\` (\\`x1\\` → \\`b_review\\`), and that edge\'s branch reaches \\`a_review\\` (\\`approval\\`), a node ' + + 'that parks the run. …`). 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: the branch that used to be ' + + 'dropped now runs (before the pause, or after it on resume), or a `decision` now takes exactly one ' + + 'branch.', +};