From 8d6993f873f6cb019da219b0f856434dfef64173 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 23:44:35 +0000 Subject: [PATCH 01/16] test(plugin-approvals): pin a failed fan-out as abandoned on the door and the reconciler, red first (#38988) Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- .../approval-fanout-late-steps-38988.test.ts | 98 +++++++++++++------ 1 file changed, 68 insertions(+), 30 deletions(-) diff --git a/packages/plugins/plugin-approvals/src/approval-fanout-late-steps-38988.test.ts b/packages/plugins/plugin-approvals/src/approval-fanout-late-steps-38988.test.ts index 4de15832bc7..cf921901225 100644 --- a/packages/plugins/plugin-approvals/src/approval-fanout-late-steps-38988.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-fanout-late-steps-38988.test.ts @@ -14,9 +14,11 @@ * - a run that reached an `end` (`completed` or `refused`) passed every * successful step, a late one included: a `refused` end unwinds the fan-out * as a failure does, and the other branches go on; - * - the routed-failure reading takes a failure another branch logged after the - * run had ended for one the flow went on from. That reading is held for - * the maintainer's ruling (the last describe records it as it stands). + * - the routed-failure reading took a failure another branch logged after the + * run had ended for one the flow went on from. It now leaves such a step + * out, and the maintainer's ruling on a fan-out where one branch fails + * (abandoned, never approved) is read by the fan-out judge + * (`approval-fanout-judge.ts`): the last describe pins both. * * Real kernel, real ObjectQL engine, real automation engine, real approval * node, driver-sql on better-sqlite3 `:memory:`. @@ -98,6 +100,12 @@ const FLOWS = [ flow('fork_fail_both', [step('first', 'approver'), mark('fork'), mark('note'), mark('late'), step('second', 'approver2')], [edge('start', 'first'), edge('first', 'fork', 'approve'), edge('first', 'end', 'reject'), edge('fork', 'note'), edge('fork', 'late'), edge('note', 'end'), edge('late', 'second'), ...decided('second', 'end')]), + // The control: the first step routes by its decision, no fan-out. Approved, + // it goes to `note`, which fails on its way to the end; rejected, it would + // have gone to `late`, between the two steps. The branch not taken is not open. + flow('label_fail', [step('first', 'approver'), mark('note'), mark('late'), step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'note', 'approve'), edge('first', 'late', 'reject'), + edge('note', 'end'), edge('late', 'second'), ...decided('second', 'end')]), ]; /** One composition of the approvals plugin over a real automation engine. */ @@ -247,21 +255,21 @@ describe('[#38988] a refused fan-out run: a step another branch completed after }); /** - * Held out of this change: the routed-failure reading still takes a failure - * another branch logged after the run had ended for one the flow went on - * from. Ignoring it would make the reconciler agree with the door below, - * `approved`, while the late branch was the only one that could have led to - * the next step, which was never asked. Whether a step that can follow from a - * branch still open at the run's end counts as between two steps is the - * maintainer's to rule. These pins record the reading as it stands, and are - * expected to change with that ruling. + * [#38988 item 3, maintainer ruling 7329430078] A fan-out where one branch + * fails is abandoned, never approved: when the run ends, a step that could + * still follow from a branch that had not finished counts as not done + * (`approval-fanout-judge.ts`). The door judges as the run ends, while the + * open branch has logged nothing yet; the reconciler reads the whole stored + * log, the open branch's late failure included. Both say the same. And a + * failure another branch logged after the run ended is not one the flow went + * on from: the reading names the branch that had not finished. */ -describe('[#38988, held] a failure another branch logged after the run ended: the reading as it stands', () => { +describe('[#38988] a fan-out where one branch fails: abandoned, never approved', () => { let h: Harness; beforeEach(async () => { h = await boot(); }); afterEach(async () => { await h?.shutdown(); }); - it('fork_fail_both: the door writes approved, the reconciler recalled, and the next step is never asked', async () => { + it('fork_fail_both: the door and the reconciler both abandon it, naming the branch that had not finished', async () => { const { start, decide, withoutDoor, settle, settled, requestsOn, timeline, field } = helpers(h); h.during.set('note', async () => { await sleep(30); throw new Error('note failed'); }); h.during.set('late', async () => { await sleep(120); throw new Error('late failed'); }); @@ -278,32 +286,62 @@ describe('[#38988, held] a failure another branch logged after the run ended: th // The door, judging as the failure ends the run. await start('fork_fail_both', 'crm_invoice', 'i_both_door'); await settle(decide('i_both_door', 'approve', 'approver')); - await settled('i_both_door', 'late'); + const door = await settled('i_both_door', 'late'); expect(await field('crm_invoice', 'i_both_rec'), 'the reconciler').toBe('recalled'); - expect(await field('crm_invoice', 'i_both_door'), 'the door').toBe('approved'); - for (const id of ['i_both_rec', 'i_both_door']) { + expect(await field('crm_invoice', 'i_both_door'), 'the door').toBe('recalled'); + for (const [id, first] of [['i_both_rec', rec.first], ['i_both_door', door.first]] as const) { expect((await requestsOn(id)).length, `${id}: no later step opened`).toBe(1); + const why = String((await timeline(String(first.id))).at(-1)![2]); + expect(why, `${id}: the branch that had not finished is named`).toMatch(/its branch at node 'late'/); + expect(why, `${id}: a late failure is not one the flow went on from`).not.toMatch(/the flow went on/); } - const why = String((await timeline(String(rec.first.id))).at(-1)![2]); - expect(why, 'the reconciler names the late branch').toMatch(/its node 'late' failed between two steps/); }); - it('a refused run: a failure another branch logged after the refusal is read as one the flow went on from', async () => { + it('a refused run with a branch still open: the door and the reconciler both abandon it', async () => { const { start, decide, withoutDoor, settle, settled, requestsOn, timeline, field } = helpers(h); - await start('fork_refuse_fail', 'crm_invoice', 'i_refuse_fail'); h.during.set('late', async () => { await sleep(120); throw new Error('late failed'); }); - await withoutDoor(() => settle(decide('i_refuse_fail', 'approve', 'approver'))); - const { run, first } = await settled('i_refuse_fail', 'late'); - expect(run.status).toBe('refused'); - const late = run.steps.at(-1); - expect([late.nodeId, late.status]).toEqual(['late', 'failure']); - expect(Date.parse(late.completedAt), 'failed after the run was refused').toBeGreaterThan(Date.parse(run.completedAt)); + await start('fork_refuse_fail', 'crm_invoice', 'i_refuse_rec'); + await withoutDoor(() => settle(decide('i_refuse_rec', 'approve', 'approver'))); + const rec = await settled('i_refuse_rec', 'late'); + expect(rec.run.status).toBe('refused'); + const late = rec.run.steps.at(-1); + expect([late.nodeId, late.status]).toEqual(['late', 'failure']); + expect(Date.parse(late.completedAt), 'failed after the run was refused').toBeGreaterThan(Date.parse(rec.run.completedAt)); expect((await h.svc.reconcileMarkedApprovals()).judged).toEqual({ abandoned: 1 }); - expect(await field('crm_invoice', 'i_refuse_fail')).toBe('recalled'); - expect((await requestsOn('i_refuse_fail')).length, 'no later step opened').toBe(1); - const why = String((await timeline(String(first.id))).at(-1)![2]); - expect(why, 'the late branch is named').toMatch(/its node 'late' failed between two steps/); + + await start('fork_refuse_fail', 'crm_invoice', 'i_refuse_door'); + await settle(decide('i_refuse_door', 'approve', 'approver')); + const door = await settled('i_refuse_door', 'late'); + + expect(await field('crm_invoice', 'i_refuse_rec'), 'the reconciler').toBe('recalled'); + expect(await field('crm_invoice', 'i_refuse_door'), 'the door').toBe('recalled'); + for (const [id, first] of [['i_refuse_rec', rec.first], ['i_refuse_door', door.first]] as const) { + expect((await requestsOn(id)).length, `${id}: no later step opened`).toBe(1); + const why = String((await timeline(String(first.id))).at(-1)![2]); + expect(why, `${id}: the branch that had not finished is named`).toMatch(/its branch at node 'late'/); + expect(why, `${id}: a late failure is not one the flow went on from`).not.toMatch(/the flow went on/); + } + }); + + it('control: a step that routes by its decision is no fan-out: the branch it did not take is not open', async () => { + const { start, decide, withoutDoor, settle, settled, requestsOn, field } = helpers(h); + h.during.set('note', async () => { await sleep(30); throw new Error('note failed'); }); + + await start('label_fail', 'crm_invoice', 'i_label_rec'); + await withoutDoor(() => settle(decide('i_label_rec', 'approve', 'approver'))); + const rec = await settled('i_label_rec', 'note'); + expect(rec.run.status).toBe('failed'); + expect(rec.run.steps.some((s: any) => s.nodeId === 'late'), 'the branch not taken never ran').toBe(false); + expect((await h.svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + + await start('label_fail', 'crm_invoice', 'i_label_door'); + await settle(decide('i_label_door', 'approve', 'approver')); + await settled('i_label_door', 'note'); + + expect(await field('crm_invoice', 'i_label_rec'), 'the reconciler').toBe('approved'); + expect(await field('crm_invoice', 'i_label_door'), 'the door').toBe('approved'); + for (const id of ['i_label_rec', 'i_label_door']) expect((await requestsOn(id)).length).toBe(1); }); }); From 77db9cf4a3294cd9b8c8b8c7e528a3fcec8c57e0 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 23:46:52 +0000 Subject: [PATCH 02/16] fix(plugin-approvals): a fan-out where one branch fails is abandoned, never approved, on the door and the reconciler (#38988) The routed-failure reading leaves out a failure logged after the run's end, as the stop reading does. A new module, approval-fanout-judge.ts, reads whether a run that ended without completing (a refusing end included) left a branch of a fan-out open from which a step can still follow; the run is then read as ended between two steps. approval-service.ts takes the call sites only. Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- .changeset/38988-fanout-judge.md | 14 ++ .../src/approval-fanout-judge-38988.test.ts | 110 +++++++++++++ .../src/approval-fanout-judge.ts | 145 ++++++++++++++++++ .../plugin-approvals/src/approval-service.ts | 23 ++- 4 files changed, 291 insertions(+), 1 deletion(-) create mode 100644 .changeset/38988-fanout-judge.md create mode 100644 packages/plugins/plugin-approvals/src/approval-fanout-judge-38988.test.ts create mode 100644 packages/plugins/plugin-approvals/src/approval-fanout-judge.ts diff --git a/.changeset/38988-fanout-judge.md b/.changeset/38988-fanout-judge.md new file mode 100644 index 00000000000..f7502cdf8af --- /dev/null +++ b/.changeset/38988-fanout-judge.md @@ -0,0 +1,14 @@ +--- +'@objectstack/plugin-approvals': patch +--- + +fix(plugin-approvals): an approval whose flow fans out and one branch fails is abandoned, never approved + +Clause-②: no +Metadata-protocol: none + +When a flow's node fans out to branches that run together and one branch fails, or reaches an `end` that refuses, the run ends while the other branches keep going. The approval plugin could judge such an approval approved: the judgement after the decision ran as the run ended, while a branch that could still lead to the next approval step had logged nothing yet, and it placed the run at the failed branch, which leads to no later step. The record took `approved` with the next approver never asked. The reconciler, reading the stored log later, put the record back to `recalled`, so the two judgements could disagree. + +Both now read it the same way, as the maintainer ruled: when the run ends, an approval step on another branch that has not finished counts as not done, and the approval is abandoned. The record is put back (`recalled`, or the value at submit where the object closes on `recalled`), and the request's timeline names the branch that had not finished. The judge reads the flow's out-edges that run together, and the steps the run logged by its end. A node that routes by its decision (an approval's `approve` and `reject` edges) is not a fan-out, so the branch it did not take is not read as open. + +A failure another branch logged after the run ended is also no longer read as a failure the flow went on from. The outcome was abandoned before as well; the timeline now names the branch that was still open instead. diff --git a/packages/plugins/plugin-approvals/src/approval-fanout-judge-38988.test.ts b/packages/plugins/plugin-approvals/src/approval-fanout-judge-38988.test.ts new file mode 100644 index 00000000000..780e385b07f --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-fanout-judge-38988.test.ts @@ -0,0 +1,110 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38988 item 3, maintainer ruling 7329430078] The fan-out-aware judge, on + * fixtures: which branch a run that ended left open, from which a step can + * still follow. The real-engine pins live in + * `approval-fanout-late-steps-38988.test.ts` (the last describe). + */ + +import { describe, it, expect } from 'vitest'; +import { openBranchAtEnd, runFlowBody, type FanOutEdge, type FanOutStep } from './approval-fanout-judge.js'; + +const e = (source: string, target: string, extra: Partial> = {}): FanOutEdge => ({ source, target, ...extra }); +const ok = (nodeId: string, extra: Record = {}): FanOutStep => ({ nodeId, status: 'success', ...extra }); +const failed = (nodeId: string, extra: Record = {}): FanOutStep => ({ nodeId, status: 'failure', ...extra }); +const LATE = Symbol('late'); +const late = (step: FanOutStep): FanOutStep => ({ ...step, [LATE]: true }) as FanOutStep; +const isLate = (s: FanOutStep) => (s as any)[LATE] === true; +const between = (...nodes: string[]) => (n: string) => nodes.includes(n); + +/** first (a step) then `fork`, which fans out to `note` (to the end) and `late` (to the second step). */ +const FORK = { edges: [e('start', 'first'), e('first', 'fork', { label: 'approve' }), e('first', 'end', { label: 'reject' }), e('fork', 'note'), e('fork', 'late'), e('note', 'end'), e('late', 'second')] }; +const LOG = [ok('start'), ok('first'), ok('fork'), failed('note')]; + +describe('[#38988] openBranchAtEnd: a branch of a fan-out open at the run\'s end', () => { + it('a fan-out taken, one branch logged and another not, a step can follow the other: that branch is open', () => { + expect(openBranchAtEnd({ steps: LOG, late: isLate, body: FORK, standsBetween: between('first', 'fork', 'late') })).toBe('late'); + }); + + it('no step can follow the branch that had not finished: nothing is open', () => { + expect(openBranchAtEnd({ steps: LOG, late: isLate, body: FORK, standsBetween: between('first', 'fork') })).toBeUndefined(); + }); + + it('every branch of the fan-out was logged by the end: nothing is open', () => { + const steps = [...LOG, failed('late')]; + expect(openBranchAtEnd({ steps, late: isLate, body: FORK, standsBetween: between('first', 'fork', 'late') })).toBeUndefined(); + }); + + it('a branch logged only after the run ended was open at it', () => { + const steps = [...LOG, late(failed('late'))]; + expect(openBranchAtEnd({ steps, late: isLate, body: FORK, standsBetween: between('first', 'fork', 'late') })).toBe('late'); + }); + + it('read off the log alone where the body cannot be read: a step logged after the end, where a step can follow it', () => { + const steps = [...LOG, late(failed('late'))]; + expect(openBranchAtEnd({ steps, late: isLate, body: null, standsBetween: between('late') })).toBe('late'); + expect(openBranchAtEnd({ steps: LOG, late: isLate, body: null, standsBetween: between('late') })).toBeUndefined(); + }); + + it('a node that routes by its decision takes one label: the label it did not take is no open branch', () => { + const body = { edges: [e('first', 'note', { label: 'approve' }), e('first', 'late', { label: 'reject' }), e('late', 'second')] }; + const steps = [ok('start'), ok('first'), failed('note')]; + expect(openBranchAtEnd({ steps, late: isLate, body, standsBetween: between('first', 'late') })).toBeUndefined(); + }); + + it('two out-edges of the one label it took run together: the other is open', () => { + const body = { edges: [e('first', 'note', { label: 'approve' }), e('first', 'late', { label: 'approve' }), e('first', 'end', { label: 'reject' })] }; + const steps = [ok('start'), ok('first'), failed('note')]; + expect(openBranchAtEnd({ steps, late: isLate, body, standsBetween: between('first', 'late') })).toBe('late'); + }); + + it('a group of which no target was logged was not taken', () => { + const body = { edges: [e('first', 'a', { label: 'reject' }), e('first', 'b', { label: 'reject' }), e('first', 'note', { label: 'approve' })] }; + const steps = [ok('start'), ok('first'), failed('note')]; + expect(openBranchAtEnd({ steps, late: isLate, body, standsBetween: between('a', 'b') })).toBeUndefined(); + }); + + it('conditional, default and fault edges are not run together', () => { + for (const extra of [{ condition: 'x > 1' }, { isDefault: true }, { type: 'fault' }]) { + const body = { edges: [e('fork', 'note'), e('fork', 'late', extra)] }; + const steps = [ok('fork'), failed('note')]; + expect(openBranchAtEnd({ steps, late: isLate, body, standsBetween: between('late') }), JSON.stringify(extra)).toBeUndefined(); + } + }); + + it('a node that failed fanned out nothing', () => { + const steps = [ok('start'), ok('first'), failed('fork'), ok('note')]; + expect(openBranchAtEnd({ steps, late: isLate, body: FORK, standsBetween: between('late') })).toBeUndefined(); + }); + + it('a region\'s steps are the region\'s: the top level is read', () => { + const steps = [ok('start'), ok('first'), ok('fork', { parentNodeId: 'region' }), failed('note', { parentNodeId: 'region' })]; + expect(openBranchAtEnd({ steps, late: isLate, body: FORK, standsBetween: between('late') })).toBeUndefined(); + const lateInRegion = [...LOG, late(failed('late', { parentNodeId: 'region' }))]; + expect(openBranchAtEnd({ steps: lateInRegion, late: isLate, body: null, standsBetween: between('late') })).toBeUndefined(); + }); + + it('a branch logged before the node fanned out again is not logged after it', () => { + const body = { edges: [e('fork', 'note'), e('fork', 'late'), e('late', 'fork')] }; + const steps = [ok('fork'), ok('late'), ok('fork'), failed('note')]; + expect(openBranchAtEnd({ steps, late: isLate, body, standsBetween: between('late') })).toBe('late'); + }); +}); + +describe('[#38988] runFlowBody: the body filed under the run\'s key', () => { + const body = { edges: [] }; + it('the body under the key first, the body served under the name otherwise, `null` where none', async () => { + expect(await runFlowBody({ getRunFlow: () => body, getFlow: async () => ({ other: true }) }, 'f')).toBe(body); + expect(await runFlowBody({ getRunFlow: () => null, getFlow: async () => body }, 'f')).toBe(body); + expect(await runFlowBody({ getFlow: async () => body }, 'f')).toBe(body); + expect(await runFlowBody({ getRunFlow: () => null, getFlow: async () => null }, 'f')).toBeNull(); + expect(await runFlowBody({ getFlow: async () => body }, undefined)).toBeNull(); + expect(await runFlowBody(undefined, 'f')).toBeNull(); + }); + + it('a reader that throws reads as no body', async () => { + expect(await runFlowBody({ getRunFlow: () => { throw new Error('refused'); } }, 'f')).toBeNull(); + expect(await runFlowBody({ getFlow: async () => { throw new Error('refused'); } }, 'f')).toBeNull(); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/approval-fanout-judge.ts b/packages/plugins/plugin-approvals/src/approval-fanout-judge.ts new file mode 100644 index 00000000000..6de5bf4adfe --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-fanout-judge.ts @@ -0,0 +1,145 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 Execution item 8; #38988 item 3, maintainer ruling 7329430078] + * The fan-out-aware judge: whether a run that ended without reaching its end + * left a branch open from which a step of its approval could still follow. + * + * The engine runs a node's unconditional out-edges together (`Promise.all`), + * and when one branch fails, or reaches an `end` that refuses, the run ends + * while the other branches go on. The ruling: for an approval flow that fans + * out where one branch fails, the result is abandoned, never approved. When + * the run ends, any approval step on another branch that has not finished + * counts as not done, so the approval ended between two steps. + * + * A branch is open at the run's end where the run's log by its end says so: + * + * - **Read off the flow.** A node the run logged at the top level as a + * success, by its end, whose out-edges taken together (no `condition`, + * not `isDefault`, not `fault`, one `label`) number two or more, and of + * which at least one target was logged after it by the run's end: that + * group was taken. Each target of the group the run logged nothing for + * after the node, by its end, is an open branch. A node that routes by + * its decision (an approval's `approve` and `reject`) takes one label's + * edges, so a label the run did not take is no open branch; edges of + * different labels are never read as taken together, which can only miss + * a fan-out the engine ran, never invent one. + * - **Read off the log.** A step the run logged at the top level after its + * end is a branch that was open at it ({@link FanOutInput.late}). This + * half also answers where the flow's body cannot be read. + * + * An open branch counts where its node stands between two steps + * ({@link FanOutInput.standsBetween}, the set the approval was stamped with): + * a step can still follow it. The read is over the top level of the run, as + * the routed-failure reading is: a region's branches are the region's. + * + * The flow body is the one the engine holds under the run's key now. A body + * changed since the run was started may name other edges; the set the + * approval was stamped with is the one the judge counts by either way. + * + * Pure: the caller hands it the run's steps, which of them were logged after + * the run's end, the body and the stamped set. + */ + +/** One step of a run's log, as the judge reads it. */ +export interface FanOutStep { + readonly nodeId?: unknown; + readonly status?: unknown; + readonly parentNodeId?: unknown; +} + +/** One edge of a flow body, as the judge reads it. */ +export interface FanOutEdge { + readonly source?: unknown; + readonly target?: unknown; + readonly type?: unknown; + readonly condition?: unknown; + readonly isDefault?: unknown; + readonly label?: unknown; +} + +/** What {@link openBranchAtEnd} reads. */ +export interface FanOutInput { + /** The run's step log, in the order logged. */ + readonly steps: readonly FanOutStep[]; + /** Whether a step was logged after the run had ended (the plugin's `loggedAfterEnd`). */ + readonly late: (step: FanOutStep) => boolean; + /** The flow body the run ran, where it can be read. */ + readonly body: { readonly edges?: unknown } | null | undefined; + /** Whether a node of the run's flow stands between two steps of the approval. */ + readonly standsBetween: (nodeId: string) => boolean; +} + +/** A label value for grouping: an edge with no label is its own group key. */ +const NO_LABEL = '\u0000'; + +/** Whether `edge` is one the engine runs together with its siblings. */ +function runsTogether(edge: FanOutEdge): boolean { + return edge.type !== 'fault' && !edge.condition && edge.isDefault !== true; +} + +/** + * The node of the first branch open at the run's end from which a step can + * still follow, or `undefined` where there is none. + */ +export function openBranchAtEnd(input: FanOutInput): string | undefined { + const { steps, late, body, standsBetween } = input; + const topLevel = (s: FanOutStep | null | undefined): s is FanOutStep & { nodeId: string } => + !!s && !s.parentNodeId && typeof s.nodeId === 'string' && s.nodeId !== ''; + + // Read off the log: a top-level step logged after the run's end. + for (const s of steps) { + if (topLevel(s) && late(s) && standsBetween(s.nodeId)) return s.nodeId; + } + + // Read off the flow: a group of out-edges taken together, one target of + // which was logged after the node by the run's end and another not. + const edges = Array.isArray(body?.edges) ? (body!.edges as FanOutEdge[]) : []; + if (edges.length === 0) return undefined; + const inRun = steps.map((s) => (topLevel(s) && !late(s) ? s.nodeId : undefined)); + for (let i = 0; i < inRun.length; i++) { + const source = inRun[i]; + if (source === undefined || steps[i].status !== 'success') continue; + const groups = new Map(); + for (const e of edges) { + if (e.source !== source || typeof e.target !== 'string' || !runsTogether(e)) continue; + const key = typeof e.label === 'string' && e.label !== '' ? e.label : NO_LABEL; + groups.set(key, [...(groups.get(key) ?? []), e.target]); + } + const after = new Set(inRun.slice(i + 1).filter((n): n is string => n !== undefined)); + for (const targets of groups.values()) { + if (targets.length < 2 || !targets.some((t) => after.has(t))) continue; + const open = targets.find((t) => !after.has(t) && standsBetween(t)); + if (open !== undefined) return open; + } + } + return undefined; +} + +/** + * The flow body the engine holds under a run's key (`flowName` on its row, a + * slot key where two packages hold the name), or `null` where none can be + * read: the body filed under the key, else the body served under the name. + * Never throws. + */ +export async function runFlowBody( + automation: { + getRunFlow?(run: { flowName: string }): unknown; + getFlow?(name: string): Promise; + } | null | undefined, + flowName: string | undefined, +): Promise<{ edges?: unknown } | null> { + if (!automation || !flowName) return null; + try { + const byKey = typeof automation.getRunFlow === 'function' ? automation.getRunFlow({ flowName }) : null; + const body = byKey ?? (typeof automation.getFlow === 'function' ? await automation.getFlow(flowName) : null); + return body && typeof body === 'object' ? body as { edges?: unknown } : null; + } catch { + return null; + } +} + +/** Why an approval whose run ended with a branch open ended between two steps. */ +export function openBranchWhy(runId: string, status: string, node: string): string { + return `its run '${runId}' ended ${status} while its branch at node '${node}', from which a step can still follow, had not finished, between two steps.`; +} diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 95b8ffe319e..5eb9edfa49c 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -182,6 +182,7 @@ import { consolePageLink, type ConsolePageComposer } from './public-base-url.js' import { APPROVAL_EMAIL_CHANNELS, EMAILED_APPROVAL_TOPICS } from './approval-email-templates.js'; import { enMessages } from './translations/messages.js'; import { closedValuesOf, judgeApprovalOpening, type OpeningFlow } from './approval-opening-check.js'; +import { openBranchAtEnd, openBranchWhy, runFlowBody } from './approval-fanout-judge.js'; import { gapsAreAboutTheField, openingRefusalText } from './approval-opening-refusal.js'; import { approvalMessageKey, @@ -6468,7 +6469,14 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // the set, after which no request of the approval opened. Read for a // paused run as for an ended one: a failure routed to a pause outside // the set ended the approval as surely as one routed to an end. + // [#38988, N5] Of the steps the run logged by its end, as the stop reading + // ({@link loggedAfterEnd}): a failure another branch of a fan-out logged + // after the run had ended is no failure the flow went on from. Such a + // branch was open at the end, which the fan-out judge reads below. A + // paused run has no end, and every step it logged is read. + const ended = instantOf(run.completedAt); const routedFailure = (stop: string | undefined) => steps.find((s) => s?.status === 'failure' + && !loggedAfterEnd(s, ended) && !s.parentNodeId && typeof s.nodeId === 'string' && s.nodeId !== stop @@ -6536,17 +6544,30 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega if (routed) { return { answer: 'read', over: true, endedWhy: routedWhy(routed), endedAt: typeof routed.startedAt === 'string' ? routed.startedAt : undefined, children }; } - if (REACHED_AN_END.has(status)) return { answer: 'read', over: true, children }; // A run that ended before the approval's latest request opened did not // stop it: the approval went on. const answered = instantOf(run.completedAt) < lastOpened; const endedAt = typeof run.completedAt === 'string' ? run.completedAt : undefined; + // [#38988 item 3, maintainer ruling 7329430078] A run that ended without + // completing, a refusing `end` included, while a branch of a fan-out from + // which a step can still follow had not finished: the approval ended + // between two steps (approval-fanout-judge.ts). + const openBranch = async () => (status === 'completed' || answered ? undefined : openBranchAtEnd({ + steps, late: (s) => loggedAfterEnd(s, ended), body: await runFlowBody(automation, flow), + standsBetween: (node) => standsBetweenSteps(stamp, flow, node), + })); + if (REACHED_AN_END.has(status)) { + const open = await openBranch(); + return { answer: 'read', over: true, children, ...(open !== undefined ? { endedWhy: openBranchWhy(runId, status, open), endedAt } : {}) }; + } if (!stop) { return { answer: 'read', over: true, children, ...(answered ? {} : { endedWhy: `its run '${runId}' ended ${status}, at a node the plugin cannot place.`, endedAt }) }; } if (!answered && standsBetweenSteps(stamp, flow, stop)) { return { answer: 'read', over: true, endedWhy: `its run '${runId}' ended ${status} at node '${stop}', between two steps.`, endedAt, children }; } + const open = await openBranch(); + if (open !== undefined) return { answer: 'read', over: true, endedWhy: openBranchWhy(runId, status, open), endedAt, children }; return { answer: 'read', over: true, children }; } From 89be4000159409f8d387bd9bd37fba598cf2f568 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 23:47:43 +0000 Subject: [PATCH 03/16] fix(plugin-approvals): the fan-out judge's step type carries completedAt for the caller's late reading (#38988) Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- packages/plugins/plugin-approvals/src/approval-fanout-judge.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/plugins/plugin-approvals/src/approval-fanout-judge.ts b/packages/plugins/plugin-approvals/src/approval-fanout-judge.ts index 6de5bf4adfe..d512509b1db 100644 --- a/packages/plugins/plugin-approvals/src/approval-fanout-judge.ts +++ b/packages/plugins/plugin-approvals/src/approval-fanout-judge.ts @@ -46,6 +46,8 @@ export interface FanOutStep { readonly nodeId?: unknown; readonly status?: unknown; readonly parentNodeId?: unknown; + /** When the step was logged, read by the caller's {@link FanOutInput.late}. */ + readonly completedAt?: unknown; } /** One edge of a flow body, as the judge reads it. */ From b0311d824437caab773ca783690e7dccd734d6c6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 01:04:42 +0000 Subject: [PATCH 04/16] test(plugin-approvals): pin the two-deep open branch, the shared-target label and a rejection to a refusing end, red first (#38988) Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- .../approval-fanout-late-steps-38988.test.ts | 89 +++++++++++++++++++ 1 file changed, 89 insertions(+) diff --git a/packages/plugins/plugin-approvals/src/approval-fanout-late-steps-38988.test.ts b/packages/plugins/plugin-approvals/src/approval-fanout-late-steps-38988.test.ts index cf921901225..28090e4f057 100644 --- a/packages/plugins/plugin-approvals/src/approval-fanout-late-steps-38988.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-fanout-late-steps-38988.test.ts @@ -106,6 +106,26 @@ const FLOWS = [ flow('label_fail', [step('first', 'approver'), mark('note'), mark('late'), step('second', 'approver2')], [edge('start', 'first'), edge('first', 'note', 'approve'), edge('first', 'late', 'reject'), edge('note', 'end'), edge('late', 'second'), ...decided('second', 'end')]), + // Two deep: after the first step `fork` fans out to `note1` then `note2` + // (fails) to the end, and to `late1` then `late2` to the second step. `late1` + // has completed when `note2` ends the run; `late2` is still running. + flow('fork_two_deep', [step('first', 'approver'), mark('fork'), mark('note1'), mark('note2'), mark('late1'), mark('late2'), step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'fork', 'approve'), edge('first', 'end', 'reject'), + edge('fork', 'note1'), edge('fork', 'late1'), edge('note1', 'note2'), edge('note2', 'end'), + edge('late1', 'late2'), edge('late2', 'second'), ...decided('second', 'end')]), + // A control: two labels share a target. Approved, `first` goes to `second` + // and `notify` together; rejected, to `notify` alone, which fails. The + // approve group never ran. + flow('shared_notify', [step('first', 'approver'), mark('notify'), step('second', 'approver2'), step('third', 'approver2')], + [edge('start', 'first'), edge('first', 'second', 'approve'), edge('first', 'notify', 'approve'), edge('first', 'notify', 'reject'), + edge('notify', 'end'), ...decided('second', 'third'), edge('third', 'end', 'approve'), edge('third', 'end', 'reject')]), + // A control: the first step's reject edge reaches `fork`, which fans out + // to a refusing end and to `late` (on its way to a second step). The run is + // refused while the branch through `late` was never seen through: an + // approver's rejection, not an approval with an approver missing. + flow('reject_fork_refuse', [step('first', 'approver'), mark('fork'), mark('late'), step('second', 'approver2'), REFUSE], + [edge('start', 'first'), edge('first', 'end', 'approve'), edge('first', 'fork', 'reject'), + edge('fork', 'refuse'), edge('fork', 'late'), edge('late', 'second'), ...decided('second', 'end')]), ]; /** One composition of the approvals plugin over a real automation engine. */ @@ -325,6 +345,75 @@ describe('[#38988] a fan-out where one branch fails: abandoned, never approved', } }); + it('two deep: a branch that logged its first node and is still running is open, at the door and at the reconciler', async () => { + const { start, decide, withoutDoor, settle, settled, requestsOn, timeline, field } = helpers(h); + h.during.set('note2', async () => { await sleep(40); throw new Error('note2 failed'); }); + h.during.set('late2', async () => { await sleep(150); throw new Error('late2 failed'); }); + + await start('fork_two_deep', 'crm_invoice', 'i_deep_rec'); + await withoutDoor(() => settle(decide('i_deep_rec', 'approve', 'approver'))); + const rec = await settled('i_deep_rec', 'late2'); + expect(rec.run.status).toBe('failed'); + const at = (node: string) => Date.parse(rec.run.steps.find((s: any) => s.nodeId === node).completedAt); + const ended = Date.parse(rec.run.completedAt); + expect(at('late1'), 'the branch logged its first node by the end').toBeLessThanOrEqual(ended); + expect(at('late2'), 'and its second after it').toBeGreaterThan(ended); + expect((await h.svc.reconcileMarkedApprovals()).judged).toEqual({ abandoned: 1 }); + + await start('fork_two_deep', 'crm_invoice', 'i_deep_door'); + await settle(decide('i_deep_door', 'approve', 'approver')); + const door = await settled('i_deep_door', 'late2'); + + expect(await field('crm_invoice', 'i_deep_rec'), 'the reconciler').toBe('recalled'); + expect(await field('crm_invoice', 'i_deep_door'), 'the door').toBe('recalled'); + for (const [id, first] of [['i_deep_rec', rec.first], ['i_deep_door', door.first]] as const) { + expect((await requestsOn(id)).length, `${id}: no later step opened`).toBe(1); + expect(String((await timeline(String(first.id))).at(-1)![2]), `${id}: the branch's frontier is named`).toMatch(/its branch at node 'late2'/); + } + }); + + it('control: two labels share a target, and the label not taken is no open branch: a rejection stays rejected', async () => { + const { start, decide, withoutDoor, settle, settled, requestsOn, timeline, field } = helpers(h); + h.during.set('notify', async () => { await sleep(20); throw new Error('notify failed'); }); + + await start('shared_notify', 'crm_invoice', 'i_shared_rec'); + await withoutDoor(() => settle(decide('i_shared_rec', 'reject', 'approver'))); + const rec = await settled('i_shared_rec', 'notify'); + expect(rec.run.status).toBe('failed'); + expect((await h.svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + + await start('shared_notify', 'crm_invoice', 'i_shared_door'); + await settle(decide('i_shared_door', 'reject', 'approver')); + const door = await settled('i_shared_door', 'notify'); + + for (const [id, first] of [['i_shared_rec', rec.first], ['i_shared_door', door.first]] as const) { + expect(await field('crm_invoice', id), id).toBe('rejected'); + expect((await requestsOn(id)).length).toBe(1); + const lines = (await timeline(String(first.id))).map((a) => String(a[2] ?? '')); + expect(lines.some((l) => /did not go on/.test(l)), `${id}: no put-back line`).toBe(false); + } + }); + + it('control: a rejection routed to a refusing end stays rejected, while another taken branch is still open', async () => { + const { start, decide, withoutDoor, settle, settled, requestsOn, timeline, field } = helpers(h); + h.during.set('late', async () => { await sleep(60); throw new Error('late failed'); }); + + for (const [id, door] of [['i_rr_rec', false], ['i_rr_door', true]] as const) { + await start('reject_fork_refuse', 'crm_invoice', id); + const reject = () => settle(decide(id, 'reject', 'approver')); + if (door) await reject(); else await withoutDoor(reject); + const { run, first } = await settled(id, 'late'); + expect(run.status, `${id}: the run was refused`).toBe('refused'); + const late = run.steps.find((s: any) => s.nodeId === 'late'); + expect(Date.parse(late.completedAt), `${id}: the branch through 'late' ended after the run`).toBeGreaterThan(Date.parse(run.completedAt)); + if (!door) expect((await h.svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', id), id).toBe('rejected'); + expect((await requestsOn(id)).length).toBe(1); + const lines = (await timeline(String(first.id))).map((a) => String(a[2] ?? '')); + expect(lines.some((l) => /did not go on/.test(l)), `${id}: no put-back line`).toBe(false); + } + }); + it('control: a step that routes by its decision is no fan-out: the branch it did not take is not open', async () => { const { start, decide, withoutDoor, settle, settled, requestsOn, field } = helpers(h); h.during.set('note', async () => { await sleep(30); throw new Error('note failed'); }); From 77870609cc9449f3b9cc47149ca91cdd71ee6826 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 01:06:05 +0000 Subject: [PATCH 05/16] fix(plugin-approvals): the fan-out judge reads each branch to its frontier and ties a taken group to its own target (#38988) M1: a branch is open where the first node on it the run had not logged by its end stands between two steps, not only at the fan-out's direct target. S1: a labelled group is read as taken only on a logged target no other group of the node names. S2: a skipped step is no node that ran. N1: the run's end instant is read once. N2: the docblock says an edge with no label forms a group of its own. Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- .../src/approval-fanout-judge-38988.test.ts | 34 ++++++- .../src/approval-fanout-judge.ts | 88 +++++++++++++------ .../plugin-approvals/src/approval-service.ts | 2 +- 3 files changed, 97 insertions(+), 27 deletions(-) diff --git a/packages/plugins/plugin-approvals/src/approval-fanout-judge-38988.test.ts b/packages/plugins/plugin-approvals/src/approval-fanout-judge-38988.test.ts index 780e385b07f..1dfc0c37e54 100644 --- a/packages/plugins/plugin-approvals/src/approval-fanout-judge-38988.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-fanout-judge-38988.test.ts @@ -31,11 +31,24 @@ describe('[#38988] openBranchAtEnd: a branch of a fan-out open at the run\'s end expect(openBranchAtEnd({ steps: LOG, late: isLate, body: FORK, standsBetween: between('first', 'fork') })).toBeUndefined(); }); - it('every branch of the fan-out was logged by the end: nothing is open', () => { + it('two deep: a branch that logged its first node and had not logged its next is open at the next', () => { + const body = { edges: [...FORK.edges.filter((x) => x.source !== 'late'), e('late', 'late2'), e('late2', 'second')] }; + const steps = [...LOG, ok('late')]; + expect(openBranchAtEnd({ steps, late: isLate, body, standsBetween: between('first', 'fork', 'late', 'late2') })).toBe('late2'); + expect(openBranchAtEnd({ steps: [...steps, ok('late2')], late: isLate, body, standsBetween: between('first', 'fork', 'late', 'late2', 'second') }), + 'and on at the step itself once the branch logged that node').toBe('second'); + }); + + it('every branch of the fan-out ended by the end: nothing is open', () => { const steps = [...LOG, failed('late')]; expect(openBranchAtEnd({ steps, late: isLate, body: FORK, standsBetween: between('first', 'fork', 'late') })).toBeUndefined(); }); + it('a skipped step is no node that ran: its branch is still open', () => { + const steps = [...LOG.slice(0, 3), { nodeId: 'late', status: 'skipped' }, failed('note')]; + expect(openBranchAtEnd({ steps, late: isLate, body: FORK, standsBetween: between('first', 'fork', 'late') })).toBe('late'); + }); + it('a branch logged only after the run ended was open at it', () => { const steps = [...LOG, late(failed('late'))]; expect(openBranchAtEnd({ steps, late: isLate, body: FORK, standsBetween: between('first', 'fork', 'late') })).toBe('late'); @@ -59,6 +72,25 @@ describe('[#38988] openBranchAtEnd: a branch of a fan-out open at the run\'s end expect(openBranchAtEnd({ steps, late: isLate, body, standsBetween: between('first', 'late') })).toBe('late'); }); + it('two labels share the only logged target: neither is read as taken', () => { + // Rejected, `first` went to `notify` alone; `approve` also names `notify`. + const body = { edges: [e('first', 'second', { label: 'approve' }), e('first', 'notify', { label: 'approve' }), e('first', 'notify', { label: 'reject' }), e('notify', 'end')] }; + const steps = [ok('start'), ok('first'), failed('notify')]; + expect(openBranchAtEnd({ steps, late: isLate, body, standsBetween: between('first', 'second') })).toBeUndefined(); + // The same with the reject edge to a refusing end beside it: a refused run reads the same. + const refused = { edges: [...body.edges, e('first', 'refuse', { label: 'reject' })] }; + expect(openBranchAtEnd({ steps: [ok('start'), ok('first'), ok('notify')], late: isLate, body: refused, standsBetween: between('first', 'second') })).toBeUndefined(); + }); + + it('an unlabelled group on a node that claimed a label: a target it shares with the label is no evidence', () => { + const body = { edges: [e('first', 'second'), e('first', 'notify'), e('first', 'notify', { label: 'reject' })] }; + const steps = [ok('start'), ok('first'), failed('notify')]; + expect(openBranchAtEnd({ steps, late: isLate, body, standsBetween: between('first', 'second') })).toBeUndefined(); + // A target the unlabelled group alone names, logged: that group ran. + const ran = { edges: [e('first', 'second'), e('first', 'log'), e('first', 'notify', { label: 'reject' })] }; + expect(openBranchAtEnd({ steps: [ok('start'), ok('first'), failed('log')], late: isLate, body: ran, standsBetween: between('first', 'second') })).toBe('second'); + }); + it('a group of which no target was logged was not taken', () => { const body = { edges: [e('first', 'a', { label: 'reject' }), e('first', 'b', { label: 'reject' }), e('first', 'note', { label: 'approve' })] }; const steps = [ok('start'), ok('first'), failed('note')]; diff --git a/packages/plugins/plugin-approvals/src/approval-fanout-judge.ts b/packages/plugins/plugin-approvals/src/approval-fanout-judge.ts index d512509b1db..7394b387640 100644 --- a/packages/plugins/plugin-approvals/src/approval-fanout-judge.ts +++ b/packages/plugins/plugin-approvals/src/approval-fanout-judge.ts @@ -12,23 +12,34 @@ * the run ends, any approval step on another branch that has not finished * counts as not done, so the approval ended between two steps. * - * A branch is open at the run's end where the run's log by its end says so: + * A branch is open at the run's end where the run's log by its end says so. + * "Logged" below means a top-level step the run logged by its end with a + * status other than `skipped`: a `skipped` step records a gate that did not + * open in front of a node, never the node running. * - * - **Read off the flow.** A node the run logged at the top level as a - * success, by its end, whose out-edges taken together (no `condition`, - * not `isDefault`, not `fault`, one `label`) number two or more, and of - * which at least one target was logged after it by the run's end: that - * group was taken. Each target of the group the run logged nothing for - * after the node, by its end, is an open branch. A node that routes by - * its decision (an approval's `approve` and `reject`) takes one label's - * edges, so a label the run did not take is no open branch; edges of - * different labels are never read as taken together, which can only miss - * a fan-out the engine ran, never invent one. + * - **Read off the flow.** The out-edges of a node that run together are + * those with no `condition`, not `isDefault` and not `fault`, grouped by + * their `label`; the edges with no label form one group of their own. A + * group is taken after a visit of the node logged as a success where: + * the node has no other group and this one is unlabelled (the engine runs + * those edges whatever the node answered), or one of the group's targets + * was logged after the visit and no other group of the node names that + * target. A node that routes by its decision (an approval's `approve` and + * `reject`) runs one label's edges, so a group is read as taken only on a + * target that group alone could have reached; where two groups share the + * only logged target, neither is read as taken. That can miss a fan-out + * the engine ran (toward the reading before this judge), never invent one. + * A taken group of two or more targets is a fan-out, and each of its + * branches is read to its frontier: from the visit, a target logged after + * it as a success is followed on through its own taken groups; the first + * node on the branch the run had not logged by its end is the frontier, + * and the branch is open there. A branch that logged a failure ended + * there. * - **Read off the log.** A step the run logged at the top level after its * end is a branch that was open at it ({@link FanOutInput.late}). This * half also answers where the flow's body cannot be read. * - * An open branch counts where its node stands between two steps + * An open branch counts where its frontier node stands between two steps * ({@link FanOutInput.standsBetween}, the set the approval was stamped with): * a step can still follow it. The read is over the top level of the run, as * the routed-failure reading is: a region's branches are the region's. @@ -72,7 +83,7 @@ export interface FanOutInput { readonly standsBetween: (nodeId: string) => boolean; } -/** A label value for grouping: an edge with no label is its own group key. */ +/** The group key of an edge with no label: such edges form one group of their own. */ const NO_LABEL = '\u0000'; /** Whether `edge` is one the engine runs together with its siblings. */ @@ -94,25 +105,52 @@ export function openBranchAtEnd(input: FanOutInput): string | undefined { if (topLevel(s) && late(s) && standsBetween(s.nodeId)) return s.nodeId; } - // Read off the flow: a group of out-edges taken together, one target of - // which was logged after the node by the run's end and another not. const edges = Array.isArray(body?.edges) ? (body!.edges as FanOutEdge[]) : []; if (edges.length === 0) return undefined; - const inRun = steps.map((s) => (topLevel(s) && !late(s) ? s.nodeId : undefined)); - for (let i = 0; i < inRun.length; i++) { - const source = inRun[i]; - if (source === undefined || steps[i].status !== 'success') continue; + /** The node each step logged by the run's end ran, or `undefined` (late, nested, skipped). */ + const logged = steps.map((s) => (topLevel(s) && !late(s) && s.status !== 'skipped' ? s.nodeId : undefined)); + const loggedAfter = (node: string, visit: number): number => { + for (let k = visit + 1; k < logged.length; k++) if (logged[k] === node) return k; + return -1; + }; + /** The groups of `node`'s out-edges taken after its visit at `visit` (see the module docblock). */ + const takenGroups = (node: string, visit: number): string[][] => { const groups = new Map(); for (const e of edges) { - if (e.source !== source || typeof e.target !== 'string' || !runsTogether(e)) continue; + if (e.source !== node || typeof e.target !== 'string' || !runsTogether(e)) continue; const key = typeof e.label === 'string' && e.label !== '' ? e.label : NO_LABEL; groups.set(key, [...(groups.get(key) ?? []), e.target]); } - const after = new Set(inRun.slice(i + 1).filter((n): n is string => n !== undefined)); - for (const targets of groups.values()) { - if (targets.length < 2 || !targets.some((t) => after.has(t))) continue; - const open = targets.find((t) => !after.has(t) && standsBetween(t)); - if (open !== undefined) return open; + if (groups.size === 1 && groups.has(NO_LABEL)) return [groups.get(NO_LABEL)!]; + const owners = new Map(); + for (const targets of groups.values()) for (const t of new Set(targets)) owners.set(t, (owners.get(t) ?? 0) + 1); + return [...groups.values()].filter((targets) => targets.some((t) => owners.get(t) === 1 && loggedAfter(t, visit) >= 0)); + }; + /** The frontier of the branch that starts at `target` after the visit at `visit`, where it is open. */ + const seen = new Set(); + const frontierOf = (target: string, visit: number): string | undefined => { + const k = loggedAfter(target, visit); + if (k < 0) return standsBetween(target) ? target : undefined; + if (steps[k].status !== 'success' || seen.has(k)) return undefined; + seen.add(k); + for (const group of takenGroups(target, k)) { + for (const next of group) { + const open = frontierOf(next, k); + if (open !== undefined) return open; + } + } + return undefined; + }; + + for (let i = 0; i < logged.length; i++) { + const source = logged[i]; + if (source === undefined || steps[i].status !== 'success') continue; + for (const group of takenGroups(source, i)) { + if (group.length < 2) continue; + for (const target of group) { + const open = frontierOf(target, i); + if (open !== undefined) return open; + } } } return undefined; diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 5eb9edfa49c..f7e074a007d 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -6546,7 +6546,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega } // A run that ended before the approval's latest request opened did not // stop it: the approval went on. - const answered = instantOf(run.completedAt) < lastOpened; + const answered = ended < lastOpened; const endedAt = typeof run.completedAt === 'string' ? run.completedAt : undefined; // [#38988 item 3, maintainer ruling 7329430078] A run that ended without // completing, a refusing `end` included, while a branch of a fan-out from From 0be5313d396d93fd51a2d606a3f4923e3d5cb2ed Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 01:06:35 +0000 Subject: [PATCH 06/16] fix(plugin-approvals): a refusal after the latest request was rejected stays rejected, with a branch still open (#38988) The seat's confirmed reading of ruling 7329430078: the ruling is about a record marked approved with an approver missing, and a rejection is an approver's decision. The fan-out judge's refused arm does not read a run whose approval's latest request is rejected. Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- packages/plugins/plugin-approvals/src/approval-service.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index f7e074a007d..3fb07ad7f3c 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -6557,7 +6557,10 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega standsBetween: (node) => standsBetweenSteps(stamp, flow, node), })); if (REACHED_AN_END.has(status)) { - const open = await openBranch(); + // [Seat's confirmed reading of ruling 7329430078] A refusal after the + // latest request was rejected is an approver's decision, not an + // approval with an approver missing: rejected stays rejected. + const open = latest?.status === 'rejected' ? undefined : await openBranch(); return { answer: 'read', over: true, children, ...(open !== undefined ? { endedWhy: openBranchWhy(runId, status, open), endedAt } : {}) }; } if (!stop) { From b326d32c9fbb0282fdc73dbb3c2ae91b659f63f9 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 01:06:52 +0000 Subject: [PATCH 07/16] docs(changeset): the fan-out judge's changeset says what the frontier, label and rejection readings do (#38988) Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- .changeset/38988-fanout-judge.md | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/.changeset/38988-fanout-judge.md b/.changeset/38988-fanout-judge.md index f7502cdf8af..90f0711a08d 100644 --- a/.changeset/38988-fanout-judge.md +++ b/.changeset/38988-fanout-judge.md @@ -7,8 +7,16 @@ fix(plugin-approvals): an approval whose flow fans out and one branch fails is a Clause-②: no Metadata-protocol: none -When a flow's node fans out to branches that run together and one branch fails, or reaches an `end` that refuses, the run ends while the other branches keep going. The approval plugin could judge such an approval approved: the judgement after the decision ran as the run ended, while a branch that could still lead to the next approval step had logged nothing yet, and it placed the run at the failed branch, which leads to no later step. The record took `approved` with the next approver never asked. The reconciler, reading the stored log later, put the record back to `recalled`, so the two judgements could disagree. +When a flow's node fans out to branches that run together and one branch fails, or reaches an `end` that refuses, the run ends while the other branches keep going. The approval plugin could judge such an approval approved. The judgement after the decision ran as the run ended, while a branch that could still lead to the next approval step had not finished. It placed the run at the failed branch, which leads to no later step, so the record took `approved` and the next approver was never asked. The reconciler, reading the stored log later, could put the record back to `recalled`, so the two judgements could disagree. -Both now read it the same way, as the maintainer ruled: when the run ends, an approval step on another branch that has not finished counts as not done, and the approval is abandoned. The record is put back (`recalled`, or the value at submit where the object closes on `recalled`), and the request's timeline names the branch that had not finished. The judge reads the flow's out-edges that run together, and the steps the run logged by its end. A node that routes by its decision (an approval's `approve` and `reject` edges) is not a fan-out, so the branch it did not take is not read as open. +The maintainer ruled that when the run ends, an approval step on another branch that has not finished counts as not done, and the approval is abandoned. The judgement after the decision and the reconciler now read every case pinned here the same way. The record is put back (`recalled`, or the value at submit where the object closes on `recalled`), and the request's timeline names the node where the unfinished branch stood. + +How a branch is read as unfinished: + +- The judge reads the flow's out-edges that run together, and the steps the run logged by its end. It follows each branch of a fan-out past the nodes it had already logged, to the first node it had not reached. A branch counts where a step can still follow that node. +- A node that routes by its decision (an approval's `approve` and `reject` edges) runs one label's edges. A group of edges counts as taken only where the run logged a target that no other label of the node names. So the branch a decision did not take is not read as open, even where two labels share a target. +- A step logged as `skipped` (a gate that did not open) does not count as the node having run. + +A run refused after the approval's latest request was rejected keeps `rejected`, even with another branch still open. The ruling concerns a record marked approved with an approver missing, and a rejection is an approver's decision. A failure another branch logged after the run ended is also no longer read as a failure the flow went on from. The outcome was abandoned before as well; the timeline now names the branch that was still open instead. From beec3648f15bfd7b5110e635da80c8faf3ffc6a6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 01:58:19 +0000 Subject: [PATCH 08/16] test(plugin-approvals): pin a decision on the open branch and an approval step's label by its decision, red first (#38988) Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- .../approval-fanout-late-steps-38988.test.ts | 92 +++++++++++++++++++ 1 file changed, 92 insertions(+) diff --git a/packages/plugins/plugin-approvals/src/approval-fanout-late-steps-38988.test.ts b/packages/plugins/plugin-approvals/src/approval-fanout-late-steps-38988.test.ts index 28090e4f057..5ee868ce965 100644 --- a/packages/plugins/plugin-approvals/src/approval-fanout-late-steps-38988.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-fanout-late-steps-38988.test.ts @@ -119,6 +119,27 @@ const FLOWS = [ flow('shared_notify', [step('first', 'approver'), mark('notify'), step('second', 'approver2'), step('third', 'approver2')], [edge('start', 'first'), edge('first', 'second', 'approve'), edge('first', 'notify', 'approve'), edge('first', 'notify', 'reject'), edge('notify', 'end'), ...decided('second', 'third'), edge('third', 'end', 'approve'), edge('third', 'end', 'reject')]), + // A decision on the open branch: after the first step `fork` fans out to + // `note` (fails, on its way to the end) and to `late1`, then the decision + // `dec`, whose condition holds for `late2` (still running) on the way to + // the second step; its fallback edge goes to the end. + flow('fork_decision', [step('first', 'approver'), mark('fork'), mark('note'), mark('late1'), { id: 'dec', type: 'decision', label: 'dec' }, mark('late2'), step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'fork', 'approve'), edge('first', 'end', 'reject'), + edge('fork', 'note'), edge('fork', 'late1'), edge('note', 'end'), edge('late1', 'dec'), + { id: 'dec_late2', source: 'dec', target: 'late2', condition: 'true' }, { id: 'dec_end', source: 'dec', target: 'end', isDefault: true }, + edge('late2', 'second'), ...decided('second', 'end')]), + // Approved, `first` runs `prep` (on its way to the second step) and `notify` + // together; rejected, `notify` alone. The only target logged by the end is + // the shared one. + flow('approved_shared', [step('first', 'approver'), mark('prep'), mark('notify'), step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'prep', 'approve'), edge('first', 'notify', 'approve'), edge('first', 'notify', 'reject'), + edge('prep', 'second'), edge('notify', 'end'), ...decided('second', 'end')]), + // A control: approved, `first` runs the second step and `audit` together; + // rejected, `notify` then `audit`. Rejected, `audit` fails: the approve group + // never ran, though `audit` is logged. + flow('reject_audit', [step('first', 'approver'), mark('notify'), mark('audit'), step('second', 'approver2'), step('third', 'approver2')], + [edge('start', 'first'), edge('first', 'second', 'approve'), edge('first', 'audit', 'approve'), edge('first', 'notify', 'reject'), + edge('notify', 'audit'), edge('audit', 'end'), ...decided('second', 'third'), edge('third', 'end', 'approve'), edge('third', 'end', 'reject')]), // A control: the first step's reject edge reaches `fork`, which fans out // to a refusing end and to `late` (on its way to a second step). The run is // refused while the branch through `late` was never seen through: an @@ -372,6 +393,77 @@ describe('[#38988] a fan-out where one branch fails: abandoned, never approved', } }); + it('a decision on the open branch: a conditional target still running is open, at the door and at the reconciler', async () => { + const { start, decide, withoutDoor, settle, settled, requestsOn, timeline, field } = helpers(h); + h.during.set('note', async () => { await sleep(40); throw new Error('note failed'); }); + h.during.set('late2', async () => { await sleep(150); throw new Error('late2 failed'); }); + + await start('fork_decision', 'crm_invoice', 'i_dec_rec'); + await withoutDoor(() => settle(decide('i_dec_rec', 'approve', 'approver'))); + const rec = await settled('i_dec_rec', 'late2'); + expect(rec.run.status).toBe('failed'); + const ended = Date.parse(rec.run.completedAt); + const at = (node: string) => Date.parse(rec.run.steps.find((s: any) => s.nodeId === node).completedAt); + expect(at('dec'), 'the decision was logged by the end').toBeLessThanOrEqual(ended); + expect(at('late2'), 'its taken target after it').toBeGreaterThan(ended); + expect((await h.svc.reconcileMarkedApprovals()).judged).toEqual({ abandoned: 1 }); + + await start('fork_decision', 'crm_invoice', 'i_dec_door'); + await settle(decide('i_dec_door', 'approve', 'approver')); + const door = await settled('i_dec_door', 'late2'); + + expect(await field('crm_invoice', 'i_dec_rec'), 'the reconciler').toBe('recalled'); + expect(await field('crm_invoice', 'i_dec_door'), 'the door').toBe('recalled'); + for (const [id, first] of [['i_dec_rec', rec.first], ['i_dec_door', door.first]] as const) { + expect((await requestsOn(id)).length, `${id}: no later step opened`).toBe(1); + expect(String((await timeline(String(first.id))).at(-1)![2]), `${id}: the branch's frontier is named`).toMatch(/its branch at node 'late2'/); + } + }); + + it('an approval step\'s label is its request\'s decision: approved, a shared target logged and the other branch running is open', async () => { + const { start, decide, withoutDoor, settle, settled, requestsOn, timeline, field } = helpers(h); + h.during.set('notify', async () => { await sleep(30); throw new Error('notify failed'); }); + h.during.set('prep', async () => { await sleep(150); throw new Error('prep failed'); }); + + await start('approved_shared', 'crm_invoice', 'i_appr_rec'); + await withoutDoor(() => settle(decide('i_appr_rec', 'approve', 'approver'))); + const rec = await settled('i_appr_rec', 'prep'); + expect(rec.run.status).toBe('failed'); + expect((await h.svc.reconcileMarkedApprovals()).judged).toEqual({ abandoned: 1 }); + + await start('approved_shared', 'crm_invoice', 'i_appr_door'); + await settle(decide('i_appr_door', 'approve', 'approver')); + const door = await settled('i_appr_door', 'prep'); + + for (const [id, first] of [['i_appr_rec', rec.first], ['i_appr_door', door.first]] as const) { + expect(await field('crm_invoice', id), id).toBe('recalled'); + expect((await requestsOn(id)).length, `${id}: no later step opened`).toBe(1); + expect(String((await timeline(String(first.id))).at(-1)![2]), `${id}: the open branch is named`).toMatch(/its branch at node 'prep'/); + } + }); + + it('control: rejected, a node the approve group also names is logged downstream of the reject edge: no open branch, rejected stays', async () => { + const { start, decide, withoutDoor, settle, settled, requestsOn, timeline, field } = helpers(h); + h.during.set('audit', async () => { await sleep(20); throw new Error('audit failed'); }); + + await start('reject_audit', 'crm_invoice', 'i_audit_rec'); + await withoutDoor(() => settle(decide('i_audit_rec', 'reject', 'approver'))); + const rec = await settled('i_audit_rec', 'audit'); + expect(rec.run.status).toBe('failed'); + expect((await h.svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + + await start('reject_audit', 'crm_invoice', 'i_audit_door'); + await settle(decide('i_audit_door', 'reject', 'approver')); + const door = await settled('i_audit_door', 'audit'); + + for (const [id, first] of [['i_audit_rec', rec.first], ['i_audit_door', door.first]] as const) { + expect(await field('crm_invoice', id), id).toBe('rejected'); + expect((await requestsOn(id)).length).toBe(1); + const lines = (await timeline(String(first.id))).map((a) => String(a[2] ?? '')); + expect(lines.some((l) => /did not go on/.test(l)), `${id}: no put-back line`).toBe(false); + } + }); + it('control: two labels share a target, and the label not taken is no open branch: a rejection stays rejected', async () => { const { start, decide, withoutDoor, settle, settled, requestsOn, timeline, field } = helpers(h); h.during.set('notify', async () => { await sleep(20); throw new Error('notify failed'); }); From 006c6f69117b3f4064d5ebf4b0bfadc6739a0450 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 02:01:22 +0000 Subject: [PATCH 09/16] fix(plugin-approvals): the fan-out judge reads conditional targets and an approval step's decision off what the platform records (#38988) M2: on a branch, a conditional or default target with neither a step nor a skipped step logged after the visit is undecided or running, and is read as the frontier. A label-routing node whose label is not recorded and not shown by a target only one group names reads every group (open), never none. S3: an approval step's label is its request's decision, read exactly (approvalStepLabels); target ownership stays for other label-routing nodes. Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- .../src/approval-fanout-judge-38988.test.ts | 58 ++++- .../src/approval-fanout-judge.ts | 204 ++++++++++++------ .../plugin-approvals/src/approval-service.ts | 12 +- 3 files changed, 199 insertions(+), 75 deletions(-) diff --git a/packages/plugins/plugin-approvals/src/approval-fanout-judge-38988.test.ts b/packages/plugins/plugin-approvals/src/approval-fanout-judge-38988.test.ts index 1dfc0c37e54..db90ac9aefe 100644 --- a/packages/plugins/plugin-approvals/src/approval-fanout-judge-38988.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-fanout-judge-38988.test.ts @@ -8,7 +8,7 @@ */ import { describe, it, expect } from 'vitest'; -import { openBranchAtEnd, runFlowBody, type FanOutEdge, type FanOutStep } from './approval-fanout-judge.js'; +import { approvalStepLabels, openBranchAtEnd, runFlowBody, type FanOutEdge, type FanOutStep } from './approval-fanout-judge.js'; const e = (source: string, target: string, extra: Partial> = {}): FanOutEdge => ({ source, target, ...extra }); const ok = (nodeId: string, extra: Record = {}): FanOutStep => ({ nodeId, status: 'success', ...extra }); @@ -72,25 +72,49 @@ describe('[#38988] openBranchAtEnd: a branch of a fan-out open at the run\'s end expect(openBranchAtEnd({ steps, late: isLate, body, standsBetween: between('first', 'late') })).toBe('late'); }); - it('two labels share the only logged target: neither is read as taken', () => { + it('two labels share the only logged target: the label recorded decides, and with none recorded both are read (open)', () => { // Rejected, `first` went to `notify` alone; `approve` also names `notify`. const body = { edges: [e('first', 'second', { label: 'approve' }), e('first', 'notify', { label: 'approve' }), e('first', 'notify', { label: 'reject' }), e('notify', 'end')] }; const steps = [ok('start'), ok('first'), failed('notify')]; - expect(openBranchAtEnd({ steps, late: isLate, body, standsBetween: between('first', 'second') })).toBeUndefined(); + const rejected = (s: FanOutStep) => (s.nodeId === 'first' ? 'reject' : undefined); + expect(openBranchAtEnd({ steps, late: isLate, body, standsBetween: between('first', 'second'), takenLabel: rejected })).toBeUndefined(); // The same with the reject edge to a refusing end beside it: a refused run reads the same. const refused = { edges: [...body.edges, e('first', 'refuse', { label: 'reject' })] }; - expect(openBranchAtEnd({ steps: [ok('start'), ok('first'), ok('notify')], late: isLate, body: refused, standsBetween: between('first', 'second') })).toBeUndefined(); + expect(openBranchAtEnd({ steps: [ok('start'), ok('first'), ok('notify')], late: isLate, body: refused, standsBetween: between('first', 'second'), takenLabel: rejected })).toBeUndefined(); + // Approved, recorded: the approve group ran, and `second` had not logged. + const approved = (s: FanOutStep) => (s.nodeId === 'first' ? 'approve' : undefined); + expect(openBranchAtEnd({ steps, late: isLate, body, standsBetween: between('first', 'second'), takenLabel: approved })).toBe('second'); + // Nothing recorded, and the log cannot tell the two labels apart: open. + expect(openBranchAtEnd({ steps, late: isLate, body, standsBetween: between('first', 'second') })).toBe('second'); }); - it('an unlabelled group on a node that claimed a label: a target it shares with the label is no evidence', () => { + it('an unlabelled group on a node that claimed a label: the label recorded decides, and a target only the unlabelled group names shows it ran', () => { const body = { edges: [e('first', 'second'), e('first', 'notify'), e('first', 'notify', { label: 'reject' })] }; const steps = [ok('start'), ok('first'), failed('notify')]; - expect(openBranchAtEnd({ steps, late: isLate, body, standsBetween: between('first', 'second') })).toBeUndefined(); - // A target the unlabelled group alone names, logged: that group ran. + expect(openBranchAtEnd({ steps, late: isLate, body, standsBetween: between('first', 'second'), takenLabel: () => 'reject' })).toBeUndefined(); const ran = { edges: [e('first', 'second'), e('first', 'log'), e('first', 'notify', { label: 'reject' })] }; expect(openBranchAtEnd({ steps: [ok('start'), ok('first'), failed('log')], late: isLate, body: ran, standsBetween: between('first', 'second') })).toBe('second'); }); + it('a label recorded as not made reads every edge; a label no edge carries makes the engine walk every edge', () => { + const body = { edges: [e('first', 'a', { label: 'approve' }), e('first', 'b', { label: 'approve' }), e('first', 'c', { label: 'reject' })] }; + const steps = [ok('first'), failed('a')]; + expect(openBranchAtEnd({ steps, late: isLate, body, standsBetween: between('c'), takenLabel: () => null })).toBe('c'); + expect(openBranchAtEnd({ steps, late: isLate, body, standsBetween: between('c'), takenLabel: () => 'revise' })).toBe('c'); + expect(openBranchAtEnd({ steps, late: isLate, body, standsBetween: between('c'), takenLabel: () => 'approve' })).toBeUndefined(); + }); + + it('a conditional or default edge on the branch: a target with neither a step nor a skipped step after the visit is open', () => { + for (const extra of [{ condition: 'true' }, { isDefault: true }]) { + const body = { edges: [e('fork', 'note'), e('fork', 'late1'), e('late1', 'dec'), e('dec', 'late2', extra), e('late2', 'second')] }; + const base = [ok('fork'), ok('late1'), ok('dec'), failed('note')]; + const sb = between('late1', 'dec', 'late2'); + expect(openBranchAtEnd({ steps: base, late: isLate, body, standsBetween: sb }), `${JSON.stringify(extra)}: undecided or running`).toBe('late2'); + expect(openBranchAtEnd({ steps: [...base, { nodeId: 'late2', status: 'skipped' }], late: isLate, body, standsBetween: sb }), `${JSON.stringify(extra)}: passed over`).toBeUndefined(); + expect(openBranchAtEnd({ steps: [...base, failed('late2')], late: isLate, body, standsBetween: sb }), `${JSON.stringify(extra)}: ran and ended`).toBeUndefined(); + } + }); + it('a group of which no target was logged was not taken', () => { const body = { edges: [e('first', 'a', { label: 'reject' }), e('first', 'b', { label: 'reject' }), e('first', 'note', { label: 'approve' })] }; const steps = [ok('start'), ok('first'), failed('note')]; @@ -140,3 +164,23 @@ describe('[#38988] runFlowBody: the body filed under the run\'s key', () => { expect(await runFlowBody({ getFlow: async () => { throw new Error('refused'); } }, 'f')).toBeNull(); }); }); + +describe('[#38988] approvalStepLabels: an approval step\'s label is its request\'s decision', () => { + const req = (node: string, status: string, created: string, run = 'r1') => ({ flow_run_id: run, flow_node_id: node, status, created_at: created }); + const visit = (node: string, completedAt: string, nodeType = 'approval'): FanOutStep => ({ nodeId: node, nodeType, status: 'success', completedAt }); + it('the decision on the request the visit opened, the last of its run and node opened by the time the step was logged', () => { + const labels = approvalStepLabels([ + req('first', 'returned', '2026-01-01T00:00:00Z'), req('first', 'approved', '2026-01-01T00:05:00Z'), req('first', 'rejected', '2026-01-01T00:05:00Z', 'other'), + ], 'r1'); + expect(labels(visit('first', '2026-01-01T00:00:01Z'))).toBe('revise'); + expect(labels(visit('first', '2026-01-01T00:05:01Z'))).toBe('approve'); + }); + it('not decided, or none opened by then: `null`; no request row, or not an approval step: `undefined`', () => { + const labels = approvalStepLabels([req('first', 'pending', '2026-01-01T00:00:00Z'), req('second', 'rejected', '2026-01-01T00:09:00Z')], 'r1'); + expect(labels(visit('first', '2026-01-01T00:00:01Z'))).toBeNull(); + expect(labels(visit('second', '2026-01-01T00:00:01Z'))).toBeNull(); + expect(labels(visit('second', '2026-01-01T00:09:01Z'))).toBe('reject'); + expect(labels(visit('third', '2026-01-01T00:00:01Z'))).toBeUndefined(); + expect(labels(visit('first', '2026-01-01T00:00:01Z', 'mark'))).toBeUndefined(); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/approval-fanout-judge.ts b/packages/plugins/plugin-approvals/src/approval-fanout-judge.ts index 7394b387640..424441d54be 100644 --- a/packages/plugins/plugin-approvals/src/approval-fanout-judge.ts +++ b/packages/plugins/plugin-approvals/src/approval-fanout-judge.ts @@ -1,5 +1,7 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +import { APPROVAL_BRANCH_LABELS } from '@objectstack/spec/automation'; + /** * [ADR-0162 Execution item 8; #38988 item 3, maintainer ruling 7329430078] * The fan-out-aware judge: whether a run that ended without reaching its end @@ -12,49 +14,62 @@ * the run ends, any approval step on another branch that has not finished * counts as not done, so the approval ended between two steps. * - * A branch is open at the run's end where the run's log by its end says so. - * "Logged" below means a top-level step the run logged by its end with a - * status other than `skipped`: a `skipped` step records a gate that did not - * open in front of a node, never the node running. + * The judge reads the facts the platform records, and where a fact is not + * recorded it reads the branch as open (the put-back, which ADR-0162 D5 + * tolerates as a resubmission), never as nothing open. "Logged" below means a + * top-level step the run logged by its end; a `skipped` step records a gate + * that did not open in front of a node, never the node running. + * + * **What follows a visit of a node** (logged as a success), edge by edge, + * `fault` edges aside (they are taken instead of these, on a failure): + * + * - **The label it took.** Where the platform recorded it, the edges it + * claims are the only ones the engine walked ({@link FanOutInput.takenLabel}: + * an approval step's label is its request's decision, read exactly). A + * label no edge carries makes the engine walk every edge. Where the node + * routes by a decision that is recorded as not made, every edge is read. + * - **Conditional and default edges.** The engine logs a `skipped` step for + * each it passed over, and a step for the target it ran once that target + * completes. So a target with either after the visit is decided; one with + * neither is undecided or still running, and is followed as open. + * - **Edges that run together** (no `condition`, not `isDefault`), grouped + * by `label`; the edges with no label form one group of their own. With + * the label recorded, or with one unlabelled group alone, that is the + * group. With no label recorded, a group is read as taken on a target the + * run logged after the visit that no other group names; where none is, + * every group is read (not recorded, so open). * - * - **Read off the flow.** The out-edges of a node that run together are - * those with no `condition`, not `isDefault` and not `fault`, grouped by - * their `label`; the edges with no label form one group of their own. A - * group is taken after a visit of the node logged as a success where: - * the node has no other group and this one is unlabelled (the engine runs - * those edges whatever the node answered), or one of the group's targets - * was logged after the visit and no other group of the node names that - * target. A node that routes by its decision (an approval's `approve` and - * `reject`) runs one label's edges, so a group is read as taken only on a - * target that group alone could have reached; where two groups share the - * only logged target, neither is read as taken. That can miss a fan-out - * the engine ran (toward the reading before this judge), never invent one. - * A taken group of two or more targets is a fan-out, and each of its - * branches is read to its frontier: from the visit, a target logged after - * it as a success is followed on through its own taken groups; the first - * node on the branch the run had not logged by its end is the frontier, - * and the branch is open there. A branch that logged a failure ended - * there. - * - **Read off the log.** A step the run logged at the top level after its - * end is a branch that was open at it ({@link FanOutInput.late}). This - * half also answers where the flow's body cannot be read. + * **A fan-out** is a visit whose edges that run together, as read above, + * number two or more. Each of its branches is read to its frontier: a target + * logged after the visit as a success is followed on through what follows + * it, as above; the first node on the branch the run had not logged by its + * end is the frontier, and the branch is open there. A branch that logged a + * failure ended there. + * + * **Read off the log**, too: a step the run logged at the top level after its + * end is a branch that was open at it ({@link FanOutInput.late}). This half + * also answers where the flow's body cannot be read. * * An open branch counts where its frontier node stands between two steps * ({@link FanOutInput.standsBetween}, the set the approval was stamped with): * a step can still follow it. The read is over the top level of the run, as * the routed-failure reading is: a region's branches are the region's. * - * The flow body is the one the engine holds under the run's key now. A body - * changed since the run was started may name other edges; the set the - * approval was stamped with is the one the judge counts by either way. + * Where it still infers: the label of a node other than an approval step, + * and of an approval step with no request row (an empty slate it approved of + * itself), is read off which targets the run logged; the flow body is the + * one the engine holds under the run's key now, and a body changed since the + * run was started may name other edges (the stamped set is what the judge + * counts by either way). * * Pure: the caller hands it the run's steps, which of them were logged after - * the run's end, the body and the stamped set. + * the run's end, the body, the stamped set and the labels it recorded. */ /** One step of a run's log, as the judge reads it. */ export interface FanOutStep { readonly nodeId?: unknown; + readonly nodeType?: unknown; readonly status?: unknown; readonly parentNodeId?: unknown; /** When the step was logged, read by the caller's {@link FanOutInput.late}. */ @@ -81,14 +96,20 @@ export interface FanOutInput { readonly body: { readonly edges?: unknown } | null | undefined; /** Whether a node of the run's flow stands between two steps of the approval. */ readonly standsBetween: (nodeId: string) => boolean; + /** + * The label the visit `step` took, where the platform recorded it: a label; + * `null` where the node routes by a decision recorded as not made; + * `undefined` where nothing is recorded ({@link approvalStepLabels}). + */ + readonly takenLabel?: (step: FanOutStep) => string | null | undefined; } /** The group key of an edge with no label: such edges form one group of their own. */ const NO_LABEL = '\u0000'; -/** Whether `edge` is one the engine runs together with its siblings. */ -function runsTogether(edge: FanOutEdge): boolean { - return edge.type !== 'fault' && !edge.condition && edge.isDefault !== true; +/** The label of an edge, or {@link NO_LABEL}. */ +function labelOf(edge: FanOutEdge): string { + return typeof edge.label === 'string' && edge.label !== '' ? edge.label : NO_LABEL; } /** @@ -96,7 +117,7 @@ function runsTogether(edge: FanOutEdge): boolean { * still follow, or `undefined` where there is none. */ export function openBranchAtEnd(input: FanOutInput): string | undefined { - const { steps, late, body, standsBetween } = input; + const { steps, late, body, standsBetween, takenLabel } = input; const topLevel = (s: FanOutStep | null | undefined): s is FanOutStep & { nodeId: string } => !!s && !s.parentNodeId && typeof s.nodeId === 'string' && s.nodeId !== ''; @@ -105,57 +126,116 @@ export function openBranchAtEnd(input: FanOutInput): string | undefined { if (topLevel(s) && late(s) && standsBetween(s.nodeId)) return s.nodeId; } - const edges = Array.isArray(body?.edges) ? (body!.edges as FanOutEdge[]) : []; + const edges = (Array.isArray(body?.edges) ? (body!.edges as FanOutEdge[]) : []) + .filter((e) => e.type !== 'fault' && typeof e.target === 'string' && e.target !== ''); if (edges.length === 0) return undefined; - /** The node each step logged by the run's end ran, or `undefined` (late, nested, skipped). */ - const logged = steps.map((s) => (topLevel(s) && !late(s) && s.status !== 'skipped' ? s.nodeId : undefined)); - const loggedAfter = (node: string, visit: number): number => { - for (let k = visit + 1; k < logged.length; k++) if (logged[k] === node) return k; + /** The node each step logged by the run's end stands for, or `undefined` (late or nested). */ + const inRun = steps.map((s) => (topLevel(s) && !late(s) ? s.nodeId : undefined)); + /** The first step logged after `visit` for `node`: any status, or (`ran`) not `skipped`. */ + const after = (node: string, visit: number, ran: boolean): number => { + for (let k = visit + 1; k < inRun.length; k++) { + if (inRun[k] === node && (!ran || steps[k].status !== 'skipped')) return k; + } return -1; }; - /** The groups of `node`'s out-edges taken after its visit at `visit` (see the module docblock). */ - const takenGroups = (node: string, visit: number): string[][] => { + + /** What follows the visit of `node` at `visit` (see the module docblock). */ + const following = (node: string, visit: number): { together: string[]; sequential: string[] } => { + let out = edges.filter((e) => e.source === node); + const label = takenLabel?.(steps[visit]); + const recorded = typeof label === 'string' && out.some((e) => e.label === label); + if (recorded) out = out.filter((e) => e.label === label); + const sequential = out + .filter((e) => !!e.condition || e.isDefault === true) + .map((e) => e.target as string) + .filter((t) => { const k = after(t, visit, false); return k < 0 || steps[k].status !== 'skipped'; }); const groups = new Map(); - for (const e of edges) { - if (e.source !== node || typeof e.target !== 'string' || !runsTogether(e)) continue; - const key = typeof e.label === 'string' && e.label !== '' ? e.label : NO_LABEL; - groups.set(key, [...(groups.get(key) ?? []), e.target]); + for (const e of out) { + if (e.condition || e.isDefault === true) continue; + groups.set(labelOf(e), [...(groups.get(labelOf(e)) ?? []), e.target as string]); + } + const all = [...groups.values()]; + let taken = all; + if (!recorded && label !== null && !(groups.size === 1 && groups.has(NO_LABEL)) && typeof label !== 'string') { + const owners = new Map(); + for (const targets of all) for (const t of new Set(targets)) owners.set(t, (owners.get(t) ?? 0) + 1); + const shown = all.filter((targets) => targets.some((t) => owners.get(t) === 1 && after(t, visit, true) >= 0)); + if (shown.length > 0) taken = shown; } - if (groups.size === 1 && groups.has(NO_LABEL)) return [groups.get(NO_LABEL)!]; - const owners = new Map(); - for (const targets of groups.values()) for (const t of new Set(targets)) owners.set(t, (owners.get(t) ?? 0) + 1); - return [...groups.values()].filter((targets) => targets.some((t) => owners.get(t) === 1 && loggedAfter(t, visit) >= 0)); + return { together: [...new Set(taken.flat())], sequential }; }; + /** The frontier of the branch that starts at `target` after the visit at `visit`, where it is open. */ const seen = new Set(); const frontierOf = (target: string, visit: number): string | undefined => { - const k = loggedAfter(target, visit); + const k = after(target, visit, true); if (k < 0) return standsBetween(target) ? target : undefined; if (steps[k].status !== 'success' || seen.has(k)) return undefined; seen.add(k); - for (const group of takenGroups(target, k)) { - for (const next of group) { - const open = frontierOf(next, k); - if (open !== undefined) return open; - } + const next = following(target, k); + for (const t of [...next.together, ...next.sequential]) { + const open = frontierOf(t, k); + if (open !== undefined) return open; } return undefined; }; - for (let i = 0; i < logged.length; i++) { - const source = logged[i]; + for (let i = 0; i < inRun.length; i++) { + const source = inRun[i]; if (source === undefined || steps[i].status !== 'success') continue; - for (const group of takenGroups(source, i)) { - if (group.length < 2) continue; - for (const target of group) { - const open = frontierOf(target, i); - if (open !== undefined) return open; - } + const { together } = following(source, i); + if (together.length < 2) continue; + for (const target of together) { + const open = frontierOf(target, i); + if (open !== undefined) return open; } } return undefined; } +/** The instant of an ISO date, or `NaN`. */ +function instantOf(v: unknown): number { + return v == null || v === '' ? NaN : new Date(v as string).getTime(); +} + +/** The label an approval step's request status says its decision took, or `null` for one not decided. */ +const LABEL_OF_REQUEST_STATUS: Readonly> = { + approved: APPROVAL_BRANCH_LABELS.approve, + rejected: APPROVAL_BRANCH_LABELS.reject, + returned: APPROVAL_BRANCH_LABELS.revise, +}; + +/** + * {@link FanOutInput.takenLabel} for the approval steps of the run `runId`, + * read off the approval's requests: a visit of an `approval` node took the + * label of the decision on the request its visit opened, the request of that + * run and node opened last by the time the step was logged (a visit logs its + * step as it pauses, once its request is written). A request not decided + * (pending, recalled, cancelled) is `null`, and so is a visit with requests + * of its node none of which opened by then. A visit of a node with no request + * row (an empty slate the step approved of itself), and any node that is not + * an approval step, is `undefined`: nothing recorded. + */ +export function approvalStepLabels( + requests: ReadonlyArray<{ flow_run_id?: unknown; flow_node_id?: unknown; status?: unknown; created_at?: unknown }>, + runId: string, +): (step: FanOutStep) => string | null | undefined { + return (step) => { + if (step?.nodeType !== 'approval' || typeof step.nodeId !== 'string') return undefined; + const mine = requests.filter((r) => r?.flow_run_id != null && String(r.flow_run_id) === runId && r.flow_node_id === step.nodeId); + if (mine.length === 0) return undefined; + const at = instantOf(step.completedAt); + let opened: (typeof mine)[number] | undefined; + for (const r of mine) { + const created = instantOf(r.created_at); + if (Number.isFinite(at) && !(created <= at)) continue; + if (!opened || instantOf(opened.created_at) < created) opened = r; + } + if (!opened) return null; + return LABEL_OF_REQUEST_STATUS[String(opened.status)] ?? null; + }; +} + /** * The flow body the engine holds under a run's key (`flowName` on its row, a * slot key where two packages hold the name), or `null` where none can be diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 3fb07ad7f3c..2e4e63192e4 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -182,7 +182,7 @@ import { consolePageLink, type ConsolePageComposer } from './public-base-url.js' import { APPROVAL_EMAIL_CHANNELS, EMAILED_APPROVAL_TOPICS } from './approval-email-templates.js'; import { enMessages } from './translations/messages.js'; import { closedValuesOf, judgeApprovalOpening, type OpeningFlow } from './approval-opening-check.js'; -import { openBranchAtEnd, openBranchWhy, runFlowBody } from './approval-fanout-judge.js'; +import { approvalStepLabels, openBranchAtEnd, openBranchWhy, runFlowBody } from './approval-fanout-judge.js'; import { gapsAreAboutTheField, openingRefusalText } from './approval-opening-refusal.js'; import { approvalMessageKey, @@ -6210,7 +6210,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega continue; } const one = await this.readApprovalRun(runId, { - stamp, lastOpened, aged, stands, item: next.item && !ownRuns.has(runId), latest, + stamp, lastOpened, aged, stands, item: next.item && !ownRuns.has(runId), latest, approval, }); read.set(runId, one); if (one.answer === 'undetermined') return { answer: 'undetermined', why: one.why, runId, kept: kept() }; @@ -6422,7 +6422,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega */ private async readApprovalRun( runId: string, - at: { stamp: readonly StampedNode[]; lastOpened: number; aged: boolean; stands: (state: string) => boolean; item: boolean; latest: any }, + at: { stamp: readonly StampedNode[]; lastOpened: number; aged: boolean; stands: (state: string) => boolean; item: boolean; latest: any; approval: readonly any[] }, ): Promise { const log: { cut?: string } = {}; const one = await this.placeApprovalRun(runId, at, log); @@ -6432,10 +6432,10 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega /** The body of {@link readApprovalRun}; `log.cut` is set where the run's step log is cut ({@link stepLogCut}). */ private async placeApprovalRun( runId: string, - at: { stamp: readonly StampedNode[]; lastOpened: number; aged: boolean; stands: (state: string) => boolean; item: boolean; latest: any }, + at: { stamp: readonly StampedNode[]; lastOpened: number; aged: boolean; stands: (state: string) => boolean; item: boolean; latest: any; approval: readonly any[] }, log: { cut?: string }, ): Promise { - const { stamp, lastOpened, aged, stands, item, latest } = at; + const { stamp, lastOpened, aged, stands, item, latest, approval } = at; const automation = this.automation!; let run: { status?: string; flowName?: string; completedAt?: string; trigger?: { object?: string; recordId?: string }; steps?: unknown; @@ -6553,7 +6553,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // which a step can still follow had not finished: the approval ended // between two steps (approval-fanout-judge.ts). const openBranch = async () => (status === 'completed' || answered ? undefined : openBranchAtEnd({ - steps, late: (s) => loggedAfterEnd(s, ended), body: await runFlowBody(automation, flow), + steps, late: (s) => loggedAfterEnd(s, ended), body: await runFlowBody(automation, flow), takenLabel: approvalStepLabels(approval, runId), standsBetween: (node) => standsBetweenSteps(stamp, flow, node), })); if (REACHED_AN_END.has(status)) { From 24adca7d19c042ac6ce41ae90c23f4cd4a8c8d2b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 02:01:39 +0000 Subject: [PATCH 10/16] docs(plugin-approvals): the rejected guard says it is on the refused arm only, and why (#38988) Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- .changeset/38988-fanout-judge.md | 5 +++-- .../plugins/plugin-approvals/src/approval-service.ts | 9 ++++++--- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/.changeset/38988-fanout-judge.md b/.changeset/38988-fanout-judge.md index 90f0711a08d..101b931f305 100644 --- a/.changeset/38988-fanout-judge.md +++ b/.changeset/38988-fanout-judge.md @@ -14,9 +14,10 @@ The maintainer ruled that when the run ends, an approval step on another branch How a branch is read as unfinished: - The judge reads the flow's out-edges that run together, and the steps the run logged by its end. It follows each branch of a fan-out past the nodes it had already logged, to the first node it had not reached. A branch counts where a step can still follow that node. -- A node that routes by its decision (an approval's `approve` and `reject` edges) runs one label's edges. A group of edges counts as taken only where the run logged a target that no other label of the node names. So the branch a decision did not take is not read as open, even where two labels share a target. +- An approval step's branch is the one its request's decision took (`approve`, `reject` or `revise`), so the branch a decision did not take is not read as open, even where two labels share a target. For another node that routes by a label, the judge reads which targets the run logged. Where that cannot tell the labels apart, every branch counts, which errs toward putting the record back. +- On a branch, a target of a conditional or default edge counts as decided only once the run logged a step for it, or a `skipped` step that passed it over. Otherwise it is undecided or still running, and counts as unfinished. - A step logged as `skipped` (a gate that did not open) does not count as the node having run. -A run refused after the approval's latest request was rejected keeps `rejected`, even with another branch still open. The ruling concerns a record marked approved with an approver missing, and a rejection is an approver's decision. +A run that ends `refused` after the approval's latest request was rejected keeps `rejected`, even with another branch still open. The ruling concerns a record marked approved with an approver missing, and a rejection is an approver's decision. This applies to a refused run only. A run that failed, was cancelled or timed out was already put back before this change when it stopped between two steps, whatever the latest decision, and it still is. A failure another branch logged after the run ended is also no longer read as a failure the flow went on from. The outcome was abandoned before as well; the timeline now names the branch that was still open instead. diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 2e4e63192e4..a439a72fd72 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -6557,9 +6557,12 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega standsBetween: (node) => standsBetweenSteps(stamp, flow, node), })); if (REACHED_AN_END.has(status)) { - // [Seat's confirmed reading of ruling 7329430078] A refusal after the - // latest request was rejected is an approver's decision, not an - // approval with an approver missing: rejected stays rejected. + // [Seat's confirmed reading of ruling 7329430078] On the refused arm + // only: a run refused after the latest request was rejected keeps + // `rejected`, an approver's decision rather than an approval with an + // approver missing. The guard is not on the failed, cancelled and timed + // out arms below: there a stop between two steps already put a rejected + // approval back before the fan-out judge, and the judge keeps that. const open = latest?.status === 'rejected' ? undefined : await openBranch(); return { answer: 'read', over: true, children, ...(open !== undefined ? { endedWhy: openBranchWhy(runId, status, open), endedAt } : {}) }; } From d91d5c696afcb9a4d86e159bf4dbab10fbd5ee2a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 02:30:38 +0000 Subject: [PATCH 11/16] test(plugin-approvals): pin a fan-out whose node carries labels it never routes by, red first (#38988) On the real engine at the round-2 head, a plain node whose out-edges carry labels fans out to a failing branch and a branch still running toward the second step; the door writes approved with the second step never asked. Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- .../approval-fanout-late-steps-38988.test.ts | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/packages/plugins/plugin-approvals/src/approval-fanout-late-steps-38988.test.ts b/packages/plugins/plugin-approvals/src/approval-fanout-late-steps-38988.test.ts index 5ee868ce965..f10e5c5fa4b 100644 --- a/packages/plugins/plugin-approvals/src/approval-fanout-late-steps-38988.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-fanout-late-steps-38988.test.ts @@ -140,6 +140,12 @@ const FLOWS = [ flow('reject_audit', [step('first', 'approver'), mark('notify'), mark('audit'), step('second', 'approver2'), step('third', 'approver2')], [edge('start', 'first'), edge('first', 'second', 'approve'), edge('first', 'audit', 'approve'), edge('first', 'notify', 'reject'), edge('notify', 'audit'), edge('audit', 'end'), ...decided('second', 'third'), edge('third', 'end', 'approve'), edge('third', 'end', 'reject')]), + // A fan-out whose edges carry labels the node never routes by: `fork` is no + // decision and no approval step, so the engine runs both. `note` fails on its + // way to the end; `late`, on its way to the second step, is still running. + flow('labelled_fork', [step('first', 'approver'), mark('fork'), mark('note'), mark('late'), step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'fork', 'approve'), edge('first', 'end', 'reject'), + edge('fork', 'note', 'notice'), edge('fork', 'late', 'go'), edge('note', 'end'), edge('late', 'second'), ...decided('second', 'end')]), // A control: the first step's reject edge reaches `fork`, which fans out // to a refusing end and to `late` (on its way to a second step). The run is // refused while the branch through `late` was never seen through: an @@ -464,6 +470,28 @@ describe('[#38988] a fan-out where one branch fails: abandoned, never approved', } }); + it('labels on the edges of a node that routes by none: the engine runs them together, and the branch still running is open', async () => { + const { start, decide, withoutDoor, settle, settled, requestsOn, timeline, field } = helpers(h); + h.during.set('note', async () => { await sleep(30); throw new Error('note failed'); }); + h.during.set('late', async () => { await sleep(150); throw new Error('late failed'); }); + + await start('labelled_fork', 'crm_invoice', 'i_lab_rec'); + await withoutDoor(() => settle(decide('i_lab_rec', 'approve', 'approver'))); + const rec = await settled('i_lab_rec', 'late'); + expect(rec.run.status).toBe('failed'); + expect((await h.svc.reconcileMarkedApprovals()).judged).toEqual({ abandoned: 1 }); + + await start('labelled_fork', 'crm_invoice', 'i_lab_door'); + await settle(decide('i_lab_door', 'approve', 'approver')); + const door = await settled('i_lab_door', 'late'); + + for (const [id, first] of [['i_lab_door', door.first], ['i_lab_rec', rec.first]] as const) { + expect(await field('crm_invoice', id), id).toBe('recalled'); + expect((await requestsOn(id)).length, `${id}: no later step opened`).toBe(1); + expect(String((await timeline(String(first.id))).at(-1)![2]), `${id}: the open branch is named`).toMatch(/its branch at node 'late'/); + } + }); + it('control: two labels share a target, and the label not taken is no open branch: a rejection stays rejected', async () => { const { start, decide, withoutDoor, settle, settled, requestsOn, timeline, field } = helpers(h); h.during.set('notify', async () => { await sleep(20); throw new Error('notify failed'); }); From 40b23f49047da4f29311dbac0f6ef2b6bd0bb91a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 02:30:38 +0000 Subject: [PATCH 12/16] fix(plugin-approvals): the fan-out judge reads target ownership only on a node that chooses a label (#38988) The engine narrows a node's out-edges to a label only where the node chose one: an approval step, or a decision that declares conditions. Any other node runs every out-edge, labelled or not, so the judge now reads every group of it instead of inferring a label from which target logged, which read a cosmetic-labelled fan-out as one branch and answered nothing open. Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- .changeset/38988-fanout-judge.md | 2 +- .../src/approval-fanout-judge-38988.test.ts | 22 ++++++++++++-- .../src/approval-fanout-judge.ts | 29 +++++++++++++++---- 3 files changed, 44 insertions(+), 9 deletions(-) diff --git a/.changeset/38988-fanout-judge.md b/.changeset/38988-fanout-judge.md index 101b931f305..564cdb82b9e 100644 --- a/.changeset/38988-fanout-judge.md +++ b/.changeset/38988-fanout-judge.md @@ -14,7 +14,7 @@ The maintainer ruled that when the run ends, an approval step on another branch How a branch is read as unfinished: - The judge reads the flow's out-edges that run together, and the steps the run logged by its end. It follows each branch of a fan-out past the nodes it had already logged, to the first node it had not reached. A branch counts where a step can still follow that node. -- An approval step's branch is the one its request's decision took (`approve`, `reject` or `revise`), so the branch a decision did not take is not read as open, even where two labels share a target. For another node that routes by a label, the judge reads which targets the run logged. Where that cannot tell the labels apart, every branch counts, which errs toward putting the record back. +- An approval step's branch is the one its request's decision took (`approve`, `reject` or `revise`), so the branch a decision did not take is not read as open, even where two labels share a target. Only an approval step and a `decision` that declares `conditions` route by a label. For such a decision, the judge reads which targets the run logged. Where that cannot tell the labels apart, every branch counts, which errs toward putting the record back. Any other node runs all its out-edges, even where they carry labels, so every branch of it counts. - On a branch, a target of a conditional or default edge counts as decided only once the run logged a step for it, or a `skipped` step that passed it over. Otherwise it is undecided or still running, and counts as unfinished. - A step logged as `skipped` (a gate that did not open) does not count as the node having run. diff --git a/packages/plugins/plugin-approvals/src/approval-fanout-judge-38988.test.ts b/packages/plugins/plugin-approvals/src/approval-fanout-judge-38988.test.ts index db90ac9aefe..037f2fa4f5c 100644 --- a/packages/plugins/plugin-approvals/src/approval-fanout-judge-38988.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-fanout-judge-38988.test.ts @@ -61,11 +61,26 @@ describe('[#38988] openBranchAtEnd: a branch of a fan-out open at the run\'s end }); it('a node that routes by its decision takes one label: the label it did not take is no open branch', () => { - const body = { edges: [e('first', 'note', { label: 'approve' }), e('first', 'late', { label: 'reject' }), e('late', 'second')] }; - const steps = [ok('start'), ok('first'), failed('note')]; + const conditions = [{ label: 'approve', expression: 'true' }]; + const body = { + nodes: [{ id: 'first', type: 'decision', config: { conditions } }], + edges: [e('first', 'note', { label: 'approve' }), e('first', 'late', { label: 'reject' }), e('late', 'second')], + }; + const steps = [ok('start'), ok('first', { nodeType: 'decision' }), failed('note')]; expect(openBranchAtEnd({ steps, late: isLate, body, standsBetween: between('first', 'late') })).toBeUndefined(); }); + it('labels on the out-edges of a node that chooses none: the engine runs every group, so the one not logged is open', () => { + const edges = [e('first', 'note', { label: 'notice' }), e('first', 'late', { label: 'go' }), e('late', 'second')]; + const steps = (nodeType: string) => [ok('start'), ok('first', { nodeType }), failed('note')]; + expect(openBranchAtEnd({ steps: steps('mark'), late: isLate, body: { edges }, standsBetween: between('late') }), 'any other node').toBe('late'); + // A decision that declares no `conditions` answers no label either. + const bare = { nodes: [{ id: 'first', type: 'decision', config: {} }], edges }; + expect(openBranchAtEnd({ steps: steps('decision'), late: isLate, body: bare, standsBetween: between('late') }), 'a bare decision').toBe('late'); + // With the type not logged, nothing says it chose a label: open. + expect(openBranchAtEnd({ steps: [ok('start'), ok('first'), failed('note')], late: isLate, body: { edges }, standsBetween: between('late') })).toBe('late'); + }); + it('two out-edges of the one label it took run together: the other is open', () => { const body = { edges: [e('first', 'note', { label: 'approve' }), e('first', 'late', { label: 'approve' }), e('first', 'end', { label: 'reject' })] }; const steps = [ok('start'), ok('first'), failed('note')]; @@ -116,8 +131,9 @@ describe('[#38988] openBranchAtEnd: a branch of a fan-out open at the run\'s end }); it('a group of which no target was logged was not taken', () => { + // An approval step with no label recorded (an empty slate it approved of itself). const body = { edges: [e('first', 'a', { label: 'reject' }), e('first', 'b', { label: 'reject' }), e('first', 'note', { label: 'approve' })] }; - const steps = [ok('start'), ok('first'), failed('note')]; + const steps = [ok('start'), ok('first', { nodeType: 'approval' }), failed('note')]; expect(openBranchAtEnd({ steps, late: isLate, body, standsBetween: between('a', 'b') })).toBeUndefined(); }); diff --git a/packages/plugins/plugin-approvals/src/approval-fanout-judge.ts b/packages/plugins/plugin-approvals/src/approval-fanout-judge.ts index 424441d54be..d98c9eabfc4 100644 --- a/packages/plugins/plugin-approvals/src/approval-fanout-judge.ts +++ b/packages/plugins/plugin-approvals/src/approval-fanout-judge.ts @@ -35,9 +35,13 @@ import { APPROVAL_BRANCH_LABELS } from '@objectstack/spec/automation'; * - **Edges that run together** (no `condition`, not `isDefault`), grouped * by `label`; the edges with no label form one group of their own. With * the label recorded, or with one unlabelled group alone, that is the - * group. With no label recorded, a group is read as taken on a target the - * run logged after the visit that no other group names; where none is, - * every group is read (not recorded, so open). + * group. A node that chooses no label runs every group, labelled or not: + * the engine narrows to a label only where the node chose one, and only an + * approval step or a `decision` that declares `conditions` does (any other + * node, a custom one included, is read as choosing none, which errs toward + * open). On a node that chooses one, with no label recorded, a group is + * read as taken on a target the run logged after the visit that no other + * group names; where none is, every group is read (not recorded, so open). * * **A fan-out** is a visit whose edges that run together, as read above, * number two or more. Each of its branches is read to its frontier: a target @@ -93,7 +97,7 @@ export interface FanOutInput { /** Whether a step was logged after the run had ended (the plugin's `loggedAfterEnd`). */ readonly late: (step: FanOutStep) => boolean; /** The flow body the run ran, where it can be read. */ - readonly body: { readonly edges?: unknown } | null | undefined; + readonly body: { readonly edges?: unknown; readonly nodes?: unknown } | null | undefined; /** Whether a node of the run's flow stands between two steps of the approval. */ readonly standsBetween: (nodeId: string) => boolean; /** @@ -107,6 +111,18 @@ export interface FanOutInput { /** The group key of an edge with no label: such edges form one group of their own. */ const NO_LABEL = '\u0000'; +/** + * Whether a visit of a node logged as `step` can have chosen a label the + * engine narrowed its out-edges to: an approval step, or a `decision` whose + * body declares `conditions` (it answers one of their labels, or `default`). + */ +function choosesALabel(step: FanOutStep, node: unknown): boolean { + if (step.nodeType === 'approval') return true; + if (step.nodeType !== 'decision' || !node || typeof node !== 'object') return false; + const conditions = (node as { config?: { conditions?: unknown } }).config?.conditions; + return Array.isArray(conditions) && conditions.length > 0; +} + /** The label of an edge, or {@link NO_LABEL}. */ function labelOf(edge: FanOutEdge): string { return typeof edge.label === 'string' && edge.label !== '' ? edge.label : NO_LABEL; @@ -129,6 +145,8 @@ export function openBranchAtEnd(input: FanOutInput): string | undefined { const edges = (Array.isArray(body?.edges) ? (body!.edges as FanOutEdge[]) : []) .filter((e) => e.type !== 'fault' && typeof e.target === 'string' && e.target !== ''); if (edges.length === 0) return undefined; + const nodes = Array.isArray(body?.nodes) ? (body!.nodes as Array<{ id?: unknown }>) : []; + const nodeOf = (id: string) => nodes.find((n) => !!n && n.id === id); /** The node each step logged by the run's end stands for, or `undefined` (late or nested). */ const inRun = steps.map((s) => (topLevel(s) && !late(s) ? s.nodeId : undefined)); /** The first step logged after `visit` for `node`: any status, or (`ran`) not `skipped`. */ @@ -156,7 +174,8 @@ export function openBranchAtEnd(input: FanOutInput): string | undefined { } const all = [...groups.values()]; let taken = all; - if (!recorded && label !== null && !(groups.size === 1 && groups.has(NO_LABEL)) && typeof label !== 'string') { + if (!recorded && label !== null && typeof label !== 'string' && !(groups.size === 1 && groups.has(NO_LABEL)) + && choosesALabel(steps[visit], nodeOf(node))) { const owners = new Map(); for (const targets of all) for (const t of new Set(targets)) owners.set(t, (owners.get(t) ?? 0) + 1); const shown = all.filter((targets) => targets.some((t) => owners.get(t) === 1 && after(t, visit, true) >= 0)); From 40b7251460cb451cc41ddb627fee7ef66c119584 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 03:22:21 +0000 Subject: [PATCH 13/16] test(plugin-approvals): pin a decision's sibling-run target and an unreadable body, red first (#38988) On the real engine at 40b23f49: a decision with conditions whose other label names a node a sibling branch ran reads that label as taken, and the door writes approved with the second step never asked; and where the flow's body cannot be read and the open branch has logged nothing, the reconciler answers finished. Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- .../approval-fanout-late-steps-38988.test.ts | 75 ++++++++++++++++++- 1 file changed, 74 insertions(+), 1 deletion(-) diff --git a/packages/plugins/plugin-approvals/src/approval-fanout-late-steps-38988.test.ts b/packages/plugins/plugin-approvals/src/approval-fanout-late-steps-38988.test.ts index f10e5c5fa4b..a538f5c86cd 100644 --- a/packages/plugins/plugin-approvals/src/approval-fanout-late-steps-38988.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-fanout-late-steps-38988.test.ts @@ -29,7 +29,7 @@ import { ObjectKernel } from '@objectstack/core'; import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; import { AutomationServicePlugin, type AutomationEngine } from '@objectstack/service-automation'; -import { ApprovalService } from './approval-service.js'; +import { ApprovalService, RECONCILER_AGE_BOUND_MS } from './approval-service.js'; import { registerApprovalNode } from './approval-node.js'; import { SysApprovalRequest } from './sys-approval-request.object.js'; import { SysApprovalAction } from './sys-approval-action.object.js'; @@ -146,6 +146,17 @@ const FLOWS = [ flow('labelled_fork', [step('first', 'approver'), mark('fork'), mark('note'), mark('late'), step('second', 'approver2')], [edge('start', 'first'), edge('first', 'fork', 'approve'), edge('first', 'end', 'reject'), edge('fork', 'note', 'notice'), edge('fork', 'late', 'go'), edge('note', 'end'), edge('late', 'second'), ...decided('second', 'end')]), + // A decision that routes by its conditions, beside a sibling that runs the + // same node: after the first step `fork` fans out to `audit` and to `dec`; + // `dec` answers `high` (to `prep`, on its way to the second step), and its + // `low` label names `audit` too. `audit`, run by the sibling, fails after + // `dec` was logged; `prep` is still running. + flow('dec_sibling', [step('first', 'approver'), mark('fork'), mark('audit'), + { id: 'dec', type: 'decision', label: 'dec', config: { conditions: [{ label: 'high', expression: 'true' }, { label: 'low', expression: 'false' }] } }, + mark('prep'), step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'fork', 'approve'), edge('first', 'end', 'reject'), + edge('fork', 'audit'), edge('fork', 'dec'), edge('dec', 'prep', 'high'), edge('dec', 'audit', 'low'), + edge('audit', 'end'), edge('prep', 'second'), ...decided('second', 'end')]), // A control: the first step's reject edge reaches `fork`, which fans out // to a refusing end and to `late` (on its way to a second step). The run is // refused while the branch through `late` was never seen through: an @@ -492,6 +503,68 @@ describe('[#38988] a fan-out where one branch fails: abandoned, never approved', } }); + it('a decision\'s label is not recorded, and the target only its other label names was run by a sibling: no evidence, the branch still running is open', async () => { + const { start, decide, withoutDoor, settle, settled, requestsOn, timeline, field } = helpers(h); + h.during.set('audit', async () => { await sleep(30); throw new Error('audit failed'); }); + h.during.set('prep', async () => { await sleep(150); throw new Error('prep failed'); }); + + await start('dec_sibling', 'crm_invoice', 'i_sib_rec'); + await withoutDoor(() => settle(decide('i_sib_rec', 'approve', 'approver'))); + const rec = await settled('i_sib_rec', 'prep'); + expect(rec.run.status).toBe('failed'); + const order = rec.run.steps.filter((s: any) => !s.parentNodeId).map((s: any) => s.nodeId); + expect(order.indexOf('dec'), 'the decision was logged before the sibling\'s audit').toBeLessThan(order.indexOf('audit')); + expect((await h.svc.reconcileMarkedApprovals()).judged).toEqual({ abandoned: 1 }); + + await start('dec_sibling', 'crm_invoice', 'i_sib_door'); + await settle(decide('i_sib_door', 'approve', 'approver')); + const door = await settled('i_sib_door', 'prep'); + + for (const [id, first] of [['i_sib_door', door.first], ['i_sib_rec', rec.first]] as const) { + expect(await field('crm_invoice', id), id).toBe('recalled'); + expect((await requestsOn(id)).length, `${id}: no later step opened`).toBe(1); + expect(String((await timeline(String(first.id))).at(-1)![2]), `${id}: the open branch is named`).toMatch(/its branch at node 'prep'/); + } + }); + + it('the flow\'s body cannot be read and the open branch has logged nothing: undetermined within the age bound, put back past it, never approved', async () => { + const { start, decide, withoutDoor, settle, requestsOn, timeline, field } = helpers(h); + let release!: () => void; + const held = new Promise((r) => { release = r; }); + h.during.set('note', async () => { await sleep(30); throw new Error('note failed'); }); + h.during.set('late', async () => { await held; throw new Error('late failed'); }); + + await start('fork_fail_both', 'crm_invoice', 'i_blind'); + await withoutDoor(() => settle(decide('i_blind', 'approve', 'approver'))); + const [first] = await requestsOn('i_blind'); + let run: any; + for (let i = 0; i < 100 && run?.status !== 'failed'; i++) { await sleep(10); run = await h.automation.getRun(String(first.record_run_id)); } + expect(run.status).toBe('failed'); + expect(run.steps.some((s: any) => s.nodeId === 'late'), 'the open branch has logged nothing').toBe(false); + // The flow is no longer registered under the run's key or its name. + const engine = h.automation as any; + const [byKey, byName] = [engine.getRunFlow, engine.getFlow]; + engine.getRunFlow = () => null; + engine.getFlow = async () => null; + try { + expect((await h.svc.reconcileMarkedApprovals()).judged, 'within the age bound').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_blind')).not.toBe('approved'); + const past = new Date(Date.now() - 2 * RECONCILER_AGE_BOUND_MS).toISOString(); + for (const r of await requestsOn('i_blind')) { + if (r.unjudged_since != null) await h.ql.update('sys_approval_request', { id: r.id, unjudged_since: past }, { context: SYS }); + } + expect((await h.svc.reconcileMarkedApprovals()).judged, 'past the age bound').toEqual({ abandoned: 1 }); + } finally { + engine.getRunFlow = byKey; + engine.getFlow = byName; + release(); + } + expect(await field('crm_invoice', 'i_blind')).toBe('recalled'); + expect((await requestsOn('i_blind')).length, 'no later step opened').toBe(1); + expect(String((await timeline(String(first.id))).at(-1)![2])).toMatch(/cannot be read/); + await sleep(20); + }); + it('control: two labels share a target, and the label not taken is no open branch: a rejection stays rejected', async () => { const { start, decide, withoutDoor, settle, settled, requestsOn, timeline, field } = helpers(h); h.during.set('notify', async () => { await sleep(20); throw new Error('notify failed'); }); From 491eff0a97ff8d57913a89a029f44908035c7f36 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 03:24:02 +0000 Subject: [PATCH 14/16] fix(plugin-approvals): the fan-out judge takes no sibling's step as a label's evidence, and an unreadable body is not nothing open (#38988) S4: on a node that chose a label not recorded, a target only one label names shows that label only where no other node the run logged before it has an edge into it (nor another visit of the node); otherwise every group is read, toward open. S5: where the run's flow body cannot be read and no branch logged after the end, the placement answers undetermined within the age bound, and past it, where the judgement before read the same, places the run at the step last decided (stoodState 'body'), the rule for a run that cannot be read. N4: the docblock names the label-chosen-but-unread case. Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- .changeset/38988-fanout-judge.md | 3 +- .../src/approval-fanout-judge-38988.test.ts | 26 +++++++- .../src/approval-fanout-judge.ts | 63 +++++++++++++++---- .../plugin-approvals/src/approval-service.ts | 47 +++++++++++--- 4 files changed, 118 insertions(+), 21 deletions(-) diff --git a/.changeset/38988-fanout-judge.md b/.changeset/38988-fanout-judge.md index 564cdb82b9e..01d0860e0f4 100644 --- a/.changeset/38988-fanout-judge.md +++ b/.changeset/38988-fanout-judge.md @@ -14,9 +14,10 @@ The maintainer ruled that when the run ends, an approval step on another branch How a branch is read as unfinished: - The judge reads the flow's out-edges that run together, and the steps the run logged by its end. It follows each branch of a fan-out past the nodes it had already logged, to the first node it had not reached. A branch counts where a step can still follow that node. -- An approval step's branch is the one its request's decision took (`approve`, `reject` or `revise`), so the branch a decision did not take is not read as open, even where two labels share a target. Only an approval step and a `decision` that declares `conditions` route by a label. For such a decision, the judge reads which targets the run logged. Where that cannot tell the labels apart, every branch counts, which errs toward putting the record back. Any other node runs all its out-edges, even where they carry labels, so every branch of it counts. +- An approval step's branch is the one its request's decision took (`approve`, `reject` or `revise`), so the branch a decision did not take is not read as open, even where two labels share a target. Only an approval step and a `decision` that declares `conditions` route by a label. For such a decision, the judge reads which targets the run logged. A target counts as showing a label only where that label alone names it and no other node the run logged, such as a sibling branch, could have run it. Where that cannot tell the labels apart, every branch counts, which errs toward putting the record back. Any other node runs all its out-edges, even where they carry labels, so every branch of it counts. - On a branch, a target of a conditional or default edge counts as decided only once the run logged a step for it, or a `skipped` step that passed it over. Otherwise it is undecided or still running, and counts as unfinished. - A step logged as `skipped` (a gate that did not open) does not count as the node having run. +- Where the flow's body cannot be read when the run is judged, a branch that has logged nothing cannot be seen. The approval is then not judged until the reconciler's age bound has passed. After that it is put back where a step can follow the step last decided, the same rule as for a run that cannot be read. A run that ends `refused` after the approval's latest request was rejected keeps `rejected`, even with another branch still open. The ruling concerns a record marked approved with an approver missing, and a rejection is an approver's decision. This applies to a refused run only. A run that failed, was cancelled or timed out was already put back before this change when it stopped between two steps, whatever the latest decision, and it still is. diff --git a/packages/plugins/plugin-approvals/src/approval-fanout-judge-38988.test.ts b/packages/plugins/plugin-approvals/src/approval-fanout-judge-38988.test.ts index 037f2fa4f5c..e10a696152b 100644 --- a/packages/plugins/plugin-approvals/src/approval-fanout-judge-38988.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-fanout-judge-38988.test.ts @@ -8,7 +8,7 @@ */ import { describe, it, expect } from 'vitest'; -import { approvalStepLabels, openBranchAtEnd, runFlowBody, type FanOutEdge, type FanOutStep } from './approval-fanout-judge.js'; +import { approvalStepLabels, flowBodyReadable, openBranchAtEnd, runFlowBody, type FanOutEdge, type FanOutStep } from './approval-fanout-judge.js'; const e = (source: string, target: string, extra: Partial> = {}): FanOutEdge => ({ source, target, ...extra }); const ok = (nodeId: string, extra: Record = {}): FanOutStep => ({ nodeId, status: 'success', ...extra }); @@ -130,6 +130,30 @@ describe('[#38988] openBranchAtEnd: a branch of a fan-out open at the run\'s end } }); + it('a target only one label names is evidence only where no other logged node could have run it', () => { + const conditions = [{ label: 'high', expression: 'true' }, { label: 'low', expression: 'false' }]; + const nodes = [{ id: 'dec', type: 'decision', config: { conditions } }]; + const decEdges = [e('dec', 'prep', { label: 'high' }), e('dec', 'audit', { label: 'low' }), e('prep', 'second')]; + const steps = [ok('fork'), ok('dec', { nodeType: 'decision' }), failed('audit')]; + // `fork` runs `audit` beside `dec`: the logged `audit` may be the sibling's, so both labels are read. + const sibling = { nodes, edges: [e('fork', 'audit'), e('fork', 'dec'), ...decEdges] }; + expect(openBranchAtEnd({ steps, late: isLate, body: sibling, standsBetween: between('prep') })).toBe('prep'); + // A fault edge into it counts as another route as well. + const faulted = { nodes, edges: [e('fork', 'dec'), e('fork', 'x'), e('x', 'audit', { type: 'fault' }), ...decEdges] }; + expect(openBranchAtEnd({ steps: [ok('fork'), failed('x'), ok('dec', { nodeType: 'decision' }), failed('audit')], late: isLate, body: faulted, standsBetween: between('prep') })).toBe('prep'); + // Only `dec` leads to `audit`: the logged `audit` shows `low`, and `high` is not read. + const alone = { nodes, edges: [e('fork', 'note'), e('fork', 'dec'), ...decEdges] }; + expect(openBranchAtEnd({ steps: [ok('fork'), ok('note'), ok('dec', { nodeType: 'decision' }), failed('audit')], late: isLate, body: alone, standsBetween: between('prep') })).toBeUndefined(); + }); + + it('flowBodyReadable: a body with an edge to follow, and nothing else', () => { + expect(flowBodyReadable({ edges: [e('a', 'b')] })).toBe(true); + expect(flowBodyReadable({ edges: [e('a', 'b', { type: 'fault' })] })).toBe(false); + expect(flowBodyReadable({ edges: [] })).toBe(false); + expect(flowBodyReadable({})).toBe(false); + expect(flowBodyReadable(null)).toBe(false); + }); + it('a group of which no target was logged was not taken', () => { // An approval step with no label recorded (an empty slate it approved of itself). const body = { edges: [e('first', 'a', { label: 'reject' }), e('first', 'b', { label: 'reject' }), e('first', 'note', { label: 'approve' })] }; diff --git a/packages/plugins/plugin-approvals/src/approval-fanout-judge.ts b/packages/plugins/plugin-approvals/src/approval-fanout-judge.ts index d98c9eabfc4..2d795f2dcfe 100644 --- a/packages/plugins/plugin-approvals/src/approval-fanout-judge.ts +++ b/packages/plugins/plugin-approvals/src/approval-fanout-judge.ts @@ -40,8 +40,12 @@ import { APPROVAL_BRANCH_LABELS } from '@objectstack/spec/automation'; * approval step or a `decision` that declares `conditions` does (any other * node, a custom one included, is read as choosing none, which errs toward * open). On a node that chooses one, with no label recorded, a group is - * read as taken on a target the run logged after the visit that no other - * group names; where none is, every group is read (not recorded, so open). + * read as taken on a target that no other group of the node names, logged + * after the visit, where no other node with an edge into that target (nor + * another visit of this one) was logged before it: then only this visit + * can have run it. A target another logged route could have reached, a + * sibling branch running the same node, is no evidence. Where no group is + * shown so, every group is read (not recorded, so open). * * **A fan-out** is a visit whose edges that run together, as read above, * number two or more. Each of its branches is read to its frontier: a target @@ -52,18 +56,26 @@ import { APPROVAL_BRANCH_LABELS } from '@objectstack/spec/automation'; * * **Read off the log**, too: a step the run logged at the top level after its * end is a branch that was open at it ({@link FanOutInput.late}). This half - * also answers where the flow's body cannot be read. + * also answers where the flow's body cannot be read, but only for a branch + * that has logged a step since the end: a branch that has logged nothing is + * seen through the body alone. So where the body cannot be read + * ({@link flowBodyReadable}) and this half finds nothing, the caller cannot + * tell whether a branch was open, and must not read it as nothing open. * * An open branch counts where its frontier node stands between two steps * ({@link FanOutInput.standsBetween}, the set the approval was stamped with): * a step can still follow it. The read is over the top level of the run, as * the routed-failure reading is: a region's branches are the region's. * - * Where it still infers: the label of a node other than an approval step, - * and of an approval step with no request row (an empty slate it approved of - * itself), is read off which targets the run logged; the flow body is the - * one the engine holds under the run's key now, and a body changed since the - * run was started may name other edges (the stamped set is what the judge + * Where it still infers: the label of a `decision` that declares + * `conditions`, and of an approval step with no request row (an empty slate + * it approved of itself), is read off which targets the run logged, as + * above; on a node that chose a label the judge could not read, its + * conditional and default edges are all read as undecided, though the + * engine walked only the edges of the label it chose and logged no + * `skipped` step for the rest (toward open); the flow body is the one the + * engine holds under the run's key now, and a body changed since the run + * was started may name other edges (the stamped set is what the judge * counts by either way). * * Pure: the caller hands it the run's steps, which of them were logged after @@ -123,6 +135,16 @@ function choosesALabel(step: FanOutStep, node: unknown): boolean { return Array.isArray(conditions) && conditions.length > 0; } +/** + * Whether `body` names edges the judge can follow: where it does not, the + * flow's body cannot be read, and {@link openBranchAtEnd} sees a branch only + * once it has logged a step after the run's end. + */ +export function flowBodyReadable(body: FanOutInput['body']): boolean { + return Array.isArray(body?.edges) + && (body!.edges as FanOutEdge[]).some((e) => e?.type !== 'fault' && typeof e?.target === 'string' && e.target !== ''); +} + /** The label of an edge, or {@link NO_LABEL}. */ function labelOf(edge: FanOutEdge): string { return typeof edge.label === 'string' && edge.label !== '' ? edge.label : NO_LABEL; @@ -142,9 +164,9 @@ export function openBranchAtEnd(input: FanOutInput): string | undefined { if (topLevel(s) && late(s) && standsBetween(s.nodeId)) return s.nodeId; } - const edges = (Array.isArray(body?.edges) ? (body!.edges as FanOutEdge[]) : []) - .filter((e) => e.type !== 'fault' && typeof e.target === 'string' && e.target !== ''); - if (edges.length === 0) return undefined; + if (!flowBodyReadable(body)) return undefined; + const every = (body!.edges as FanOutEdge[]).filter((e) => !!e && typeof e.target === 'string' && e.target !== ''); + const edges = every.filter((e) => e.type !== 'fault'); const nodes = Array.isArray(body?.nodes) ? (body!.nodes as Array<{ id?: unknown }>) : []; const nodeOf = (id: string) => nodes.find((n) => !!n && n.id === id); /** The node each step logged by the run's end stands for, or `undefined` (late or nested). */ @@ -157,6 +179,19 @@ export function openBranchAtEnd(input: FanOutInput): string | undefined { return -1; }; + /** + * Whether the step at `k` for `target` can only have come from the visit at + * `visit`: no other top-level step logged before it ran a node with an edge + * (of any kind, `fault` included) into `target`. + */ + const onlyFrom = (target: string, visit: number, k: number): boolean => { + const into = new Set(every.filter((e) => e.target === target).map((e) => e.source)); + for (let j = 0; j < k; j++) { + if (j !== visit && topLevel(steps[j]) && steps[j].status !== 'skipped' && into.has(steps[j].nodeId)) return false; + } + return true; + }; + /** What follows the visit of `node` at `visit` (see the module docblock). */ const following = (node: string, visit: number): { together: string[]; sequential: string[] } => { let out = edges.filter((e) => e.source === node); @@ -178,7 +213,11 @@ export function openBranchAtEnd(input: FanOutInput): string | undefined { && choosesALabel(steps[visit], nodeOf(node))) { const owners = new Map(); for (const targets of all) for (const t of new Set(targets)) owners.set(t, (owners.get(t) ?? 0) + 1); - const shown = all.filter((targets) => targets.some((t) => owners.get(t) === 1 && after(t, visit, true) >= 0)); + const shown = all.filter((targets) => targets.some((t) => { + if (owners.get(t) !== 1) return false; + const k = after(t, visit, true); + return k >= 0 && onlyFrom(t, visit, k); + })); if (shown.length > 0) taken = shown; } return { together: [...new Set(taken.flat())], sequential }; diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index a439a72fd72..5bf6e1b4bed 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -182,7 +182,7 @@ import { consolePageLink, type ConsolePageComposer } from './public-base-url.js' import { APPROVAL_EMAIL_CHANNELS, EMAILED_APPROVAL_TOPICS } from './approval-email-templates.js'; import { enMessages } from './translations/messages.js'; import { closedValuesOf, judgeApprovalOpening, type OpeningFlow } from './approval-opening-check.js'; -import { approvalStepLabels, openBranchAtEnd, openBranchWhy, runFlowBody } from './approval-fanout-judge.js'; +import { approvalStepLabels, flowBodyReadable, openBranchAtEnd, openBranchWhy, runFlowBody } from './approval-fanout-judge.js'; import { gapsAreAboutTheField, openingRefusalText } from './approval-opening-refusal.js'; import { approvalMessageKey, @@ -2271,16 +2271,21 @@ interface RunsRead { * - `cut`: the run's step log does not name every child run it started; * - `no_row`: the run has no row, and no run that was read speaks for it; * - `tree`: the approval's runs number more than one judgement reads (on - * the run that carries the record). + * the run that carries the record); + * - `body`: the run ended without completing, and the flow body it ran + * cannot be read, so whether a branch of it was open cannot be told. * * Spelled with spaces, kind first: it is compared as a whole and never * parsed, and it is not of the `:` shape this package keeps for * approver addresses. */ -function stoodState(kind: 'pause_gone' | 'on_ended' | 'own_node' | 'cut' | 'no_row' | 'tree', runId: string, on?: string): string { +function stoodState(kind: 'pause_gone' | 'on_ended' | 'own_node' | 'cut' | 'no_row' | 'tree' | 'body', runId: string, on?: string): string { return on === undefined ? `${kind} ${runId}` : `${kind} ${runId} ${on}`; } +/** What the fan-out judge answers where the run's flow body cannot be read ({@link ApprovalService} `placeApprovalRun`). */ +const BLIND: unique symbol = Symbol('flow body cannot be read'); + /** The instant of an ISO date, or `NaN`. */ function instantOf(v: unknown): number { return v == null || v === '' ? NaN : new Date(v as string).getTime(); @@ -6552,10 +6557,36 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // completing, a refusing `end` included, while a branch of a fan-out from // which a step can still follow had not finished: the approval ended // between two steps (approval-fanout-judge.ts). - const openBranch = async () => (status === 'completed' || answered ? undefined : openBranchAtEnd({ - steps, late: (s) => loggedAfterEnd(s, ended), body: await runFlowBody(automation, flow), takenLabel: approvalStepLabels(approval, runId), - standsBetween: (node) => standsBetweenSteps(stamp, flow, node), - })); + // + // [#38988, S5 of delta review 7333739245] Where the body cannot be read, + // a branch that has logged nothing since the end is not seen, so the + // answer is that it cannot be told (`BLIND`), never nothing open. + const openBranch = async (): Promise => { + if (status === 'completed' || answered) return undefined; + const body = await runFlowBody(automation, flow); + const open = openBranchAtEnd({ + steps, late: (s) => loggedAfterEnd(s, ended), body, takenLabel: approvalStepLabels(approval, runId), + standsBetween: (node) => standsBetweenSteps(stamp, flow, node), + }); + return open === undefined && !flowBodyReadable(body) ? BLIND : open; + }; + // The rule for a run that cannot be read (rulings A3 and B2 on #37767): + // within the age bound nothing is concluded; past it, and where the + // judgement before read the same ({@link stoodState}), the run has + // stopped at the step last decided, and a step that can follow it was + // not asked. + const blind = (): ApprovalRunRead => { + const what = `its run '${runId}' ended ${status}, and the flow it ran cannot be read, so whether a branch of it from which a step can follow was still open cannot be told`; + const stood = stands(stoodState('body', runId)); + if (!aged) return { answer: 'undetermined', why: `${what}; within the age bound nothing is concluded from it.` }; + if (!stood) { + return { answer: 'undetermined', why: `${what}; the judgement before this one did not read the same, and the next judgement places it if it still reads so.` }; + } + const step = String(latest.flow_node_id ?? latest.current_step ?? ''); + return step && standsBetweenSteps(stamp, flowNameOfProcess(latest.process_name) ?? flow, step) + ? { answer: 'read', over: true, children, endedWhy: `${what}; past the age bound it has stopped at the step '${step}' last decided, between two steps.`, ...(endedAt ? { endedAt } : {}) } + : { answer: 'read', over: true, children }; + }; if (REACHED_AN_END.has(status)) { // [Seat's confirmed reading of ruling 7329430078] On the refused arm // only: a run refused after the latest request was rejected keeps @@ -6564,6 +6595,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // out arms below: there a stop between two steps already put a rejected // approval back before the fan-out judge, and the judge keeps that. const open = latest?.status === 'rejected' ? undefined : await openBranch(); + if (open === BLIND) return blind(); return { answer: 'read', over: true, children, ...(open !== undefined ? { endedWhy: openBranchWhy(runId, status, open), endedAt } : {}) }; } if (!stop) { @@ -6573,6 +6605,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega return { answer: 'read', over: true, endedWhy: `its run '${runId}' ended ${status} at node '${stop}', between two steps.`, endedAt, children }; } const open = await openBranch(); + if (open === BLIND) return blind(); if (open !== undefined) return { answer: 'read', over: true, endedWhy: openBranchWhy(runId, status, open), endedAt, children }; return { answer: 'read', over: true, children }; } From 410f407332eee897e041521f9e3daf7c373a183a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 04:18:37 +0000 Subject: [PATCH 15/16] test(plugin-approvals): pin a decision that runs every edge and its own conditional edge, red first, and the cost control (#38988) On the real engine at 491eff0a: a decision that answers a label no edge carries runs every out-edge, and a decision's own conditional edge of the label it took reaches a target its other label names; in both the door writes approved with the second step never asked. The cost control pins the put-back the read-every-group rule accepts where a decision's label is not recorded. Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- .../approval-fanout-late-steps-38988.test.ts | 86 +++++++++++++++++++ 1 file changed, 86 insertions(+) diff --git a/packages/plugins/plugin-approvals/src/approval-fanout-late-steps-38988.test.ts b/packages/plugins/plugin-approvals/src/approval-fanout-late-steps-38988.test.ts index a538f5c86cd..e19d9d7e9cc 100644 --- a/packages/plugins/plugin-approvals/src/approval-fanout-late-steps-38988.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-fanout-late-steps-38988.test.ts @@ -157,6 +157,37 @@ const FLOWS = [ [edge('start', 'first'), edge('first', 'fork', 'approve'), edge('first', 'end', 'reject'), edge('fork', 'audit'), edge('fork', 'dec'), edge('dec', 'prep', 'high'), edge('dec', 'audit', 'low'), edge('audit', 'end'), edge('prep', 'second'), ...decided('second', 'end')]), + // A decision that declares `high` and `low`, neither of which holds, and has + // no default route: it answers `default`, no edge carries it, and the engine + // runs every out-edge. `tidy` fails while `prep`, on its way to the second + // step, is still running. + flow('dec_nodefault', [step('first', 'approver'), + { id: 'dec', type: 'decision', label: 'dec', config: { conditions: [{ label: 'high', expression: 'false' }, { label: 'low', expression: 'false' }] } }, + mark('prep'), mark('tidy'), step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'dec', 'approve'), edge('first', 'end', 'reject'), + edge('dec', 'prep', 'high'), edge('dec', 'tidy', 'low'), edge('prep', 'second'), edge('tidy', 'end'), ...decided('second', 'end')]), + // A decision whose taken label `high` has a conditional edge into `audit`, + // which its `low` label also names: `dec` answers `high`, `audit` runs first + // and is logged, then `prep` (on its way to the second step) runs; `note`, + // on the sibling branch, fails meanwhile. + flow('dec_own_cond', [step('first', 'approver'), mark('fork'), mark('note'), + { id: 'dec', type: 'decision', label: 'dec', config: { conditions: [{ label: 'high', expression: 'true' }, { label: 'low', expression: 'false' }] } }, + mark('audit'), mark('prep'), step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'fork', 'approve'), edge('first', 'end', 'reject'), + edge('fork', 'note'), edge('fork', 'dec'), edge('note', 'end'), + edge('dec', 'prep', 'high'), { id: 'dec_audit_high', source: 'dec', target: 'audit', label: 'high', condition: 'true' }, edge('dec', 'audit', 'low'), + { id: 'dec_end_default', source: 'dec', target: 'end', isDefault: true }, + edge('audit', 'end'), edge('prep', 'second'), ...decided('second', 'end')]), + // The cost of reading every group of a decision whose label is not + // recorded: approved, `first` leads to `dec`, which answers `low` (to + // `notify`, which fails); its `high` label leads to the second step (a third + // follows it), which never ran. Read as open, the record is put back. + flow('dec_low_notify', [step('first', 'approver'), + { id: 'dec', type: 'decision', label: 'dec', config: { conditions: [{ label: 'high', expression: 'false' }, { label: 'low', expression: 'true' }] } }, + mark('notify'), step('second', 'approver2'), step('third', 'approver2')], + [edge('start', 'first'), edge('first', 'dec', 'approve'), edge('first', 'notify', 'reject'), + edge('dec', 'second', 'high'), edge('dec', 'notify', 'low'), edge('notify', 'end'), + ...decided('second', 'third'), edge('third', 'end', 'approve'), edge('third', 'end', 'reject')]), // A control: the first step's reject edge reaches `fork`, which fans out // to a refusing end and to `late` (on its way to a second step). The run is // refused while the branch through `late` was never seen through: an @@ -565,6 +596,61 @@ describe('[#38988] a fan-out where one branch fails: abandoned, never approved', await sleep(20); }); + it('a decision answers a label no edge carries, and the engine runs every edge: the branch still running is open', async () => { + const { start, decide, withoutDoor, settle, settled, requestsOn, timeline, field } = helpers(h); + h.during.set('tidy', async () => { await sleep(30); throw new Error('tidy failed'); }); + h.during.set('prep', async () => { await sleep(150); throw new Error('prep failed'); }); + + await start('dec_nodefault', 'crm_invoice', 'i_nodef_rec'); + await withoutDoor(() => settle(decide('i_nodef_rec', 'approve', 'approver'))); + const rec = await settled('i_nodef_rec', 'prep'); + expect(rec.run.status).toBe('failed'); + expect((await h.svc.reconcileMarkedApprovals()).judged).toEqual({ abandoned: 1 }); + + await start('dec_nodefault', 'crm_invoice', 'i_nodef_door'); + await settle(decide('i_nodef_door', 'approve', 'approver')); + const door = await settled('i_nodef_door', 'prep'); + + for (const [id, first] of [['i_nodef_door', door.first], ['i_nodef_rec', rec.first]] as const) { + expect(await field('crm_invoice', id), id).toBe('recalled'); + expect((await requestsOn(id)).length, `${id}: no later step opened`).toBe(1); + expect(String((await timeline(String(first.id))).at(-1)![2]), `${id}: the open branch is named`).toMatch(/its branch at node 'prep'/); + } + }); + + it('a decision\'s own conditional edge of the label it took reaches a target its other label names: the branch still running is open', async () => { + const { start, decide, settle, settled, requestsOn, timeline, field } = helpers(h); + h.during.set('note', async () => { await sleep(40); throw new Error('note failed'); }); + h.during.set('prep', async () => { await sleep(150); throw new Error('prep failed'); }); + + await start('dec_own_cond', 'crm_invoice', 'i_owncond'); + await settle(decide('i_owncond', 'approve', 'approver')); + const door = await settled('i_owncond', 'prep'); + const order = door.run.steps.filter((s: any) => !s.parentNodeId).map((s: any) => s.nodeId); + expect(order.indexOf('audit'), 'the conditional edge ran first').toBeGreaterThan(order.indexOf('dec')); + expect(await field('crm_invoice', 'i_owncond'), 'the door').toBe('recalled'); + expect((await requestsOn('i_owncond')).length).toBe(1); + expect(String((await timeline(String(door.first.id))).at(-1)![2])).toMatch(/its branch at node 'prep'/); + }); + + it('control of the cost: a decision\'s label is not recorded, so every group is read, and a branch that never ran is read as open: put back, not approved', async () => { + const { start, decide, settle, requestsOn, timeline, field } = helpers(h); + h.during.set('notify', async () => { await sleep(20); throw new Error('notify failed'); }); + + await start('dec_low_notify', 'crm_invoice', 'i_cost'); + await settle(decide('i_cost', 'approve', 'approver')); + const [first] = await requestsOn('i_cost'); + let run: any; + for (let i = 0; i < 100 && run?.status !== 'failed'; i++) { await sleep(10); run = await h.automation.getRun(String(first.record_run_id)); } + expect(run.status).toBe('failed'); + expect(run.steps.some((s: any) => s.nodeId === 'second'), 'the second step never ran').toBe(false); + // ADR-0162 D5 tolerates the put-back (a resubmission); a decision's label + // is not recorded, so `high` cannot be told apart from `low`. + expect(await field('crm_invoice', 'i_cost')).toBe('recalled'); + expect((await requestsOn('i_cost')).length).toBe(1); + expect(String((await timeline(String(first.id))).at(-1)![2])).toMatch(/its branch at node 'second'/); + }); + it('control: two labels share a target, and the label not taken is no open branch: a rejection stays rejected', async () => { const { start, decide, withoutDoor, settle, settled, requestsOn, timeline, field } = helpers(h); h.during.set('notify', async () => { await sleep(20); throw new Error('notify failed'); }); From 8b6d58088d422d02ad9eee85eef42ecef15cac2a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 04:21:09 +0000 Subject: [PATCH 16/16] fix(plugin-approvals): the fan-out judge reads every group of a node whose label is not recorded (#38988) S6 of contract review 7334730161, by the rule the seat confirmed in 7334756396: where the label a node took is not recorded (a decision that declares conditions, an approval step with no request row), every group is read, always. The evidence narrowing (target ownership, the S4 predecessor test) is removed rather than refined: a logged target is no knowledge of the label, and a label no edge carries makes the engine run every edge. The recorded label (an approval step's request decision) still decides. The cost, a put-back after a branch the node did not take (S7), is the direction ADR-0162 tolerates and the seat accepted. Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- .changeset/38988-fanout-judge.md | 2 +- .../src/approval-fanout-judge-38988.test.ts | 30 +++--- .../src/approval-fanout-judge.ts | 102 +++++------------- 3 files changed, 40 insertions(+), 94 deletions(-) diff --git a/.changeset/38988-fanout-judge.md b/.changeset/38988-fanout-judge.md index 01d0860e0f4..7a51255fae6 100644 --- a/.changeset/38988-fanout-judge.md +++ b/.changeset/38988-fanout-judge.md @@ -14,7 +14,7 @@ The maintainer ruled that when the run ends, an approval step on another branch How a branch is read as unfinished: - The judge reads the flow's out-edges that run together, and the steps the run logged by its end. It follows each branch of a fan-out past the nodes it had already logged, to the first node it had not reached. A branch counts where a step can still follow that node. -- An approval step's branch is the one its request's decision took (`approve`, `reject` or `revise`), so the branch a decision did not take is not read as open, even where two labels share a target. Only an approval step and a `decision` that declares `conditions` route by a label. For such a decision, the judge reads which targets the run logged. A target counts as showing a label only where that label alone names it and no other node the run logged, such as a sibling branch, could have run it. Where that cannot tell the labels apart, every branch counts, which errs toward putting the record back. Any other node runs all its out-edges, even where they carry labels, so every branch of it counts. +- An approval step's branch is the one its request's decision took (`approve`, `reject` or `revise`), so the branch a decision did not take is not read as open, even where two labels share a target. Where the label a node took is not recorded (a `decision` that declares `conditions`, or an approval step with no request row), every branch of it counts, whatever the run logged: which targets logged cannot tell the label, and a label no edge carries makes the engine run every edge. This can put a record back after a branch the flow did not take, also in a flow with no parallel branches. The seat accepted that cost in writing, the direction ADR-0162 tolerates as a resubmission. It never reads as finished a branch the engine ran. A node that chooses no label runs all its out-edges, even where they carry labels, so every branch of it counts. - On a branch, a target of a conditional or default edge counts as decided only once the run logged a step for it, or a `skipped` step that passed it over. Otherwise it is undecided or still running, and counts as unfinished. - A step logged as `skipped` (a gate that did not open) does not count as the node having run. - Where the flow's body cannot be read when the run is judged, a branch that has logged nothing cannot be seen. The approval is then not judged until the reconciler's age bound has passed. After that it is put back where a step can follow the step last decided, the same rule as for a run that cannot be read. diff --git a/packages/plugins/plugin-approvals/src/approval-fanout-judge-38988.test.ts b/packages/plugins/plugin-approvals/src/approval-fanout-judge-38988.test.ts index e10a696152b..afbf7471d80 100644 --- a/packages/plugins/plugin-approvals/src/approval-fanout-judge-38988.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-fanout-judge-38988.test.ts @@ -60,14 +60,12 @@ describe('[#38988] openBranchAtEnd: a branch of a fan-out open at the run\'s end expect(openBranchAtEnd({ steps: LOG, late: isLate, body: null, standsBetween: between('late') })).toBeUndefined(); }); - it('a node that routes by its decision takes one label: the label it did not take is no open branch', () => { - const conditions = [{ label: 'approve', expression: 'true' }]; - const body = { - nodes: [{ id: 'first', type: 'decision', config: { conditions } }], - edges: [e('first', 'note', { label: 'approve' }), e('first', 'late', { label: 'reject' }), e('late', 'second')], - }; + it('a node that routes by its decision: the label recorded decides; a decision\'s label is not recorded, so every group is read (toward open)', () => { + const body = { edges: [e('first', 'note', { label: 'approve' }), e('first', 'late', { label: 'reject' }), e('late', 'second')] }; const steps = [ok('start'), ok('first', { nodeType: 'decision' }), failed('note')]; - expect(openBranchAtEnd({ steps, late: isLate, body, standsBetween: between('first', 'late') })).toBeUndefined(); + expect(openBranchAtEnd({ steps, late: isLate, body, standsBetween: between('first', 'late'), takenLabel: () => 'approve' }), 'recorded').toBeUndefined(); + // [the seat's reading 7334756396] A logged `note` is no knowledge of the label: `late` is read as open. + expect(openBranchAtEnd({ steps, late: isLate, body, standsBetween: between('first', 'late') }), 'not recorded').toBe('late'); }); it('labels on the out-edges of a node that chooses none: the engine runs every group, so the one not logged is open', () => { @@ -130,20 +128,21 @@ describe('[#38988] openBranchAtEnd: a branch of a fan-out open at the run\'s end } }); - it('a target only one label names is evidence only where no other logged node could have run it', () => { + it('a target only one label names is no evidence of an unrecorded label: every group is read', () => { const conditions = [{ label: 'high', expression: 'true' }, { label: 'low', expression: 'false' }]; const nodes = [{ id: 'dec', type: 'decision', config: { conditions } }]; const decEdges = [e('dec', 'prep', { label: 'high' }), e('dec', 'audit', { label: 'low' }), e('prep', 'second')]; const steps = [ok('fork'), ok('dec', { nodeType: 'decision' }), failed('audit')]; - // `fork` runs `audit` beside `dec`: the logged `audit` may be the sibling's, so both labels are read. + // `fork` runs `audit` beside `dec`: the logged `audit` may be the sibling's. const sibling = { nodes, edges: [e('fork', 'audit'), e('fork', 'dec'), ...decEdges] }; expect(openBranchAtEnd({ steps, late: isLate, body: sibling, standsBetween: between('prep') })).toBe('prep'); - // A fault edge into it counts as another route as well. + // A fault edge into it is another route as well. const faulted = { nodes, edges: [e('fork', 'dec'), e('fork', 'x'), e('x', 'audit', { type: 'fault' }), ...decEdges] }; expect(openBranchAtEnd({ steps: [ok('fork'), failed('x'), ok('dec', { nodeType: 'decision' }), failed('audit')], late: isLate, body: faulted, standsBetween: between('prep') })).toBe('prep'); - // Only `dec` leads to `audit`: the logged `audit` shows `low`, and `high` is not read. + // Only `dec` leads to `audit`: still no knowledge of the label, since a label no + // edge carries runs every edge ([the seat's reading 7334756396]); `high` is read too. const alone = { nodes, edges: [e('fork', 'note'), e('fork', 'dec'), ...decEdges] }; - expect(openBranchAtEnd({ steps: [ok('fork'), ok('note'), ok('dec', { nodeType: 'decision' }), failed('audit')], late: isLate, body: alone, standsBetween: between('prep') })).toBeUndefined(); + expect(openBranchAtEnd({ steps: [ok('fork'), ok('note'), ok('dec', { nodeType: 'decision' }), failed('audit')], late: isLate, body: alone, standsBetween: between('prep') })).toBe('prep'); }); it('flowBodyReadable: a body with an edge to follow, and nothing else', () => { @@ -154,11 +153,12 @@ describe('[#38988] openBranchAtEnd: a branch of a fan-out open at the run\'s end expect(flowBodyReadable(null)).toBe(false); }); - it('a group of which no target was logged was not taken', () => { - // An approval step with no label recorded (an empty slate it approved of itself). + it('a group of which no target was logged: not taken where the label is recorded, read where it is not', () => { const body = { edges: [e('first', 'a', { label: 'reject' }), e('first', 'b', { label: 'reject' }), e('first', 'note', { label: 'approve' })] }; const steps = [ok('start'), ok('first', { nodeType: 'approval' }), failed('note')]; - expect(openBranchAtEnd({ steps, late: isLate, body, standsBetween: between('a', 'b') })).toBeUndefined(); + expect(openBranchAtEnd({ steps, late: isLate, body, standsBetween: between('a', 'b'), takenLabel: () => 'approve' }), 'recorded').toBeUndefined(); + // An approval step with no request row (an empty slate it approved of itself): every group. + expect(openBranchAtEnd({ steps, late: isLate, body, standsBetween: between('a', 'b') }), 'not recorded').toBe('a'); }); it('conditional, default and fault edges are not run together', () => { diff --git a/packages/plugins/plugin-approvals/src/approval-fanout-judge.ts b/packages/plugins/plugin-approvals/src/approval-fanout-judge.ts index 2d795f2dcfe..577963c3ff5 100644 --- a/packages/plugins/plugin-approvals/src/approval-fanout-judge.ts +++ b/packages/plugins/plugin-approvals/src/approval-fanout-judge.ts @@ -34,18 +34,16 @@ import { APPROVAL_BRANCH_LABELS } from '@objectstack/spec/automation'; * neither is undecided or still running, and is followed as open. * - **Edges that run together** (no `condition`, not `isDefault`), grouped * by `label`; the edges with no label form one group of their own. With - * the label recorded, or with one unlabelled group alone, that is the - * group. A node that chooses no label runs every group, labelled or not: - * the engine narrows to a label only where the node chose one, and only an - * approval step or a `decision` that declares `conditions` does (any other - * node, a custom one included, is read as choosing none, which errs toward - * open). On a node that chooses one, with no label recorded, a group is - * read as taken on a target that no other group of the node names, logged - * after the visit, where no other node with an edge into that target (nor - * another visit of this one) was logged before it: then only this visit - * can have run it. A target another logged route could have reached, a - * sibling branch running the same node, is no evidence. Where no group is - * shown so, every group is read (not recorded, so open). + * the label recorded, that label's group is the one taken. With no label + * recorded, every group is read, always: a node that chooses no label runs + * every group, and on one that chooses a label the platform does not + * record (a `decision` that declares `conditions`, an approval step with + * no request row) which targets logged is no knowledge of the label, and a + * label no edge carries makes the engine run every edge anyway. Reading + * every group can read a branch the node did not take as open, which puts + * the record back (ADR-0162 D5 tolerates it as a resubmission; the seat's + * reading 7334756396 accepts that cost); it never reads as nothing open a + * branch the engine ran. * * **A fan-out** is a visit whose edges that run together, as read above, * number two or more. Each of its branches is read to its frontier: a target @@ -67,16 +65,13 @@ import { APPROVAL_BRANCH_LABELS } from '@objectstack/spec/automation'; * a step can still follow it. The read is over the top level of the run, as * the routed-failure reading is: a region's branches are the region's. * - * Where it still infers: the label of a `decision` that declares - * `conditions`, and of an approval step with no request row (an empty slate - * it approved of itself), is read off which targets the run logged, as - * above; on a node that chose a label the judge could not read, its - * conditional and default edges are all read as undecided, though the - * engine walked only the edges of the label it chose and logged no - * `skipped` step for the rest (toward open); the flow body is the one the - * engine holds under the run's key now, and a body changed since the run - * was started may name other edges (the stamped set is what the judge - * counts by either way). + * Where it reads more than the engine ran (toward open): on a node whose + * label is not recorded, every group, as above, and its conditional and + * default edges are all read as undecided, though the engine walked only the + * edges of the label it chose and logged no `skipped` step for the rest. + * Where it still infers: the flow body is the one the engine holds under + * the run's key now, and a body changed since the run was started may name + * other edges (the stamped set is what the judge counts by either way). * * Pure: the caller hands it the run's steps, which of them were logged after * the run's end, the body, the stamped set and the labels it recorded. @@ -109,7 +104,7 @@ export interface FanOutInput { /** Whether a step was logged after the run had ended (the plugin's `loggedAfterEnd`). */ readonly late: (step: FanOutStep) => boolean; /** The flow body the run ran, where it can be read. */ - readonly body: { readonly edges?: unknown; readonly nodes?: unknown } | null | undefined; + readonly body: { readonly edges?: unknown } | null | undefined; /** Whether a node of the run's flow stands between two steps of the approval. */ readonly standsBetween: (nodeId: string) => boolean; /** @@ -120,21 +115,6 @@ export interface FanOutInput { readonly takenLabel?: (step: FanOutStep) => string | null | undefined; } -/** The group key of an edge with no label: such edges form one group of their own. */ -const NO_LABEL = '\u0000'; - -/** - * Whether a visit of a node logged as `step` can have chosen a label the - * engine narrowed its out-edges to: an approval step, or a `decision` whose - * body declares `conditions` (it answers one of their labels, or `default`). - */ -function choosesALabel(step: FanOutStep, node: unknown): boolean { - if (step.nodeType === 'approval') return true; - if (step.nodeType !== 'decision' || !node || typeof node !== 'object') return false; - const conditions = (node as { config?: { conditions?: unknown } }).config?.conditions; - return Array.isArray(conditions) && conditions.length > 0; -} - /** * Whether `body` names edges the judge can follow: where it does not, the * flow's body cannot be read, and {@link openBranchAtEnd} sees a branch only @@ -145,10 +125,6 @@ export function flowBodyReadable(body: FanOutInput['body']): boolean { && (body!.edges as FanOutEdge[]).some((e) => e?.type !== 'fault' && typeof e?.target === 'string' && e.target !== ''); } -/** The label of an edge, or {@link NO_LABEL}. */ -function labelOf(edge: FanOutEdge): string { - return typeof edge.label === 'string' && edge.label !== '' ? edge.label : NO_LABEL; -} /** * The node of the first branch open at the run's end from which a step can @@ -165,10 +141,7 @@ export function openBranchAtEnd(input: FanOutInput): string | undefined { } if (!flowBodyReadable(body)) return undefined; - const every = (body!.edges as FanOutEdge[]).filter((e) => !!e && typeof e.target === 'string' && e.target !== ''); - const edges = every.filter((e) => e.type !== 'fault'); - const nodes = Array.isArray(body?.nodes) ? (body!.nodes as Array<{ id?: unknown }>) : []; - const nodeOf = (id: string) => nodes.find((n) => !!n && n.id === id); + const edges = (body!.edges as FanOutEdge[]).filter((e) => !!e && e.type !== 'fault' && typeof e.target === 'string' && e.target !== ''); /** The node each step logged by the run's end stands for, or `undefined` (late or nested). */ const inRun = steps.map((s) => (topLevel(s) && !late(s) ? s.nodeId : undefined)); /** The first step logged after `visit` for `node`: any status, or (`ran`) not `skipped`. */ @@ -179,19 +152,6 @@ export function openBranchAtEnd(input: FanOutInput): string | undefined { return -1; }; - /** - * Whether the step at `k` for `target` can only have come from the visit at - * `visit`: no other top-level step logged before it ran a node with an edge - * (of any kind, `fault` included) into `target`. - */ - const onlyFrom = (target: string, visit: number, k: number): boolean => { - const into = new Set(every.filter((e) => e.target === target).map((e) => e.source)); - for (let j = 0; j < k; j++) { - if (j !== visit && topLevel(steps[j]) && steps[j].status !== 'skipped' && into.has(steps[j].nodeId)) return false; - } - return true; - }; - /** What follows the visit of `node` at `visit` (see the module docblock). */ const following = (node: string, visit: number): { together: string[]; sequential: string[] } => { let out = edges.filter((e) => e.source === node); @@ -202,25 +162,11 @@ export function openBranchAtEnd(input: FanOutInput): string | undefined { .filter((e) => !!e.condition || e.isDefault === true) .map((e) => e.target as string) .filter((t) => { const k = after(t, visit, false); return k < 0 || steps[k].status !== 'skipped'; }); - const groups = new Map(); - for (const e of out) { - if (e.condition || e.isDefault === true) continue; - groups.set(labelOf(e), [...(groups.get(labelOf(e)) ?? []), e.target as string]); - } - const all = [...groups.values()]; - let taken = all; - if (!recorded && label !== null && typeof label !== 'string' && !(groups.size === 1 && groups.has(NO_LABEL)) - && choosesALabel(steps[visit], nodeOf(node))) { - const owners = new Map(); - for (const targets of all) for (const t of new Set(targets)) owners.set(t, (owners.get(t) ?? 0) + 1); - const shown = all.filter((targets) => targets.some((t) => { - if (owners.get(t) !== 1) return false; - const k = after(t, visit, true); - return k >= 0 && onlyFrom(t, visit, k); - })); - if (shown.length > 0) taken = shown; - } - return { together: [...new Set(taken.flat())], sequential }; + // [the seat's reading 7334756396] With the label recorded, `out` holds its + // edges alone; with none recorded, every group is read, never narrowed by + // which targets logged. + const together = out.filter((e) => !e.condition && e.isDefault !== true).map((e) => e.target as string); + return { together: [...new Set(together)], sequential }; }; /** The frontier of the branch that starts at `target` after the visit at `visit`, where it is open. */