diff --git a/.changeset/38985-ended-run-approval-step.md b/.changeset/38985-ended-run-approval-step.md new file mode 100644 index 00000000000..c1a63c7c415 --- /dev/null +++ b/.changeset/38985-ended-run-approval-step.md @@ -0,0 +1,21 @@ +--- +'@objectstack/plugin-approvals': patch +--- + +fix(plugin-approvals): an approval step opens no request on a run that has already ended + +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, 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). + +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 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/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 | 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..c9827728393 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-node-ended-run-38985.test.ts @@ -0,0 +1,395 @@ +// 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. + * 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. + * + * 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 })), +}; +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, + 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')]), + // [#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')]), + // [#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')]), +]; + +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, 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); + 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); + }); + + /** 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, 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); + /** 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)); + }; + + 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); + 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'); + 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('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); + 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); + + 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`, + }]); + 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'); + }); + + /** 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'); + 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)); + 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); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/approval-node.ts b/packages/plugins/plugin-approvals/src/approval-node.ts index 4a0ea9a5f43..1382168ba23 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 type { ApprovalRecordRun, ApprovalRootRun, 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. */ @@ -68,6 +70,13 @@ export interface ApprovalAutomationSurface { * {@link rootRunOf} is. */ recordRunOf?(context: unknown): ApprovalRecordRun | undefined; + /** + * [#38985] The run's log entry (`AutomationEngine.getRun`), read for its + * 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?: ApprovalResumeSurface['getRun']; } interface MinimalLogger { @@ -194,6 +203,50 @@ 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, 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 + // 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, + }); + 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. + // + // 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, + // 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( + 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.', + { 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, // 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 +346,60 @@ export function registerApprovalNode( logger?.info?.('[approvals] approval node executor registered'); } +/** + * [#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. + * + * 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 run: Awaited>>; + try { + run = await automation.getRun(runId); + } catch { + return 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; + // `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; +} + +/** 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; +} + /** * [#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 diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 5bf6e1b4bed..4874e040080 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -12788,6 +12788,100 @@ 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 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, 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`). 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 + * 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`: 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.rootRunId || input.runId }], + }, + 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, + // 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, ` + + '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';