Skip to content
Merged
20 changes: 20 additions & 0 deletions .changeset/38838-fanout-pause-refusal.md
Original file line number Diff line number Diff line change
@@ -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 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. 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.

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.

<!-- adr-0087: registered flow-concurrent-branch-durable-pause-refused -->
40 changes: 40 additions & 0 deletions content/docs/automation/flows.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1707,6 +1707,46 @@ 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. 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`); 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`);
- **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,
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
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
Expand Down
176 changes: 142 additions & 34 deletions packages/plugins/plugin-approvals/src/flow-route.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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'];

Expand Down Expand Up @@ -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 () => {
Expand All @@ -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 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
* 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 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`.
*/
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>('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 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);
expect(err).toBeInstanceOf(Error);
expect(err).toMatchObject({ code: 'INVALID_METADATA', status: 422 });
expect(refusalText(err)).toContain(LEAD);
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', () => {
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);
});
});
Loading
Loading