From 8011f6496dee4313d4fd7ac45dfdf4da4d7fee1e Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 05:46:00 +0000 Subject: [PATCH 01/17] test(plugin-approvals): an approval step on a run another branch already failed (red) Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- .../src/approval-node-ended-run-38985.test.ts | 238 ++++++++++++++++++ 1 file changed, 238 insertions(+) create mode 100644 packages/plugins/plugin-approvals/src/approval-node-ended-run-38985.test.ts diff --git a/packages/plugins/plugin-approvals/src/approval-node-ended-run-38985.test.ts b/packages/plugins/plugin-approvals/src/approval-node-ended-run-38985.test.ts new file mode 100644 index 00000000000..e7c4b352cb9 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-node-ended-run-38985.test.ts @@ -0,0 +1,238 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38985, ADR-0162; maintainer ruling 7329450068] An approval step opens no + * request on a run that has already ended. + * + * The engine runs a node's unconditional out-edges together, and when one + * branch fails it does not stop the others. A branch that reaches an approval + * step after another branch's failure ended the run opened a request there: + * the step's approver was asked to decide for a run that can never resume, and + * the record was held `pending` until the dead-run sweep recalled the request. + * The step now refuses to open on a run whose status is terminal: no request + * row, no notice to the approver, nothing left pending. The record's outcome + * is the one the fan-out judge gives such a run: abandoned, never approved. + * + * A run that is still running, or still being resumed (its status reads + * `paused` until the resume ends), opens the step as before. + * + * Real kernel, real ObjectQL engine, real automation engine, real approval + * node, driver-sql on better-sqlite3 `:memory:`. + */ + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +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 { registerApprovalNode } from './approval-node.js'; +import { SysApprovalRequest } from './sys-approval-request.object.js'; +import { SysApprovalAction } from './sys-approval-action.object.js'; +import { SysApprovalApprover } from './sys-approval-approver.object.js'; +import { SysApprovalDelegation } from './sys-approval-delegation.object.js'; +import { SysApprovalToken } from './sys-approval-token.object.js'; + +const ORG = 'org_default'; +const SYS = { isSystem: true } as const; +const asPerson = (userId: string) => ({ userId, positions: [], permissions: [] }) as any; + +const text = (name: string) => ({ name, type: 'text' as const }); +const PLATFORM_GLOBAL = { enabled: false }; +const authzObjects = [ + { owner: '@objectstack/plugin-auth', def: { name: 'sys_user', label: 'User', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, email: text('email') } } }, + { owner: '@objectstack/plugin-auth', def: { name: 'sys_member', label: 'Member', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), organization_id: text('organization_id'), role: text('role') } } }, + { owner: '@objectstack/plugin-security', def: { name: 'sys_user_position', label: 'User Position', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), position: text('position'), organization_id: text('organization_id') } } }, + { owner: '@objectstack/plugin-security', def: { name: 'sys_user_permission_set', label: 'User Permission Set', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), permission_set: text('permission_set'), organization_id: text('organization_id') } } }, +] as const; + +const statusField = { + name: 'approval_status', type: 'select' as const, defaultValue: 'draft', + options: ['draft', 'pending', 'returned', 'approved', 'rejected', 'recalled'].map((value) => ({ label: value, value })), +}; +/** Closes on its approval's outcome, both ways. */ +const invoice = { name: 'crm_invoice', label: 'Invoice', fields: { name: text('name'), approval_status: statusField } }; + +const step = (id: string, approver: string) => ({ + id, type: 'approval', label: id, + config: { approvers: [{ type: 'user', value: approver }], approvalStatusField: 'approval_status' }, +}); +const mark = (id: string) => ({ id, type: 'mark', label: id }); +const START = { id: 'start', type: 'start', label: 'Start' }; +const END = { id: 'end', type: 'end', label: 'End' }; +const edge = (source: string, target: string, label?: string) => + ({ id: `${source}_${target}_${label ?? ''}`, source, target, ...(label ? { label } : {}) }); +const flow = (name: string, nodes: unknown[], edges: unknown[]) => + ({ name, label: name, type: 'autolaunched', nodes: [START, ...nodes, END], edges }); +/** `a` then `b`, the step's reject edge to the end. */ +const decided = (a: string, b: string) => [edge(a, b, 'approve'), edge(a, 'end', 'reject')]; +const sub = (id: string, flowName: string) => ({ id, type: 'subflow', label: id, config: { flowName } }); +const sleep = (ms: number) => new Promise((r) => { setTimeout(r, ms); }); + +const FLOWS = [ + // A child whose one node takes its time: the branch that calls it finishes late. + flow('child_slow', [mark('slow')], [edge('start', 'slow'), edge('slow', 'end')]), + // The card's flow. After `first`, `fork` fans out: `note` ends the run when + // it fails; `mid` calls the slow child, then reaches `second`. + flow('fork_fail_side', [step('first', 'approver'), mark('fork'), sub('mid', 'child_slow'), mark('note'), step('second', 'approver2')], + [edge('start', 'first'), ...decided('first', 'fork'), + edge('fork', 'mid'), edge('fork', 'note'), edge('note', 'end'), edge('mid', 'second'), ...decided('second', 'end')]), + // The control with no fan-out: `first`, then `second`. + flow('chain', [step('first', 'approver'), step('second', 'approver2')], + [edge('start', 'first'), ...decided('first', 'second'), ...decided('second', 'end')]), +]; + +describe('[#38985] an approval step opens no request on a run that has already ended', () => { + let kernel: ObjectKernel; + let ql: ObjectQL; + let automation: AutomationEngine; + let svc: ApprovalService; + /** What runs while a node of type `mark` executes, by id. */ + let during: Map Promise>; + let notices: Array<{ topic: string; audience: string[] }>; + + afterEach(async () => { + try { await kernel?.shutdown(); } catch { /* noop */ } + }); + + beforeEach(async () => { + during = new Map(); + notices = []; + kernel = new ObjectKernel({ logger: { level: 'silent' } } as any); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(new AutomationServicePlugin()); + await kernel.bootstrap(); + ql = kernel.getService('objectql'); + automation = kernel.getService('automation'); + + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + await driver.connect(); + ql.registerDriver(driver, true); + for (const def of [invoice, SysApprovalRequest, SysApprovalAction, SysApprovalApprover, SysApprovalDelegation, SysApprovalToken]) { + ql.registry.registerObject(def as any, 'approvals-test', 'approvals-test'); + } + for (const o of authzObjects) ql.registry.registerObject(o.def as any, o.owner); + ql.registry.registerObject( + { name: 'sys_organization', label: 'Organization', managedBy: 'better-auth', fields: { name: text('name'), slug: text('slug') } } as any, + '@objectstack/plugin-auth', + ); + await ql.syncSchemas(); + await ql.insert('sys_organization', { id: ORG, name: 'Default Organization', slug: 'default' }, { context: SYS }); + for (const id of ['owner', 'approver', 'approver2']) { + await ql.insert('sys_user', { id, email: `${id}@example.test` }, { context: SYS }); + await ql.insert('sys_member', { id: `mem_${id}`, user_id: id, organization_id: ORG, role: 'member' }, { context: SYS }); + } + const quiet = { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} }; + svc = new ApprovalService({ engine: ql, logger: quiet as any }); + svc.noteSweepClockScheduled(); + svc.attachMessaging({ emit: async (n: any) => { notices.push({ topic: n.topic, audience: n.audience }); } } as any); + svc.attachAutomation(automation as any); + registerApprovalNode(automation as any, svc, quiet as any); + (automation as any).registerNodeExecutor({ + type: 'mark', + descriptor: { type: 'mark', supportsPause: false }, + async execute(node: any) { + await during.get(node.id)?.(); + return { success: true }; + }, + }); + for (const f of FLOWS) automation.registerFlow(f.name, f as any); + }); + + const read = async (id: string) => (await ql.find('crm_invoice', { where: { id }, context: SYS }))[0]; + const field = async (id: string) => (await read(id))?.approval_status; + const requestsOn = async (id: string) => + (await ql.find('sys_approval_request', { where: { record_id: id }, orderBy: [{ field: 'created_at', order: 'asc' }], context: SYS })) as any[]; + const steps = async (id: string) => (await requestsOn(id)).map((r) => `${r.flow_node_id}:${r.status}`); + const start = async (name: string, id: string) => { + await ql.insert('crm_invoice', { id, name: id, organization_id: ORG }, { context: { isSystem: true, tenantId: ORG } }); + return automation.execute(name, { object: 'crm_invoice', record: await read(id), userId: 'owner' } as any); + }; + const decideFirst = async (id: string) => + svc.decide(String((await requestsOn(id)).find((r) => r.status === 'pending').id), { decision: 'approve', actorId: 'approver' } as any, asPerson('approver')) + .then(() => undefined, () => undefined); + /** Run `fn` with no door judging: the shape a process that died after the door's own action leaves. */ + const withoutDoor = async (fn: () => Promise): Promise => { + const judge = (svc as any).judgeApprovalAfterDoor; + (svc as any).judgeApprovalAfterDoor = async () => 'undetermined'; + try { return await fn(); } finally { (svc as any).judgeApprovalAfterDoor = judge; } + }; + /** The run carrying `id`'s first request, once it has logged `until`. */ + const loggedTo = async (id: string, until: string) => { + const runId = String((await requestsOn(id))[0].record_run_id); + for (let i = 0; i < 100; i++) { + const run: any = await automation.getRun(runId); + if (run?.steps?.some((s: any) => s.nodeId === until)) return run; + await sleep(20); + } + throw new Error(`the run '${runId}' never logged '${until}'`); + }; + const told = (who: string) => notices.filter((n) => n.topic === 'approval.requested' && n.audience.includes(who)).length; + /** `note` fails after 30 ms; the branch through `mid` reaches `second` at about 120 ms. */ + const failNote = () => { + during.set('note', async () => { await sleep(30); throw new Error('note failed'); }); + during.set('slow', () => sleep(120)); + }; + + for (const door of [true, false]) { + it(`after another branch failed, \`second\` opens no request, tells no one and leaves nothing pending (${door ? 'the door judges' : 'no door: the reconciler judges'})`, async () => { + const id = door ? 'i_door' : 'i_nodoor'; + await start('fork_fail_side', id); + expect(await steps(id)).toEqual(['first:pending']); + failNote(); + await (door ? decideFirst(id) : withoutDoor(() => decideFirst(id))); + const run = await loggedTo(id, 'second'); + await sleep(50); + + expect(run.status).toBe('failed'); + expect(run.error, 'the refusal does not replace how the run ended').toBe('note failed'); + expect(await steps(id), 'no request row for `second`').toEqual(['first:approved']); + expect(told('approver'), 'the first step was asked').toBe(1); + expect(told('approver2'), 'the approver of `second` is not asked').toBe(0); + + if (!door) await svc.reconcileMarkedApprovals(); + // The fan-out judge's outcome for such a run: abandoned, never approved. + expect(await field(id)).toBe('recalled'); + expect(await svc.releaseDeadRunRequests(), 'nothing is left for the dead-run sweep').toEqual({ scanned: 0, released: 0 }); + }); + } + + it('control: a fan-out run still running opens `second` as before', async () => { + await start('fork_fail_side', 'i_live'); + during.set('note', () => sleep(30)); + during.set('slow', () => sleep(120)); + await decideFirst('i_live'); + await loggedTo('i_live', 'second'); + + expect(await steps('i_live')).toEqual(['first:approved', 'second:pending']); + expect(told('approver2')).toBe(1); + expect(await field('i_live')).toBe('pending'); + const runId = String((await requestsOn('i_live'))[1].flow_run_id); + expect((await automation.getRun(runId))?.status).toBe('paused'); + }); + + it('control: a flow with no fan-out opens `second` as before', async () => { + await start('chain', 'i_chain'); + await decideFirst('i_chain'); + + expect(await steps('i_chain')).toEqual(['first:approved', 'second:pending']); + expect(told('approver2')).toBe(1); + expect(await field('i_chain')).toBe('pending'); + }); + + it('a run whose status cannot be read opens the step as before: an unreadable run is not an ended one', async () => { + await start('fork_fail_side', 'i_unread'); + failNote(); + const real = automation.getRun.bind(automation); + (automation as any).getRun = async (runId: string, options?: { strict?: boolean }) => { + if (new Error().stack?.includes('approval-node.ts')) throw new Error('store down'); + return real(runId, options); + }; + await decideFirst('i_unread'); + await loggedTo('i_unread', 'second'); + await sleep(50); + + expect(await steps('i_unread'), 'opened as before the refusal existed').toEqual(['first:approved', 'second:pending']); + expect(told('approver2')).toBe(1); + }); +}); From 0c5537c4dceb21d17cba24b71d9d14e0b47b1f1e Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 05:46:43 +0000 Subject: [PATCH 02/17] fix(plugin-approvals): an approval step opens no request on a run that has already ended Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- .../plugin-approvals/src/approval-node.ts | 55 ++++++++++++++++++- 1 file changed, 54 insertions(+), 1 deletion(-) diff --git a/packages/plugins/plugin-approvals/src/approval-node.ts b/packages/plugins/plugin-approvals/src/approval-node.ts index 4a0ea9a5f43..d733ef6f7ee 100644 --- a/packages/plugins/plugin-approvals/src/approval-node.ts +++ b/packages/plugins/plugin-approvals/src/approval-node.ts @@ -28,7 +28,7 @@ import { // `IApprovalService.openNodeRequest` declares for its context parameter since // commit aa4b90d9a (the full-envelope ruling: no per-site subset contracts). import type { ExecutionContext } from '@objectstack/spec/kernel'; -import type { ApprovalRecordRun, ApprovalRootRun, ApprovalService } from './approval-service.js'; +import { RUN_STATUS_LIVENESS, type ApprovalRecordRun, type ApprovalRootRun, type ApprovalService } from './approval-service.js'; import { registerApprovalReviseNode } from './approval-revise-node.js'; /** Minimal surface of the automation engine this provider depends on. */ @@ -68,6 +68,12 @@ export interface ApprovalAutomationSurface { * {@link rootRunOf} is. */ recordRunOf?(context: unknown): ApprovalRecordRun | undefined; + /** + * [#38985] The run's log entry (`AutomationEngine.getRun`), read for its + * `status` alone: a step refuses to open on a run that has already ended + * ({@link runEndedAs}). Absent, every step opens as it did before. + */ + getRun?(runId: string): Promise<{ status?: unknown } | null>; } interface MinimalLogger { @@ -194,6 +200,25 @@ export function registerApprovalNode( if (!object) return { success: false, error: `Approval node '${node.id}': no target object in context` }; if (!recordId) return { success: false, error: `Approval node '${node.id}': no record id in $record` }; + // [#38985, ruling 7329450068] A run that has already ended opens no + // request: no row, no notice to the approver, nothing held pending. A + // fan-out reaches here so: the engine runs a node's unconditional + // out-edges together and does not stop the others when one fails, so a + // branch can arrive at this step after the failure ended the run. The + // record's outcome is then the fan-out judge's (abandoned, never + // approved). Answered as this node answers its other refusals, a failed + // step; the run's own status and error stay as the run ended. + const endedAs = await runEndedAs(automation, String(runId)); + if (endedAs) { + logger?.info?.('[approvals] approval node opened no request: its run had already ended', { + node: node.id, run: String(runId), status: endedAs, + }); + return { + success: false, + error: `Approval node '${node.id}': its run '${String(runId)}' had already ended ${endedAs}, so no approval request was opened.`, + }; + } + // [ADR-0162 Execution item 7] The run's root run and record run, // recorded on the request it opens. An engine that has none for this run // (it could not read the run's tree whole: a run parked before runs @@ -293,6 +318,34 @@ export function registerApprovalNode( logger?.info?.('[approvals] approval node executor registered'); } +/** + * [#38985] The terminal status `runId` already ended in, or `null` where the + * run is live or its status cannot be told. + * + * Terminal is {@link RUN_STATUS_LIVENESS}'s `terminal`, the classification the + * dead-run sweep acts on. Only a terminal answer refuses: `paused` is a run + * being resumed onto this step (its entry reads `paused` until the resume + * ends), and a restore records `paused` over the strand it repairs, so a + * restored continuation opens. An unknown status, no entry, an engine with no + * `getRun` or a read that throws all open the step as before: an unreadable + * run is not an ended one, and the sweep still recalls a request a dead run + * left behind. + */ +async function runEndedAs(automation: ApprovalAutomationSurface, runId: string): Promise { + if (typeof automation.getRun !== 'function') return null; + let status: unknown; + try { + status = (await automation.getRun(runId))?.status; + } catch { + return null; + } + return typeof status === 'string' + && Object.prototype.hasOwnProperty.call(RUN_STATUS_LIVENESS, status) + && RUN_STATUS_LIVENESS[status as keyof typeof RUN_STATUS_LIVENESS] === 'terminal' + ? status + : null; +} + /** * [#35863] Whether `context` is a child run's: the engine starts a `subflow` * body or a `map` item with the parent's run id as `$parentRunId`. Read the From d49d76b8e8fd7699a02e76c325e13280ac0a4f81 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 05:49:33 +0000 Subject: [PATCH 03/17] test(plugin-approvals): the ended-run cells use an object that closes on its approval Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- .../src/approval-node-ended-run-38985.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/plugins/plugin-approvals/src/approval-node-ended-run-38985.test.ts b/packages/plugins/plugin-approvals/src/approval-node-ended-run-38985.test.ts index e7c4b352cb9..81e87c4e7d9 100644 --- a/packages/plugins/plugin-approvals/src/approval-node-ended-run-38985.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-node-ended-run-38985.test.ts @@ -12,6 +12,9 @@ * The step now refuses to open on a run whose status is terminal: no request * row, no notice to the approver, nothing left pending. The record's outcome * is the one the fan-out judge gives such a run: abandoned, never approved. + * Without that judge (#38988) the same refusal leaves `approved` on a record + * that closes on its approval, so the outcome assertions below also hold the + * order the two land in. * * A run that is still running, or still being resumed (its status reads * `paused` until the resume ends), opens the step as before. @@ -51,7 +54,7 @@ const statusField = { options: ['draft', 'pending', 'returned', 'approved', 'rejected', 'recalled'].map((value) => ({ label: value, value })), }; /** Closes on its approval's outcome, both ways. */ -const invoice = { name: 'crm_invoice', label: 'Invoice', fields: { name: text('name'), approval_status: statusField } }; +const invoice = { name: 'crm_invoice', label: 'Invoice', fields: { name: text('name'), approval_status: statusField }, closedStates: { approval_status: ['approved', 'rejected'] } }; const step = (id: string, approver: string) => ({ id, type: 'approval', label: id, From 74134486a747bdc909f9fb1c3c01888988395c6e Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 05:49:52 +0000 Subject: [PATCH 04/17] chore(changeset): an approval step on a run that has already ended Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- .changeset/38985-ended-run-approval-step.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 .changeset/38985-ended-run-approval-step.md diff --git a/.changeset/38985-ended-run-approval-step.md b/.changeset/38985-ended-run-approval-step.md new file mode 100644 index 00000000000..5c8a022499a --- /dev/null +++ b/.changeset/38985-ended-run-approval-step.md @@ -0,0 +1,14 @@ +--- +'@objectstack/plugin-approvals': patch +--- + +fix(plugin-approvals): an approval step opens no request on a run that has already ended + +Clause-②: no +Metadata-protocol: none + +When a flow's node fans out to branches that run together and one branch fails, the run ends while the other branches keep going. A branch that reached an approval step after that still opened a request there: the step's approver was notified and asked to decide for a run that can never resume, and the record was held `pending` until the dead-run sweep recalled the request (every 5 minutes by default, and never on a host with no job service). + +The approval step now reads its run's status before it opens a request. Where the run has already ended (completed, failed, cancelled, timed out, refused or missed), it opens no request, sends no notice and leaves nothing pending. The step is logged as failed with a sentence naming the run and how it ended; the run keeps the status and error it ended with. The record's outcome is the one the approval plugin gives a fan-out where one branch fails: abandoned, never approved. + +A run that is still running, or still being resumed onto the step, opens it as before, and so does a run whose status cannot be read: an unreadable run is not taken for an ended one, and the dead-run sweep still recalls a request a dead run left behind. From 9e5a5787bfa67c6f7a7d23c2ff2b376e5c7f5f5e Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 05:55:16 +0000 Subject: [PATCH 05/17] fix(plugin-approvals): refuse only where the ended run's log went on past its end, so a restored strand still opens Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- .changeset/38985-ended-run-approval-step.md | 4 +- .../plugin-approvals/src/approval-node.ts | 76 +++++++++++++------ 2 files changed, 55 insertions(+), 25 deletions(-) diff --git a/.changeset/38985-ended-run-approval-step.md b/.changeset/38985-ended-run-approval-step.md index 5c8a022499a..4ca8264c8d9 100644 --- a/.changeset/38985-ended-run-approval-step.md +++ b/.changeset/38985-ended-run-approval-step.md @@ -9,6 +9,6 @@ Metadata-protocol: none When a flow's node fans out to branches that run together and one branch fails, the run ends while the other branches keep going. A branch that reached an approval step after that still opened a request there: the step's approver was notified and asked to decide for a run that can never resume, and the record was held `pending` until the dead-run sweep recalled the request (every 5 minutes by default, and never on a host with no job service). -The approval step now reads its run's status before it opens a request. Where the run has already ended (completed, failed, cancelled, timed out, refused or missed), it opens no request, sends no notice and leaves nothing pending. The step is logged as failed with a sentence naming the run and how it ended; the run keeps the status and error it ended with. The record's outcome is the one the approval plugin gives a fan-out where one branch fails: abandoned, never approved. +The approval step now reads its run's log before it opens a request. Where the run has already ended (completed, failed, cancelled, timed out, refused or missed) and the log shows a step completed after that end, so another branch went on to this step, it opens no request, sends no notice and leaves nothing pending. The step is logged as failed with a sentence naming the run and how it ended; the run keeps the status and error it ended with. The record's outcome is the one the approval plugin gives a fan-out where one branch fails: abandoned, never approved. -A run that is still running, or still being resumed onto the step, opens it as before, and so does a run whose status cannot be read: an unreadable run is not taken for an ended one, and the dead-run sweep still recalls a request a dead run left behind. +A run that is still running, or still being resumed onto the step, opens it as before. So does a run that stranded and was restored and is now resumed again: its log still reads the end it stranded with, but nothing logged after it. A run whose status cannot be read also opens the step: an unreadable run is not taken for an ended one. Where a branch reaches the step before it has logged any step past the run's end (the step is the first node after the fan-out and the failure landed first), the step still opens, and the dead-run sweep recalls the request as before. diff --git a/packages/plugins/plugin-approvals/src/approval-node.ts b/packages/plugins/plugin-approvals/src/approval-node.ts index d733ef6f7ee..8b00c3229bb 100644 --- a/packages/plugins/plugin-approvals/src/approval-node.ts +++ b/packages/plugins/plugin-approvals/src/approval-node.ts @@ -70,10 +70,15 @@ export interface ApprovalAutomationSurface { recordRunOf?(context: unknown): ApprovalRecordRun | undefined; /** * [#38985] The run's log entry (`AutomationEngine.getRun`), read for its - * `status` alone: a step refuses to open on a run that has already ended - * ({@link runEndedAs}). Absent, every step opens as it did before. + * status, its end and its steps' ends: a step refuses to open on a run that + * has already ended while another branch went on ({@link runEndedAs}). + * Absent, every step opens as it did before. */ - getRun?(runId: string): Promise<{ status?: unknown } | null>; + getRun?(runId: string): Promise<{ + status?: unknown; + completedAt?: unknown; + steps?: ReadonlyArray<{ completedAt?: unknown } | null | undefined>; + } | null>; } interface MinimalLogger { @@ -200,9 +205,10 @@ export function registerApprovalNode( if (!object) return { success: false, error: `Approval node '${node.id}': no target object in context` }; if (!recordId) return { success: false, error: `Approval node '${node.id}': no record id in $record` }; - // [#38985, ruling 7329450068] A run that has already ended opens no - // request: no row, no notice to the approver, nothing held pending. A - // fan-out reaches here so: the engine runs a node's unconditional + // [#38985, ruling 7329450068] A run that has already ended, while + // another branch of it went on to this step, opens no request: no row, + // no notice to the approver, nothing held pending. A fan-out reaches + // here so: the engine runs a node's unconditional // out-edges together and does not stop the others when one fails, so a // branch can arrive at this step after the failure ended the run. The // record's outcome is then the fan-out judge's (abandoned, never @@ -319,31 +325,55 @@ export function registerApprovalNode( } /** - * [#38985] The terminal status `runId` already ended in, or `null` where the - * run is live or its status cannot be told. + * [#38985] The terminal status `runId` already ended in while another branch + * of it went on, or `null`: the run is live, or its status cannot be told, or + * nothing says it is still going on past its end. * - * Terminal is {@link RUN_STATUS_LIVENESS}'s `terminal`, the classification the - * dead-run sweep acts on. Only a terminal answer refuses: `paused` is a run - * being resumed onto this step (its entry reads `paused` until the resume - * ends), and a restore records `paused` over the strand it repairs, so a - * restored continuation opens. An unknown status, no entry, an engine with no - * `getRun` or a read that throws all open the step as before: an unreadable - * run is not an ended one, and the sweep still recalls a request a dead run - * left behind. + * Two facts, both read off the run's log entry: + * + * - its status is terminal, {@link RUN_STATUS_LIVENESS}'s classification + * (the one the dead-run sweep acts on); + * - and the run logged a step after that end: a step completed after the + * run's `completedAt`, strictly, as the plugin's other readers of a + * fan-out read a late step. That is the engine going on with another + * branch after a failure (or an `end` that refuses) ended the run, the + * traversal that has now reached this step. + * + * The status alone is not enough. A repaired strand is resumed again while + * its log still reads the end it stranded with: a restore records `paused` + * in this process, but the durable terminal row wins once the resume has + * consumed the pause (measured: the restored-continuation and resubmit + * replays read `failed` at their next step). That row is the snapshot of the + * strand, written at its end, so it carries no step after it, and the step + * opens. Every other answer opens the step as before too: a live status (a + * run being resumed onto this step reads `paused` until the resume ends), an + * unknown status, no entry, no readable end, an engine with no `getRun`, or a + * read that throws. An unreadable run is not an ended one, and the dead-run + * sweep still recalls a request a dead run left behind; so does it where a + * branch reaches this step before it has logged any step past the end (the + * step is the first node after the fan-out and the failure landed first). */ async function runEndedAs(automation: ApprovalAutomationSurface, runId: string): Promise { if (typeof automation.getRun !== 'function') return null; - let status: unknown; + let run: Awaited>>; try { - status = (await automation.getRun(runId))?.status; + run = await automation.getRun(runId); } catch { return null; } - return typeof status === 'string' - && Object.prototype.hasOwnProperty.call(RUN_STATUS_LIVENESS, status) - && RUN_STATUS_LIVENESS[status as keyof typeof RUN_STATUS_LIVENESS] === 'terminal' - ? status - : null; + const status = run?.status; + if (typeof status !== 'string' + || !Object.prototype.hasOwnProperty.call(RUN_STATUS_LIVENESS, status) + || RUN_STATUS_LIVENESS[status as keyof typeof RUN_STATUS_LIVENESS] !== 'terminal') return null; + const ended = instantOf(run?.completedAt); + if (!Number.isFinite(ended)) return null; + const wentOn = (run?.steps ?? []).some((step) => instantOf(step?.completedAt) > ended); + return wentOn ? status : null; +} + +/** An ISO 8601 instant as epoch milliseconds; `NaN` where it is not one. */ +function instantOf(value: unknown): number { + return typeof value === 'string' ? Date.parse(value) : Number.NaN; } /** From 4b9043e688050f0baa536b0b331f519c9cdca918 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 06:02:54 +0000 Subject: [PATCH 06/17] fix(plugin-approvals): the approval node reads getRun through the resume surface's declared type Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- .../plugins/plugin-approvals/src/approval-node.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/plugins/plugin-approvals/src/approval-node.ts b/packages/plugins/plugin-approvals/src/approval-node.ts index 8b00c3229bb..500c6d6d060 100644 --- a/packages/plugins/plugin-approvals/src/approval-node.ts +++ b/packages/plugins/plugin-approvals/src/approval-node.ts @@ -28,7 +28,9 @@ import { // `IApprovalService.openNodeRequest` declares for its context parameter since // commit aa4b90d9a (the full-envelope ruling: no per-site subset contracts). import type { ExecutionContext } from '@objectstack/spec/kernel'; -import { RUN_STATUS_LIVENESS, type ApprovalRecordRun, type ApprovalRootRun, type ApprovalService } from './approval-service.js'; +import { + RUN_STATUS_LIVENESS, type ApprovalRecordRun, type ApprovalResumeSurface, type ApprovalRootRun, type ApprovalService, +} from './approval-service.js'; import { registerApprovalReviseNode } from './approval-revise-node.js'; /** Minimal surface of the automation engine this provider depends on. */ @@ -74,11 +76,7 @@ export interface ApprovalAutomationSurface { * has already ended while another branch went on ({@link runEndedAs}). * Absent, every step opens as it did before. */ - getRun?(runId: string): Promise<{ - status?: unknown; - completedAt?: unknown; - steps?: ReadonlyArray<{ completedAt?: unknown } | null | undefined>; - } | null>; + getRun?: ApprovalResumeSurface['getRun']; } interface MinimalLogger { @@ -367,7 +365,9 @@ async function runEndedAs(automation: ApprovalAutomationSurface, runId: string): || RUN_STATUS_LIVENESS[status as keyof typeof RUN_STATUS_LIVENESS] !== 'terminal') return null; const ended = instantOf(run?.completedAt); if (!Number.isFinite(ended)) return null; - const wentOn = (run?.steps ?? []).some((step) => instantOf(step?.completedAt) > ended); + // `completedAt` is on every step the engine logs; the surface this reads + // through declares the step fields its other readers use. + const wentOn = (run?.steps ?? []).some((step) => instantOf((step as { completedAt?: unknown } | null)?.completedAt) > ended); return wentOn ? status : null; } From 594e1406b9d737796c27310351a62a03171c2e51 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 07:08:06 +0000 Subject: [PATCH 07/17] =?UTF-8?q?chore(changeset):=20declare=20#38985=20as?= =?UTF-8?q?=20Clause-=E2=91=A1=20yes=20(widening):=20ApprovalAutomationSur?= =?UTF-8?q?face=20gains=20optional=20getRun=20(#38985)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- .changeset/38985-ended-run-approval-step.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.changeset/38985-ended-run-approval-step.md b/.changeset/38985-ended-run-approval-step.md index 4ca8264c8d9..c80162f7000 100644 --- a/.changeset/38985-ended-run-approval-step.md +++ b/.changeset/38985-ended-run-approval-step.md @@ -4,9 +4,11 @@ fix(plugin-approvals): an approval step opens no request on a run that has already ended -Clause-②: no +Clause-②: yes (widening) Metadata-protocol: none +The widening: the exported `ApprovalAutomationSurface` gains an optional member, `getRun?: ApprovalResumeSurface['getRun']`, the run log read the approval step makes before it opens a request; a host that passes an engine without it opens the step as before. + When a flow's node fans out to branches that run together and one branch fails, the run ends while the other branches keep going. A branch that reached an approval step after that still opened a request there: the step's approver was notified and asked to decide for a run that can never resume, and the record was held `pending` until the dead-run sweep recalled the request (every 5 minutes by default, and never on a host with no job service). The approval step now reads its run's log before it opens a request. Where the run has already ended (completed, failed, cancelled, timed out, refused or missed) and the log shows a step completed after that end, so another branch went on to this step, it opens no request, sends no notice and leaves nothing pending. The step is logged as failed with a sentence naming the run and how it ended; the run keeps the status and error it ended with. The record's outcome is the one the approval plugin gives a fan-out where one branch fails: abandoned, never approved. From 685a81f2c6ac2dfbfd27439bfae07f99c8edad4a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 07:48:14 +0000 Subject: [PATCH 08/17] test(plugin-approvals): a refused step on an ended run leaves every object kind recalled (red on objects the judge does not judge) Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- .../src/approval-node-ended-run-38985.test.ts | 91 +++++++++++++------ 1 file changed, 63 insertions(+), 28 deletions(-) diff --git a/packages/plugins/plugin-approvals/src/approval-node-ended-run-38985.test.ts b/packages/plugins/plugin-approvals/src/approval-node-ended-run-38985.test.ts index 81e87c4e7d9..ebd33b34c90 100644 --- a/packages/plugins/plugin-approvals/src/approval-node-ended-run-38985.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-node-ended-run-38985.test.ts @@ -53,8 +53,13 @@ const statusField = { name: 'approval_status', type: 'select' as const, defaultValue: 'draft', options: ['draft', 'pending', 'returned', 'approved', 'rejected', 'recalled'].map((value) => ({ label: value, value })), }; -/** Closes on its approval's outcome, both ways. */ -const invoice = { name: 'crm_invoice', label: 'Invoice', fields: { name: text('name'), approval_status: statusField }, closedStates: { approval_status: ['approved', 'rejected'] } }; +const fields = { name: text('name'), approval_status: statusField, stage: text('stage') }; +/** Closes on its approval's outcome, both ways: the fan-out judge puts the record back. */ +const invoice = { name: 'crm_invoice', label: 'Invoice', fields, closedStates: { approval_status: ['approved', 'rejected'] } }; +/** Declares no closed state: no judge runs, the decision on `first` is mirrored at once. */ +const memo = { name: 'crm_memo', label: 'Memo', fields }; +/** Declares closed states on another field than the approval's. */ +const ticket = { name: 'crm_ticket', label: 'Ticket', fields, closedStates: { stage: ['done'] } }; const step = (id: string, approver: string) => ({ id, type: 'approval', label: id, @@ -111,7 +116,7 @@ describe('[#38985] an approval step opens no request on a run that has already e const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); await driver.connect(); ql.registerDriver(driver, true); - for (const def of [invoice, SysApprovalRequest, SysApprovalAction, SysApprovalApprover, SysApprovalDelegation, SysApprovalToken]) { + for (const def of [invoice, memo, ticket, SysApprovalRequest, SysApprovalAction, SysApprovalApprover, SysApprovalDelegation, SysApprovalToken]) { ql.registry.registerObject(def as any, 'approvals-test', 'approvals-test'); } for (const o of authzObjects) ql.registry.registerObject(o.def as any, o.owner); @@ -142,15 +147,23 @@ describe('[#38985] an approval step opens no request on a run that has already e for (const f of FLOWS) automation.registerFlow(f.name, f as any); }); - const read = async (id: string) => (await ql.find('crm_invoice', { where: { id }, context: SYS }))[0]; + /** The object each record id was started on. */ + const objectOf = new Map(); + const read = async (id: string) => (await ql.find(objectOf.get(id) ?? 'crm_invoice', { where: { id }, context: SYS }))[0]; const field = async (id: string) => (await read(id))?.approval_status; const requestsOn = async (id: string) => (await ql.find('sys_approval_request', { where: { record_id: id }, orderBy: [{ field: 'created_at', order: 'asc' }], context: SYS })) as any[]; const steps = async (id: string) => (await requestsOn(id)).map((r) => `${r.flow_node_id}:${r.status}`); - const start = async (name: string, id: string) => { - await ql.insert('crm_invoice', { id, name: id, organization_id: ORG }, { context: { isSystem: true, tenantId: ORG } }); - return automation.execute(name, { object: 'crm_invoice', record: await read(id), userId: 'owner' } as any); + const start = async (name: string, id: string, object = 'crm_invoice') => { + objectOf.set(id, object); + await ql.insert(object, { id, name: id, organization_id: ORG }, { context: { isSystem: true, tenantId: ORG } }); + return automation.execute(name, { object, record: await read(id), userId: 'owner' } as any); }; + const timeline = async (requestId: string) => + (await ql.find('sys_approval_action', { where: { request_id: requestId }, orderBy: [{ field: 'created_at', order: 'asc' }], context: SYS }) as any[]) + .map((a) => ({ action: a.action, actor: a.actor_id ?? null, comment: a.comment ?? null })); + /** The decided request's own columns: what a later write must leave as the approver wrote it. */ + const decidedRow = (r: any) => ({ id: r.id, status: r.status, completed_at: r.completed_at, pending_approvers: r.pending_approvers ?? null, flow_node_id: r.flow_node_id, node_config_json: r.node_config_json }); const decideFirst = async (id: string) => svc.decide(String((await requestsOn(id)).find((r) => r.status === 'pending').id), { decision: 'approve', actorId: 'approver' } as any, asPerson('approver')) .then(() => undefined, () => undefined); @@ -177,27 +190,49 @@ describe('[#38985] an approval step opens no request on a run that has already e during.set('slow', () => sleep(120)); }; - for (const door of [true, false]) { - it(`after another branch failed, \`second\` opens no request, tells no one and leaves nothing pending (${door ? 'the door judges' : 'no door: the reconciler judges'})`, async () => { - const id = door ? 'i_door' : 'i_nodoor'; - await start('fork_fail_side', id); - expect(await steps(id)).toEqual(['first:pending']); - failNote(); - await (door ? decideFirst(id) : withoutDoor(() => decideFirst(id))); - const run = await loggedTo(id, 'second'); - await sleep(50); - - expect(run.status).toBe('failed'); - expect(run.error, 'the refusal does not replace how the run ended').toBe('note failed'); - expect(await steps(id), 'no request row for `second`').toEqual(['first:approved']); - expect(told('approver'), 'the first step was asked').toBe(1); - expect(told('approver2'), 'the approver of `second` is not asked').toBe(0); - - if (!door) await svc.reconcileMarkedApprovals(); - // The fan-out judge's outcome for such a run: abandoned, never approved. - expect(await field(id)).toBe('recalled'); - expect(await svc.releaseDeadRunRequests(), 'nothing is left for the dead-run sweep').toEqual({ scanned: 0, released: 0 }); - }); + const KINDS = [ + ['crm_invoice', 'an object that closes on its approval: the fan-out judge puts it back'], + ['crm_memo', 'an object with no closed state: the step puts it back'], + ['crm_ticket', 'an object that closes on another field: the step puts it back'], + ] as const; + for (const [object, kind] of KINDS) { + for (const door of [true, false]) { + it(`after another branch failed, \`second\` opens no request, tells no one, and the record ends recalled: ${kind} (${door ? 'the door judges' : 'no door'})`, async () => { + const id = `${object}_${door ? 'door' : 'nodoor'}`; + await start('fork_fail_side', id, object); + expect(await steps(id)).toEqual(['first:pending']); + failNote(); + await (door ? decideFirst(id) : withoutDoor(() => decideFirst(id))); + const first = decidedRow((await requestsOn(id))[0]); + expect(first.status).toBe('approved'); + await loggedTo(id, 'second'); + await sleep(50); + const runId = String((await requestsOn(id))[0].record_run_id); + const run: any = await automation.getRun(runId); + + expect(run.status).toBe('failed'); + expect(run.error, 'the refusal does not replace how the run ended').toBe('note failed'); + expect(await steps(id), 'no request row for `second`').toEqual(['first:approved']); + expect(decidedRow((await requestsOn(id))[0]), 'the first approver\'s decided row stays as written').toEqual(first); + expect(told('approver'), 'the first step was asked').toBe(1); + expect(told('approver2'), 'the approver of `second` is not asked').toBe(0); + + if (!door) await svc.reconcileMarkedApprovals(); + expect(await field(id), 'abandoned, never approved').toBe('recalled'); + expect(await svc.releaseDeadRunRequests(), 'nothing is left for the dead-run sweep').toEqual({ scanned: 0, released: 0 }); + expect(await svc.reconcileMarkedApprovals(), 'nothing is left for the reconciler').toMatchObject({ scanned: 0 }); + + const recalls = (await timeline(String(first.id))).filter((t) => t.action === 'recall'); + if (object === 'crm_invoice') { + expect(recalls, 'the judge already put it back: the step writes nothing more').toEqual([]); + } else { + expect(recalls).toEqual([{ + action: 'recall', actor: null, + comment: `owning flow run ${runId} is failed: step 'second' opened no request, so the approval was abandoned and the record put back`, + }]); + } + }); + } } it('control: a fan-out run still running opens `second` as before', async () => { From 4d501117d7348080742da014c00b800175695bc6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 07:49:27 +0000 Subject: [PATCH 09/17] fix(plugin-approvals): a step refused on an ended run puts the record back where the dead-run sweep would, on every object Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- .../plugin-approvals/src/approval-node.ts | 24 +++++-- .../plugin-approvals/src/approval-service.ts | 66 +++++++++++++++++++ 2 files changed, 86 insertions(+), 4 deletions(-) diff --git a/packages/plugins/plugin-approvals/src/approval-node.ts b/packages/plugins/plugin-approvals/src/approval-node.ts index 500c6d6d060..443a2674155 100644 --- a/packages/plugins/plugin-approvals/src/approval-node.ts +++ b/packages/plugins/plugin-approvals/src/approval-node.ts @@ -82,6 +82,7 @@ export interface ApprovalAutomationSurface { interface MinimalLogger { info?: (msg: any, ...rest: any[]) => void; warn?: (msg: any, ...rest: any[]) => void; + error?: (msg: any, ...rest: any[]) => void; } const SYSTEM_CTX: ExecutionContext = { isSystem: true, positions: [], permissions: [] }; @@ -217,10 +218,25 @@ export function registerApprovalNode( logger?.info?.('[approvals] approval node opened no request: its run had already ended', { node: node.id, run: String(runId), status: endedAs, }); - return { - success: false, - error: `Approval node '${node.id}': its run '${String(runId)}' had already ended ${endedAs}, so no approval request was opened.`, - }; + const refusal = `Approval node '${node.id}': its run '${String(runId)}' had already ended ${endedAs}, so no approval request was opened.`; + // [#38985, seat ruling 7338562363] The record ends where the dead-run + // sweep would put it, on every object: no request is left for that + // sweep to find, and on an object the fan-out judge does not judge the + // field still holds the last decision's value. + try { + await service.abandonAtRefusedStep({ + runId: String(runId), nodeId: node.id, object, recordId: String(recordId), runStatus: endedAs, + }); + } catch (err: any) { + logger?.error?.( + `[approvals] the approval of ${object}/${String(recordId)} was not put back after step '${node.id}' refused ` + + `to open on its ended run '${String(runId)}': the record keeps the status its last decision wrote and ` + + 'looks decided, and no sweep revisits it. Recall or resubmit the approval on the record.', + { node: node.id, run: String(runId), error: err?.message ?? String(err) }, + ); + return { success: false, error: `${refusal} The approval could not be put back: ${err?.message ?? String(err)}` }; + } + return { success: false, error: refusal }; } // [ADR-0162 Execution item 7] The run's root run and record run, diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 5bf6e1b4bed..21ed327e9e5 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -12788,6 +12788,72 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega }); } + /** + * [#38985, seat ruling 7338562363] An approval step refused to open on a run + * that had already ended while another branch of it went on (the approval + * node's `runEndedAs`): put the record where the dead-run sweep puts an + * approval whose run died ({@link abandonForDeadRun}), without the request + * that sweep acts on, since the step opened none. Called once, by the node, + * on that refusal. + * + * It reads the approval's latest request on this run and its record, and + * writes the abandon path's steps against it: the audit `recall` row + * (nobody did this, so no actor), the status mirror `recalled` and the + * earlier marks cleared. ⛔ No request row is written: the latest request's + * decision stays as its approver recorded it. + * + * Nothing is written, and the answer says why, where: + * - `judged`: the approval is stamped and its object closes on its + * approval field ({@link holdsBackDecision}). The decision was held back + * and the fan-out judge (the door, else the reconciler) puts the record + * back, so writing here would put it back twice; + * - `open`: the latest request is still pending or already closed by a + * recall or a cancel: the dead-run sweep, or that act, owns it; + * - `none`: the run opened no request on the record (the refused step + * would have been the approval's first): nothing of an approval to undo. + */ + async abandonAtRefusedStep(input: { + runId: string; nodeId: string; object: string; recordId: string; runStatus: string; + }): Promise<'abandoned' | 'judged' | 'open' | 'none'> { + const rows = await this.engine.find('sys_approval_request', { + where: { flow_run_id: input.runId, object_name: input.object, record_id: input.recordId }, + orderBy: [{ field: 'created_at', order: 'desc' }], limit: 1, context: SYSTEM_CTX, + }); + const latest = Array.isArray(rows) ? rows[0] : undefined; + if (!latest) return 'none'; + if (latest.status !== 'approved' && latest.status !== 'rejected') return 'open'; + const config = parseJson( + latest.node_config_json, { approvers: [], behavior: 'first_response' } as any, + ); + if (config.approvalStatusField && this.holdsBackDecision(latest, config.approvalStatusField)) return 'judged'; + + const org = latest.organization_id ?? null; + const now = this.clock.now().toISOString(); + await this.engine.insert('sys_approval_action', await this.actionRow(latest, { + id: uid('aact'), request_id: latest.id, organization_id: org, + step_name: input.nodeId, step_index: 0, action: 'recall', + // ADR-0118 D1: no person did this, as in `abandonForDeadRun`. + actor_id: null, + comment: `owning flow run ${input.runId} is ${input.runStatus}: step '${input.nodeId}' opened no request, ` + + 'so the approval was abandoned and the record put back', + created_at: now, + }), { context: SYSTEM_CTX }); + if (config.approvalStatusField) { + // As the sweep: no human did this, and a field whose options do not + // declare `recalled` goes back to its value at submit (#24577). + await this.mirrorStatusField( + latest.object_name, latest.record_id, config.approvalStatusField, 'recalled', null, org, + { payloadJson: latest.payload_json }, { request: latest, step: latest.current_step ?? null }, + ); + } + await this.clearEarlierMarks(latest); + this.logger?.info?.('[approvals] an approval step on an ended run opened no request: the approval was abandoned', { + request: latest.id, run: input.runId, runStatus: input.runStatus, node: input.nodeId, + object: latest.object_name, record: latest.record_id, + }); + return 'abandoned'; + } + /** Execute the configured escalation action for one overdue request. */ private async escalateRequest(raw: any, esc: any): Promise { const action: string = esc.action ?? 'notify'; From 99d3d3bef10fb914ba7c621681399f280355c457 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 07:49:50 +0000 Subject: [PATCH 10/17] chore(changeset): recalled on every object kind, the new service method declared, a fault edge taken on refusal Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- .changeset/38985-ended-run-approval-step.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/.changeset/38985-ended-run-approval-step.md b/.changeset/38985-ended-run-approval-step.md index c80162f7000..af5c159dfa0 100644 --- a/.changeset/38985-ended-run-approval-step.md +++ b/.changeset/38985-ended-run-approval-step.md @@ -7,10 +7,15 @@ fix(plugin-approvals): an approval step opens no request on a run that has alrea Clause-②: yes (widening) Metadata-protocol: none -The widening: the exported `ApprovalAutomationSurface` gains an optional member, `getRun?: ApprovalResumeSurface['getRun']`, the run log read the approval step makes before it opens a request; a host that passes an engine without it opens the step as before. +The widening, two additions: the exported `ApprovalAutomationSurface` gains an optional member, `getRun?: ApprovalResumeSurface['getRun']`, the run log read the approval step makes before it opens a request (a host that passes an engine without it opens the step as before); and the exported `ApprovalService` gains a public method, `abandonAtRefusedStep({ runId, nodeId, object, recordId, runStatus })`, which the approval step calls once when it refuses, described below. It is meant for the approval step only. When a flow's node fans out to branches that run together and one branch fails, the run ends while the other branches keep going. A branch that reached an approval step after that still opened a request there: the step's approver was notified and asked to decide for a run that can never resume, and the record was held `pending` until the dead-run sweep recalled the request (every 5 minutes by default, and never on a host with no job service). -The approval step now reads its run's log before it opens a request. Where the run has already ended (completed, failed, cancelled, timed out, refused or missed) and the log shows a step completed after that end, so another branch went on to this step, it opens no request, sends no notice and leaves nothing pending. The step is logged as failed with a sentence naming the run and how it ended; the run keeps the status and error it ended with. The record's outcome is the one the approval plugin gives a fan-out where one branch fails: abandoned, never approved. +The approval step now reads its run's log before it opens a request. Where the run has already ended (completed, failed, cancelled, timed out, refused or missed) and the log shows a step completed after that end, so another branch went on to this step, it opens no request, sends no notice and leaves nothing pending. The step is logged as failed with a sentence naming the run and how it ended; the run keeps the status and error it ended with. Because the step fails, an authored `fault` out-edge on it is taken, on the run that has already ended. + +The record then ends `recalled` (or its value at submit, where its options do not declare `recalled`) on every object, abandoned and never approved, and the approver of the next step is never asked: + +- On an object that closes on its approval field, the decision before the fan-out was held back, and the plugin's fan-out judge puts the record back, through the door or the reconciler. The refusal writes nothing more there. +- On any other object, the decision before the fan-out was already written to the field (`approved`, say), and no judge runs. The refusal puts the record back itself, as the dead-run sweep does for an approval whose run died: one `recall` row with no actor on the approval's latest request, naming the run, how it ended and the step that opened nothing, then the status field set to `recalled`. That latest request keeps the decision its approver recorded; no request row is written. A run that is still running, or still being resumed onto the step, opens it as before. So does a run that stranded and was restored and is now resumed again: its log still reads the end it stranded with, but nothing logged after it. A run whose status cannot be read also opens the step: an unreadable run is not taken for an ended one. Where a branch reaches the step before it has logged any step past the run's end (the step is the first node after the fan-out and the failure landed first), the step still opens, and the dead-run sweep recalls the request as before. From f5ba015f519ebf8d978f004aada2969853c32c58 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 07:57:43 +0000 Subject: [PATCH 11/17] chore(audit): regenerate the plugin-approvals tenant-audit census for the refused-step audit row Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- .../plugins/plugin-approvals.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-approvals.md b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-approvals.md index bcaeb4fd4f9..404ea6706bc 100644 --- a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-approvals.md +++ b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-approvals.md @@ -14,24 +14,24 @@ a row or a number here — fix the code, or the census, and regenerate. | Measure | Value | |---|---:| -| Write call sites | 51 | -| Object name statically decidable | 49 | +| Write call sites | 52 | +| Object name statically decidable | 50 | | Object name chosen at run time | 2 | -| Object name spelled inline | 47 | +| Object name spelled inline | 48 | | Object name spelled through a `const` | 2 | | Object name is an `object: string` parameter | 1 | | Object name is some other run-time expression | 1 | -| Against a tenancy-enabled object | 49 | +| Against a tenancy-enabled object | 50 | | Against an object declaring tenancy off | 0 | -| Threading a tenant context | 51 | +| Threading a tenant context | 52 | | Provably carrying none (options read, no context key) | 0 | | …and decidably tenancy-enabled | 0 | | Options argument unreadable | 0 | | …and decidably tenancy-enabled | 0 | -| Threading a decidably elevated (`isSystem`) context | 49 | +| Threading a decidably elevated (`isSystem`) context | 50 | | Threading a decidably non-elevated context | 0 | | Threading a context of undecidable elevation | 2 | -| Receiver carried a readable engine type | 51 | +| Receiver carried a readable engine type | 52 | | Receiver erased, placed by the object NAME | 0 | | Receiver erased, placed by an `object: string` PARAMETER | 0 | | Receiver erased, placed by an `UNTYPED_RECEIVERS` row | 0 | @@ -50,7 +50,7 @@ a row or a number here — fix the code, or the census, and regenerate. | `packages/plugins/plugin-approvals/src/action-slot-backfill.ts` | `update` | `sys_approval_action` | enabled | elevated | 2 | | `packages/plugins/plugin-approvals/src/approval-activity-feed.ts` | `insert` | `sys_activity` | enabled | elevated | 1 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `update` | `object` | undecidable | context, elevation undecidable | 1 | -| `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_action` | enabled | elevated | 20 | +| `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_action` | enabled | elevated | 21 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `delete` | `sys_approval_approver` | enabled | elevated | 2 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_approver` | enabled | elevated | 2 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_request` | enabled | elevated | 1 | From a52afebed59e142f9095621a8919867d8a3031a9 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 07:59:48 +0000 Subject: [PATCH 12/17] fix(plugin-approvals): the approval node's logger declares warn, the fallback a failed put-back reports through Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- .../src/approval-node-ended-run-38985.test.ts | 16 ++++++++++++++++ .../plugin-approvals/src/approval-node.ts | 7 +++++-- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/packages/plugins/plugin-approvals/src/approval-node-ended-run-38985.test.ts b/packages/plugins/plugin-approvals/src/approval-node-ended-run-38985.test.ts index ebd33b34c90..74a4166735a 100644 --- a/packages/plugins/plugin-approvals/src/approval-node-ended-run-38985.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-node-ended-run-38985.test.ts @@ -235,6 +235,22 @@ describe('[#38985] an approval step opens no request on a run that has already e } } + it('a put-back that fails is said, on the refused step\'s own log line: the record keeps the last decision\'s value', async () => { + (svc as any).abandonAtRefusedStep = async () => { throw new Error('store down'); }; + await start('fork_fail_side', 'm_fail', 'crm_memo'); + failNote(); + await decideFirst('m_fail'); + await loggedTo('m_fail', 'second'); + await sleep(50); + const runId = String((await requestsOn('m_fail'))[0].record_run_id); + const second = (await automation.getRun(runId) as any).steps.find((x: any) => x.nodeId === 'second'); + + expect(second.status).toBe('failure'); + expect(JSON.stringify(second.error)).toContain('The approval could not be put back: store down'); + expect(await steps('m_fail')).toEqual(['first:approved']); + expect(await field('m_fail')).toBe('approved'); + }); + it('control: a fan-out run still running opens `second` as before', async () => { await start('fork_fail_side', 'i_live'); during.set('note', () => sleep(30)); diff --git a/packages/plugins/plugin-approvals/src/approval-node.ts b/packages/plugins/plugin-approvals/src/approval-node.ts index 443a2674155..fa2663c8be5 100644 --- a/packages/plugins/plugin-approvals/src/approval-node.ts +++ b/packages/plugins/plugin-approvals/src/approval-node.ts @@ -81,7 +81,8 @@ export interface ApprovalAutomationSurface { interface MinimalLogger { info?: (msg: any, ...rest: any[]) => void; - warn?: (msg: any, ...rest: any[]) => void; + /** Required: where a report goes on a sink with no `error` (`check:optional-error-sink`). */ + warn: (msg: any, ...rest: any[]) => void; error?: (msg: any, ...rest: any[]) => void; } @@ -228,7 +229,9 @@ export function registerApprovalNode( runId: String(runId), nodeId: node.id, object, recordId: String(recordId), runStatus: endedAs, }); } catch (err: any) { - logger?.error?.( + // A sink with no `error` reports at `warn`, its declared alternative. + (logger?.error ?? logger?.warn)?.call( + logger, `[approvals] the approval of ${object}/${String(recordId)} was not put back after step '${node.id}' refused ` + `to open on its ended run '${String(runId)}': the record keeps the status its last decision wrote and ` + 'looks decided, and no sweep revisits it. Recall or resubmit the approval on the record.', From 1f705eca35e502c90d5b21cff271095f58ba69a1 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 08:48:03 +0000 Subject: [PATCH 13/17] test(approvals): a refused step reaches the approval a child run opened (red, #38985 S3) The first approval sits in a subflow body; the parent then fans out and a late branch refuses. The decided request carries the child's run id, so the put-back finds none and the record stays approved. Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- .../src/approval-node-ended-run-38985.test.ts | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/packages/plugins/plugin-approvals/src/approval-node-ended-run-38985.test.ts b/packages/plugins/plugin-approvals/src/approval-node-ended-run-38985.test.ts index 74a4166735a..f3eb9a547ff 100644 --- a/packages/plugins/plugin-approvals/src/approval-node-ended-run-38985.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-node-ended-run-38985.test.ts @@ -85,6 +85,12 @@ const FLOWS = [ flow('fork_fail_side', [step('first', 'approver'), mark('fork'), sub('mid', 'child_slow'), mark('note'), step('second', 'approver2')], [edge('start', 'first'), ...decided('first', 'fork'), edge('fork', 'mid'), edge('fork', 'note'), edge('note', 'end'), edge('mid', 'second'), ...decided('second', 'end')]), + // [#38985 S3] The approval's first step inside a child run: `first`, alone in a subflow body. + flow('child_first', [step('first', 'approver')], [edge('start', 'first'), ...decided('first', 'end')]), + // The card's fan-out, after a `first` the child run opened and decided. + flow('sub_fork_fail_side', [sub('ask', 'child_first'), mark('fork'), sub('mid', 'child_slow'), mark('note'), step('second', 'approver2')], + [edge('start', 'ask'), edge('ask', 'fork'), + edge('fork', 'mid'), edge('fork', 'note'), edge('note', 'end'), edge('mid', 'second'), ...decided('second', 'end')]), // The control with no fan-out: `first`, then `second`. flow('chain', [step('first', 'approver'), step('second', 'approver2')], [edge('start', 'first'), ...decided('first', 'second'), ...decided('second', 'end')]), @@ -235,6 +241,32 @@ describe('[#38985] an approval step opens no request on a run that has already e } } + it('the decided request was opened by a child run: the step reaches it, and the record ends recalled', async () => { + await start('sub_fork_fail_side', 'm_child', 'crm_memo'); + expect(await steps('m_child')).toEqual(['first:pending']); + failNote(); + await decideFirst('m_child'); + const firstRaw = (await requestsOn('m_child'))[0]; + const first = decidedRow(firstRaw); + const runId = String(firstRaw.root_run_id); + expect(first.status).toBe('approved'); + expect(String(firstRaw.flow_run_id), 'opened by the child run, not the run that refuses').not.toBe(runId); + await loggedTo('m_child', 'second'); + await sleep(50); + const run: any = await automation.getRun(runId); + + expect(run.status).toBe('failed'); + expect(await steps('m_child'), 'no request row for `second`').toEqual(['first:approved']); + expect(decidedRow((await requestsOn('m_child'))[0])).toEqual(first); + expect(told('approver2')).toBe(0); + expect(await field('m_child'), 'abandoned, never approved').toBe('recalled'); + expect(await svc.releaseDeadRunRequests()).toEqual({ scanned: 0, released: 0 }); + expect((await timeline(String(first.id))).filter((t) => t.action === 'recall')).toEqual([{ + action: 'recall', actor: null, + comment: `owning flow run ${runId} is failed: step 'second' opened no request, so the approval was abandoned and the record put back`, + }]); + }); + it('a put-back that fails is said, on the refused step\'s own log line: the record keeps the last decision\'s value', async () => { (svc as any).abandonAtRefusedStep = async () => { throw new Error('store down'); }; await start('fork_fail_side', 'm_fail', 'crm_memo'); From e318c220c08e2779a4d9f2843b6b88d665cd83ba Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 08:49:22 +0000 Subject: [PATCH 14/17] fix(approvals): a refused step reaches the approval its child runs opened (#38985 S3, S2, N5) The put-back reads the latest request whose flow_run_id or root_run_id is the refusing run, in one keyed read, so a first approval inside a subflow body is found. The node's logger type is back to its main shape (info?, warn?): a failed put-back logs at warn, else info, and always rides on the step's error. The recall row names the request's own step, as the sweep's. Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- .../src/approval-node-ended-run-38985.test.ts | 5 +++ .../plugin-approvals/src/approval-node.ts | 13 ++++--- .../plugin-approvals/src/approval-service.ts | 37 ++++++++++++++----- 3 files changed, 41 insertions(+), 14 deletions(-) diff --git a/packages/plugins/plugin-approvals/src/approval-node-ended-run-38985.test.ts b/packages/plugins/plugin-approvals/src/approval-node-ended-run-38985.test.ts index f3eb9a547ff..d37e49b67dd 100644 --- a/packages/plugins/plugin-approvals/src/approval-node-ended-run-38985.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-node-ended-run-38985.test.ts @@ -215,6 +215,8 @@ describe('[#38985] an approval step opens no request on a run that has already e await sleep(50); const runId = String((await requestsOn(id))[0].record_run_id); const run: any = await automation.getRun(runId); + const { flow_run_id, root_run_id } = (await requestsOn(id))[0]; + expect([flow_run_id, root_run_id], 'a top-level run is its own root: its request carries its id in both').toEqual([runId, runId]); expect(run.status).toBe('failed'); expect(run.error, 'the refusal does not replace how the run ended').toBe('note failed'); @@ -251,6 +253,7 @@ describe('[#38985] an approval step opens no request on a run that has already e const runId = String(firstRaw.root_run_id); expect(first.status).toBe('approved'); expect(String(firstRaw.flow_run_id), 'opened by the child run, not the run that refuses').not.toBe(runId); + expect(String(firstRaw.record_run_id), 'a subflow body carries its parent\'s record run').toBe(runId); await loggedTo('m_child', 'second'); await sleep(50); const run: any = await automation.getRun(runId); @@ -265,6 +268,8 @@ describe('[#38985] an approval step opens no request on a run that has already e action: 'recall', actor: null, comment: `owning flow run ${runId} is failed: step 'second' opened no request, so the approval was abandoned and the record put back`, }]); + const row = (await ql.find('sys_approval_action', { where: { request_id: first.id, action: 'recall' }, context: SYS }) as any[])[0]; + expect(row.step_name, 'the row names the request\'s own step, as the sweep\'s; the refused one is in the comment').toBe('first'); }); it('a put-back that fails is said, on the refused step\'s own log line: the record keeps the last decision\'s value', async () => { diff --git a/packages/plugins/plugin-approvals/src/approval-node.ts b/packages/plugins/plugin-approvals/src/approval-node.ts index fa2663c8be5..46a1de7b3f2 100644 --- a/packages/plugins/plugin-approvals/src/approval-node.ts +++ b/packages/plugins/plugin-approvals/src/approval-node.ts @@ -81,9 +81,7 @@ export interface ApprovalAutomationSurface { interface MinimalLogger { info?: (msg: any, ...rest: any[]) => void; - /** Required: where a report goes on a sink with no `error` (`check:optional-error-sink`). */ - warn: (msg: any, ...rest: any[]) => void; - error?: (msg: any, ...rest: any[]) => void; + warn?: (msg: any, ...rest: any[]) => void; } const SYSTEM_CTX: ExecutionContext = { isSystem: true, positions: [], permissions: [] }; @@ -224,13 +222,18 @@ export function registerApprovalNode( // sweep would put it, on every object: no request is left for that // sweep to find, and on an object the fan-out judge does not judge the // field still holds the last decision's value. + // + // A put-back that fails is said on the step's own error, the channel + // every run carries whatever logger the host passed: the run's log + // entry keeps it on the refused step. The log line beside it goes to + // `warn`, else `info`, when the host's sink has one; a sink with + // neither still leaves the step's error. try { await service.abandonAtRefusedStep({ runId: String(runId), nodeId: node.id, object, recordId: String(recordId), runStatus: endedAs, }); } catch (err: any) { - // A sink with no `error` reports at `warn`, its declared alternative. - (logger?.error ?? logger?.warn)?.call( + (logger?.warn ?? logger?.info)?.call( logger, `[approvals] the approval of ${object}/${String(recordId)} was not put back after step '${node.id}' refused ` + `to open on its ended run '${String(runId)}': the record keeps the status its last decision wrote and ` diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 21ed327e9e5..bed10859d43 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -12796,11 +12796,23 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * that sweep acts on, since the step opened none. Called once, by the node, * on that refusal. * - * It reads the approval's latest request on this run and its record, and - * writes the abandon path's steps against it: the audit `recall` row - * (nobody did this, so no actor), the status mirror `recalled` and the - * earlier marks cleared. ⛔ No request row is written: the latest request's - * decision stays as its approver recorded it. + * It reads the approval's latest request on the record that this run or + * one of its child runs opened, and writes the abandon path's steps against + * it: the audit `recall` row (nobody did this, so no actor; its step is the + * request's own node, as the sweep's, and the refused step is named in its + * comment), the status mirror `recalled` and the earlier marks cleared. + * ⛔ No request row is written: the latest request's decision stays as its + * approver recorded it. + * + * [#38985 S3] "This run or one of its child runs" is one keyed read: a + * request whose `flow_run_id` is the run (the run opened it), or whose + * `root_run_id` is the run (a run of the tree the run is the root of + * opened it: a `subflow` body or a `map` item). A top-level run is its own + * root, so a request it opened carries its id in both columns; a child + * run's request carries the child's id in `flow_run_id` and the top-level + * run's in `root_run_id` (ADR-0162 Execution item 7, `rootRunOf`). A + * request opened by an engine that hands no root run leaves `root_run_id` + * empty and is found by `flow_run_id` alone. * * Nothing is written, and the answer says why, where: * - `judged`: the approval is stamped and its object closes on its @@ -12809,14 +12821,20 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * back, so writing here would put it back twice; * - `open`: the latest request is still pending or already closed by a * recall or a cancel: the dead-run sweep, or that act, owns it; - * - `none`: the run opened no request on the record (the refused step - * would have been the approval's first): nothing of an approval to undo. + * - `none`: neither the run nor any run of the tree it is the root of + * opened a request on the record (the refused step would have been the + * approval's first): nothing of an approval to undo. A refusing run that + * is itself a child reaches its own requests only, not those of runs + * beside it under the same root. */ async abandonAtRefusedStep(input: { runId: string; nodeId: string; object: string; recordId: string; runStatus: string; }): Promise<'abandoned' | 'judged' | 'open' | 'none'> { const rows = await this.engine.find('sys_approval_request', { - where: { flow_run_id: input.runId, object_name: input.object, record_id: input.recordId }, + where: { + object_name: input.object, record_id: input.recordId, + $or: [{ flow_run_id: input.runId }, { root_run_id: input.runId }], + }, orderBy: [{ field: 'created_at', order: 'desc' }], limit: 1, context: SYSTEM_CTX, }); const latest = Array.isArray(rows) ? rows[0] : undefined; @@ -12831,7 +12849,8 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const now = this.clock.now().toISOString(); await this.engine.insert('sys_approval_action', await this.actionRow(latest, { id: uid('aact'), request_id: latest.id, organization_id: org, - step_name: input.nodeId, step_index: 0, action: 'recall', + // The request's own node, as the sweep's row: `actionRow` labels the step from the request. + step_name: latest.flow_node_id ?? latest.current_step ?? null, step_index: 0, action: 'recall', // ADR-0118 D1: no person did this, as in `abandonForDeadRun`. actor_id: null, comment: `owning flow run ${input.runId} is ${input.runStatus}: step '${input.nodeId}' opened no request, ` From 6a1f86f9f4c810a5a5f734ccafe1f6a8d0b6e985 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 08:49:34 +0000 Subject: [PATCH 15/17] docs(changeset): the put-back reaches child runs' requests, and a failed one is on the step's error (#38985) Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- .changeset/38985-ended-run-approval-step.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/38985-ended-run-approval-step.md b/.changeset/38985-ended-run-approval-step.md index af5c159dfa0..e3900f84c4a 100644 --- a/.changeset/38985-ended-run-approval-step.md +++ b/.changeset/38985-ended-run-approval-step.md @@ -16,6 +16,6 @@ The approval step now reads its run's log before it opens a request. Where the r The record then ends `recalled` (or its value at submit, where its options do not declare `recalled`) on every object, abandoned and never approved, and the approver of the next step is never asked: - On an object that closes on its approval field, the decision before the fan-out was held back, and the plugin's fan-out judge puts the record back, through the door or the reconciler. The refusal writes nothing more there. -- On any other object, the decision before the fan-out was already written to the field (`approved`, say), and no judge runs. The refusal puts the record back itself, as the dead-run sweep does for an approval whose run died: one `recall` row with no actor on the approval's latest request, naming the run, how it ended and the step that opened nothing, then the status field set to `recalled`. That latest request keeps the decision its approver recorded; no request row is written. +- On any other object, the decision before the fan-out was already written to the field (`approved`, say), and no judge runs. The refusal puts the record back itself, as the dead-run sweep does for an approval whose run died: one `recall` row with no actor on the approval's latest request on the record, whether the run itself or one of its child runs (a `subflow` body, a `map` item) opened it, naming the run, how it ended and the step that opened nothing, then the status field set to `recalled`. That latest request keeps the decision its approver recorded; no request row is written. If the put-back fails, the step's error says so, and the record keeps the value its last decision wrote. A run that is still running, or still being resumed onto the step, opens it as before. So does a run that stranded and was restored and is now resumed again: its log still reads the end it stranded with, but nothing logged after it. A run whose status cannot be read also opens the step: an unreadable run is not taken for an ended one. Where a branch reaches the step before it has logged any step past the run's end (the step is the first node after the fan-out and the failure landed first), the step still opens, and the dead-run sweep recalls the request as before. From 813e8043bd14be9d031716319ab0ca5abaf02fbf Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 09:41:59 +0000 Subject: [PATCH 16/17] test(approvals): a refusing child run reaches its parent's and siblings' approval (red, #38985 S4) A subflow body fans out and fails; its late approval step refuses. The decided request was opened by the parent, or by a sibling child, so neither lookup arm matches the child's id and the record stays approved. A third cell pins that the put-back answers open, not a write, while the tree's newest request is pending. Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- .../src/approval-node-ended-run-38985.test.ts | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/packages/plugins/plugin-approvals/src/approval-node-ended-run-38985.test.ts b/packages/plugins/plugin-approvals/src/approval-node-ended-run-38985.test.ts index d37e49b67dd..c9827728393 100644 --- a/packages/plugins/plugin-approvals/src/approval-node-ended-run-38985.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-node-ended-run-38985.test.ts @@ -91,6 +91,15 @@ const FLOWS = [ flow('sub_fork_fail_side', [sub('ask', 'child_first'), mark('fork'), sub('mid', 'child_slow'), mark('note'), step('second', 'approver2')], [edge('start', 'ask'), edge('ask', 'fork'), edge('fork', 'mid'), edge('fork', 'note'), edge('note', 'end'), edge('mid', 'second'), ...decided('second', 'end')]), + // [#38985 S4] The fan-out inside a child run: `fork` in a subflow body, `note` fails, `second` comes late. + flow('child_fork_fail', [mark('fork'), sub('mid', 'child_slow'), mark('note'), step('second', 'approver2')], + [edge('start', 'fork'), edge('fork', 'mid'), edge('fork', 'note'), edge('note', 'end'), edge('mid', 'second'), ...decided('second', 'end')]), + // The parent decides `first` itself, then calls that child. + flow('parent_then_child_fork', [step('first', 'approver'), sub('inner', 'child_fork_fail')], + [edge('start', 'first'), ...decided('first', 'inner'), edge('inner', 'end')]), + // One child decides `first`, a sibling child then fans out. + flow('sibling_then_child_fork', [sub('ask', 'child_first'), sub('inner', 'child_fork_fail')], + [edge('start', 'ask'), edge('ask', 'inner'), edge('inner', 'end')]), // The control with no fan-out: `first`, then `second`. flow('chain', [step('first', 'approver'), step('second', 'approver2')], [edge('start', 'first'), ...decided('first', 'second'), ...decided('second', 'end')]), @@ -272,6 +281,63 @@ describe('[#38985] an approval step opens no request on a run that has already e expect(row.step_name, 'the row names the request\'s own step, as the sweep\'s; the refused one is in the comment').toBe('first'); }); + /** The child run of `child_fork_fail` that started last, once its late `second` has run. */ + const refusedChild = async () => { + for (let i = 0; i < 100; i++) { + const runs: any[] = await automation.listRuns('child_fork_fail'); + const child = runs.find((r) => r?.steps?.some((x: any) => x.nodeId === 'second')); + if (child) return child; + await sleep(20); + } + throw new Error('the child run never logged `second`'); + }; + for (const [flowName, who] of [ + ['parent_then_child_fork', 'the parent opened it'], + ['sibling_then_child_fork', 'a sibling child opened it'], + ] as const) { + it(`the refusing run is a child, and the decided request is not its own (${who}): the step reaches it, and the record ends recalled`, async () => { + const id = `m_${flowName}`; + await start(flowName, id, 'crm_memo'); + expect(await steps(id)).toEqual(['first:pending']); + failNote(); + await decideFirst(id); + const firstRaw = (await requestsOn(id))[0]; + const first = decidedRow(firstRaw); + expect(first.status).toBe('approved'); + const child = await refusedChild(); + await sleep(50); + const childId = String(child.id ?? child.runId); + const rootId = String(firstRaw.root_run_id); + expect(childId, 'the run that refuses is not the root').not.toBe(rootId); + expect(String(firstRaw.flow_run_id), 'nor did it open the decided request').not.toBe(childId); + + expect((await automation.getRun(childId) as any)?.status).toBe('failed'); + expect(await steps(id), 'no request row for `second`').toEqual(['first:approved']); + expect(decidedRow((await requestsOn(id))[0])).toEqual(first); + expect(told('approver2')).toBe(0); + expect(await field(id), 'abandoned, never approved').toBe('recalled'); + expect((await timeline(String(first.id))).filter((t) => t.action === 'recall')).toEqual([{ + action: 'recall', actor: null, + comment: `owning flow run ${childId} is failed: step 'second' opened no request, so the approval was abandoned and the record put back`, + }]); + }); + } + + it('the put-back never writes over a live request: the newest request of the tree is pending, so it answers open and writes nothing', async () => { + await start('chain', 'm_live', 'crm_memo'); + await decideFirst('m_live'); + const [firstRaw, secondRaw] = await requestsOn('m_live'); + expect([firstRaw.status, secondRaw.status]).toEqual(['approved', 'pending']); + const rootId = String(secondRaw.root_run_id); + + const answer = await svc.abandonAtRefusedStep({ + runId: 'run_child_elsewhere', rootRunId: rootId, nodeId: 'late', object: 'crm_memo', recordId: 'm_live', runStatus: 'failed', + }); + expect(answer, 'the newest is the pending `second`, not the older decided `first`').toBe('open'); + expect(await field('m_live')).toBe('pending'); + expect((await timeline(String(firstRaw.id))).filter((t) => t.action === 'recall')).toEqual([]); + }); + it('a put-back that fails is said, on the refused step\'s own log line: the record keeps the last decision\'s value', async () => { (svc as any).abandonAtRefusedStep = async () => { throw new Error('store down'); }; await start('fork_fail_side', 'm_fail', 'crm_memo'); From ad7b8cc460ef68b8e4589c2281119d6d9bd009af Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 09:42:53 +0000 Subject: [PATCH 17/17] fix(approvals): a refusing child run reaches the approval its whole tree opened (#38985 S4) The approval step hands its run's root (rootRunOf) to abandonAtRefusedStep, whose input gains an optional rootRunId; the read's second arm compares root_run_id with that root, so a child run that refuses reaches its parent's and its siblings' requests. Still one keyed read; without a root the run is its own root, as before. The changeset names the new input field and the tree. Claude-Session: https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ Co-authored-by: Claude --- .changeset/38985-ended-run-approval-step.md | 4 +- .../plugin-approvals/src/approval-node.ts | 2 + .../plugin-approvals/src/approval-service.ts | 37 ++++++++++++------- 3 files changed, 27 insertions(+), 16 deletions(-) diff --git a/.changeset/38985-ended-run-approval-step.md b/.changeset/38985-ended-run-approval-step.md index e3900f84c4a..c1a63c7c415 100644 --- a/.changeset/38985-ended-run-approval-step.md +++ b/.changeset/38985-ended-run-approval-step.md @@ -7,7 +7,7 @@ fix(plugin-approvals): an approval step opens no request on a run that has alrea Clause-②: yes (widening) Metadata-protocol: none -The widening, two additions: the exported `ApprovalAutomationSurface` gains an optional member, `getRun?: ApprovalResumeSurface['getRun']`, the run log read the approval step makes before it opens a request (a host that passes an engine without it opens the step as before); and the exported `ApprovalService` gains a public method, `abandonAtRefusedStep({ runId, nodeId, object, recordId, runStatus })`, which the approval step calls once when it refuses, described below. It is meant for the approval step only. +The widening, two additions: the exported `ApprovalAutomationSurface` gains an optional member, `getRun?: ApprovalResumeSurface['getRun']`, the run log read the approval step makes before it opens a request (a host that passes an engine without it opens the step as before); and the exported `ApprovalService` gains a public method, `abandonAtRefusedStep({ runId, nodeId, object, recordId, runStatus, rootRunId? })`, which the approval step calls once when it refuses, described below. It is meant for the approval step only. When a flow's node fans out to branches that run together and one branch fails, the run ends while the other branches keep going. A branch that reached an approval step after that still opened a request there: the step's approver was notified and asked to decide for a run that can never resume, and the record was held `pending` until the dead-run sweep recalled the request (every 5 minutes by default, and never on a host with no job service). @@ -16,6 +16,6 @@ The approval step now reads its run's log before it opens a request. Where the r The record then ends `recalled` (or its value at submit, where its options do not declare `recalled`) on every object, abandoned and never approved, and the approver of the next step is never asked: - On an object that closes on its approval field, the decision before the fan-out was held back, and the plugin's fan-out judge puts the record back, through the door or the reconciler. The refusal writes nothing more there. -- On any other object, the decision before the fan-out was already written to the field (`approved`, say), and no judge runs. The refusal puts the record back itself, as the dead-run sweep does for an approval whose run died: one `recall` row with no actor on the approval's latest request on the record, whether the run itself or one of its child runs (a `subflow` body, a `map` item) opened it, naming the run, how it ended and the step that opened nothing, then the status field set to `recalled`. That latest request keeps the decision its approver recorded; no request row is written. If the put-back fails, the step's error says so, and the record keeps the value its last decision wrote. +- On any other object, the decision before the fan-out was already written to the field (`approved`, say), and no judge runs. The refusal puts the record back itself, as the dead-run sweep does for an approval whose run died: one `recall` row with no actor on the approval's latest request on the record, whether the run itself or any run of its tree opened it (the root run, a `subflow` body or a `map` item, so also the parent or a sibling of a run that is itself a child), naming the run, how it ended and the step that opened nothing, then the status field set to `recalled`. That latest request keeps the decision its approver recorded; no request row is written. If the put-back fails, the step's error says so, and the record keeps the value its last decision wrote. A run that is still running, or still being resumed onto the step, opens it as before. So does a run that stranded and was restored and is now resumed again: its log still reads the end it stranded with, but nothing logged after it. A run whose status cannot be read also opens the step: an unreadable run is not taken for an ended one. Where a branch reaches the step before it has logged any step past the run's end (the step is the first node after the fan-out and the failure landed first), the step still opens, and the dead-run sweep recalls the request as before. diff --git a/packages/plugins/plugin-approvals/src/approval-node.ts b/packages/plugins/plugin-approvals/src/approval-node.ts index 46a1de7b3f2..1382168ba23 100644 --- a/packages/plugins/plugin-approvals/src/approval-node.ts +++ b/packages/plugins/plugin-approvals/src/approval-node.ts @@ -231,6 +231,8 @@ export function registerApprovalNode( try { await service.abandonAtRefusedStep({ runId: String(runId), nodeId: node.id, object, recordId: String(recordId), runStatus: endedAs, + // The approval is the run's whole tree: its root's request, a parent's or a sibling child's. + rootRunId: automation.rootRunOf?.(context)?.runId ?? null, }); } catch (err: any) { (logger?.warn ?? logger?.info)?.call( diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index bed10859d43..4874e040080 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -12804,15 +12804,20 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * ⛔ No request row is written: the latest request's decision stays as its * approver recorded it. * - * [#38985 S3] "This run or one of its child runs" is one keyed read: a - * request whose `flow_run_id` is the run (the run opened it), or whose - * `root_run_id` is the run (a run of the tree the run is the root of - * opened it: a `subflow` body or a `map` item). A top-level run is its own - * root, so a request it opened carries its id in both columns; a child + * [#38985 S3, S4] "Opened by the approval" is one keyed read: a request + * whose `flow_run_id` is the run (the run opened it), or whose + * `root_run_id` is the run's root, `rootRunId` (any run of the run's tree + * opened it: the root itself, a `subflow` body or a `map` item, the + * refusing run's parent and its siblings included). A top-level run is its + * own root, so a request it opened carries its id in both columns; a child * run's request carries the child's id in `flow_run_id` and the top-level - * run's in `root_run_id` (ADR-0162 Execution item 7, `rootRunOf`). A - * request opened by an engine that hands no root run leaves `root_run_id` - * empty and is found by `flow_run_id` alone. + * run's in `root_run_id` (ADR-0162 Execution item 7, `rootRunOf`). Without + * `rootRunId` (an engine that hands no root run, or one that could not + * place the run) the run is taken for its own root. + * + * The newest request of the tree is the one judged: a record holds at most + * one pending request, and none opens while one is pending, so where the + * tree has a pending request it is the newest, and the answer is `open`. * * Nothing is written, and the answer says why, where: * - `judged`: the approval is stamped and its object closes on its @@ -12821,19 +12826,23 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * back, so writing here would put it back twice; * - `open`: the latest request is still pending or already closed by a * recall or a cancel: the dead-run sweep, or that act, owns it; - * - `none`: neither the run nor any run of the tree it is the root of - * opened a request on the record (the refused step would have been the - * approval's first): nothing of an approval to undo. A refusing run that - * is itself a child reaches its own requests only, not those of runs - * beside it under the same root. + * - `none`: no run of the run's tree opened a request on the record + * (the refused step would have been the approval's first): nothing of + * an approval to undo. Outside the read, so also `none`: a request that + * records no root run (`root_run_id` empty: opened by an engine that + * hands none) and that another run than this one opened; and, where the + * run's root is not handed over, a request that another run's root + * names. */ async abandonAtRefusedStep(input: { runId: string; nodeId: string; object: string; recordId: string; runStatus: string; + /** The root run of `runId`'s tree (`rootRunOf`). Absent or `null`: `runId` is taken for its own root. */ + rootRunId?: string | null; }): Promise<'abandoned' | 'judged' | 'open' | 'none'> { const rows = await this.engine.find('sys_approval_request', { where: { object_name: input.object, record_id: input.recordId, - $or: [{ flow_run_id: input.runId }, { root_run_id: input.runId }], + $or: [{ flow_run_id: input.runId }, { root_run_id: input.rootRunId || input.runId }], }, orderBy: [{ field: 'created_at', order: 'desc' }], limit: 1, context: SYSTEM_CTX, });