diff --git a/.changeset/37218-approval-ended-durable-witness.md b/.changeset/37218-approval-ended-durable-witness.md new file mode 100644 index 00000000000..3c4be13d666 --- /dev/null +++ b/.changeset/37218-approval-ended-durable-witness.md @@ -0,0 +1,20 @@ +--- +'@objectstack/service-automation': patch +'@objectstack/plugin-approvals': patch +'@objectstack/spec': patch +--- + +fix(approvals): "The approval ended here" survives a restart and a re-registration of the flow, and is never served for a body the run did not run + +Clause-②: yes (widening: AutomationEngine gains getRunFlowChecksum and getFlowBodyChecksum; RunRecord gains optional flowChecksum; the exported ApprovalResumeSurface drops the optional getFlowVersionHistory and gains optional getRunFlowChecksum and getFlowBodyChecksum) +Metadata-protocol: none + +A decided approval request's route says where the record's approval went next, and `flow_route.outcome.ended` says the approval ended. It is served only for a run that ran the flow body armed now. That used to be proven from this process's registration history (the newest registration, registered before the run started), so every restart and every re-registration of the flow, a package reload included, dropped the line from every earlier request of that flow. Two narrow cases served it for a body the run did not run: a rollback made before the run started and undone after it, and a replica that registered an edit before another replica started the run on the older body. + +The witness is now the body's content. A run's terminal `sys_automation_run` row carries `flow_checksum`, the content checksum of the body it ran (the identity the metadata history keys a stored flow's versions by), stamped on the run's context where it starts and carried through every pause and resume. The approvals plugin serves `ended` only when that checksum equals the checksum of the body armed now. A restart, another server, or the same content registered again keeps the answer; a body with other content never answers in the run's place. + +- `@objectstack/service-automation`: `AutomationEngine.getRunFlowChecksum(runId)` (a finished run's checksum, read as `getRun` reads it: memory, then terminal row; `undefined` for a run not finished) and `AutomationEngine.getFlowBodyChecksum(flow)`; `RunRecord.flowChecksum`. A run records none when it finished before this release, its body could not be hashed, it was parked before this release and its pause pinned none, it resumed on another body because the one it started on could no longer be found, or it failed after a resume and can still be restored (a strand: its row keeps the pause's pin in `flow_checksum` for the restore, as before, and that pin is never read back as the body the run ran). +- `@objectstack/plugin-approvals`: reads the two; no longer reads `getFlowVersionHistory` (dropped from the exported `ApprovalResumeSurface`). A later step is now a request of the run opened after this one was decided, not merely after it opened: a node that fans out to two approval steps opens two requests of one run side by side, and the sibling is no longer served as where the approval went. +- `@objectstack/spec`: the `ended` sentence on `ApprovalRequestRow.flow_route.outcome` says this. + +Upgrading: a run that finished before this release has no checksum on its row, so its decided requests do not say the approval ended (they already lost the line at the restart the upgrade makes). Runs that finish after it keep the line. diff --git a/content/docs/automation/approvals.mdx b/content/docs/automation/approvals.mdx index 6c5742c1ef4..30a8dba577a 100644 --- a/content/docs/automation/approvals.mdx +++ b/content/docs/automation/approvals.mdx @@ -1260,18 +1260,25 @@ in `outcome`, so its step line can answer "what happened next": } ``` -`step` is the run's latest request opened after this one (a pending one first), -and is absent when none was opened; `status` is that request's status, or this +`step` is the run's latest request opened after this one was decided (a pending +one first), and is absent when none was opened; a request of the same run opened +while this one was still pending (a step that fans out to two approvals) is not +a later step; `status` is that request's status, or this request's own without a `step`; `ended` is `true` only when the record's approval is known to have stopped: the request's run is a root run (an approval inside a `subflow` or a `map` item runs in a child run, whose end is not the approval's), the flow body the run ran holds no `subflow` or `map` node anywhere (a child run files its requests under its own run, so the root run's requests cannot show what it decided), and the run has stopped for good. The -body the run ran is known only while the flow has not been registered again -since the run started: after an edit, a rollback or a restart, older runs are -not judged by today's body, and their requests are not served "ended". `false` -means not known to have stopped, including a run that cannot be read. So on a +body the run ran is known by its content: the run's record keeps the checksum of +the body it ran, and "ended" is served only when the body armed now has the same +checksum. A restart, another server, or the same content registered again keeps +the line; an edit or a rollback to other content does not, and neither does a +run that recorded no checksum: one that finished before runs kept it, whose body +could not be hashed, that was parked before runs kept it and whose pause pinned +none, that resumed on another body because the one it started on could no +longer be found, or that failed after a resume and can still be restored. +`false` means not known to have stopped, including a run that cannot be read. So on a flow that starts a child run, a decided request's line names the later steps of its own run but never says the approval ended. `outcome` is left out when nothing past the request is known: no later request and the approval not known to have diff --git a/packages/plugins/plugin-approvals/src/approval-route.test.ts b/packages/plugins/plugin-approvals/src/approval-route.test.ts index 3f8973f1f4c..8763869bc9a 100644 --- a/packages/plugins/plugin-approvals/src/approval-route.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-route.test.ts @@ -247,3 +247,31 @@ describe('[#35863] flowHostsChildRuns — a flow whose run may file requests und expect(flowHostsChildRuns({})).toBe(false); }); }); + +/** + * `routeOutcome` reads "later" from this request's DECISION (`completed_at`), + * not its opening: a request of the same run opened while this one was still + * pending is a sibling (one node fanning out to two approval steps over + * unconditional edges opens two side by side), not where the approval went + * after this one. The served path over the real engine is the fan-out pin in + * `flow-route.integration.test.ts`. + */ +describe('routeOutcome measures "later" from the decision, not the opening', () => { + const decided = { id: 'a@1', status: 'approved', created_at: at(1), completed_at: at(5) }; + + it('a sibling opened while this request was pending is not where the approval went', () => { + expect(routeOutcome(decided, [row('b', 'pending', at(2))], false, label)).toBeUndefined(); + expect(routeOutcome(decided, [row('b', 'pending', at(2))], true, label)).toEqual({ status: 'approved', ended: true }); + }); + + it('a request opened after the decision is', () => { + expect(routeOutcome(decided, [row('b', 'pending', at(2)), row('c', 'pending', at(6))], false, label)) + .toEqual({ step: { id: 'c', label: 'C' }, status: 'pending', ended: false }); + }); + + it('a row that records no decision time is read from its opening, as before', () => { + const { completed_at: _dropped, ...opened } = decided; + expect(routeOutcome(opened, [row('b', 'pending', at(2))], false, label)) + .toEqual({ step: { id: 'b', label: 'B' }, status: 'pending', ended: false }); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/approval-route.ts b/packages/plugins/plugin-approvals/src/approval-route.ts index dbab7a74fea..d257ea48661 100644 --- a/packages/plugins/plugin-approvals/src/approval-route.ts +++ b/packages/plugins/plugin-approvals/src/approval-route.ts @@ -154,10 +154,18 @@ export function stepsAhead( /** * [#35863] Where the record's approval stands after the decided request * `current` (`flow_route.outcome`, the contract doc is the rule): the run's - * latest request opened after `current`, on any node, a pending one first; - * else, once the run has ended, `current` itself. `undefined` when neither - * says anything, and when several later requests are pending at once: no one - * step is where a parallel approval stands, and none is picked. + * latest request opened after `current` was DECIDED (`completed_at`; its + * `created_at` on a row that records no decision time), on any node, a + * pending one first; else, once the run has ended, `current` itself. + * `undefined` when neither says anything, and when several later requests are + * pending at once: no one step is where a parallel approval stands, and none + * is picked. + * + * From the decision, not from the opening: a request of the same run opened + * while `current` was still pending is a sibling, not where the approval went + * after `current`. A run opens one beside another when one node fans out to + * two approval steps over unconditional edges (the engine runs those targets + * together), which a flow can declare. * * `runRows` is the run's own request rows, as for {@link passedSteps}; * `runEnded` is whether the record's approval is KNOWN to have stopped: the @@ -168,19 +176,19 @@ export function stepsAhead( * it cannot tell. */ export function routeOutcome( - current: { id: string; status?: string; created_at?: string }, + current: { id: string; status?: string; created_at?: string; completed_at?: string }, runRows: ReadonlyArray, runEnded: boolean, label: RouteStepLabel, ): RouteOutcome | undefined { - const openedAt = current.created_at; + const decidedAt = current.completed_at || current.created_at; const later: Array<{ node: string; status: string; at: string }> = []; - if (openedAt) { + if (decidedAt) { for (const r of runRows) { const node = typeof r.flow_node_id === 'string' ? r.flow_node_id : undefined; const at = typeof r.created_at === 'string' ? r.created_at : undefined; const status = typeof r.status === 'string' ? r.status : undefined; - if (!node || !at || !status || String(r.id) === current.id || at <= openedAt) continue; + if (!node || !at || !status || String(r.id) === current.id || at <= decidedAt) continue; later.push({ node, status, at }); } } @@ -208,7 +216,7 @@ export function routeOutcome( * names no node. */ export function flowRoute( - row: Pick, + row: Pick, flow: RouteFlowGraph, runRows: ReadonlyArray, label: RouteStepLabel, diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 9cd93c58a77..8e48bc7943e 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -124,6 +124,7 @@ import { } from './approver-address.js'; import { labelOrMachineName, requestDisplayLabels, slateLabelOf } from './display-labels.js'; import { flowHostsChildRuns, flowRoute, type RouteFlowGraph } from './approval-route.js'; +import { ranArmedBody as runRanArmedBody } from './run-body-witness.js'; import { ADMIN_RESCUE_NOTE_SNAPSHOT_KEY, adminRescueNoteOf, @@ -341,14 +342,14 @@ export interface ApprovalResumeSurface { */ getActionDescriptor?(type: string): { supportsPause?: unknown; aliasOf?: unknown } | undefined; /** - * [#35863] A flow name's registrations, oldest first: each body and when it - * was registered. Read by {@link ApprovalService.attachFlowRoute} to tell - * whether a run ran the body armed now (`ranArmedBody`). ⚠️ Declares a - * method `AutomationEngine` ALREADY implements publicly - * (`getFlowVersionHistory`); it widens no engine surface. Optional: absent, - * no request is served "ended". + * The content checksum of the body a run ran, off its durable row, and of + * a body the engine holds now. Read by {@link ApprovalService.attachFlowRoute} + * to tell whether a run ran the body armed now (`ranArmedBody`, + * `./run-body-witness.ts`). Methods `AutomationEngine` implements publicly. + * Optional: absent, no request is served "ended". */ - getFlowVersionHistory?(name: string): ReadonlyArray<{ version?: number; definition: unknown; createdAt: string }>; + getRunFlowChecksum?(runId: string): Promise; + getFlowBodyChecksum?(flow: unknown): string | undefined; /** * Terminally cancel a suspended run (ADR-0044). Used when a recall lands * during a revision window — the run is paused at the revise-window node, @@ -14896,11 +14897,20 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * run id and is not among the rows read here, so neither "ended here" nor * "the last decision" can be known. "Its flow" is the body the run ran, * and the read holds only the body armed NOW, so "ended" is also refused - * unless the run provably ran that body ({@link ranArmedBody}): a flow - * edited after the run, to drop its `subflow` say, is not judged by the - * edit. A request opened before the stamp, a child run's, a run of such a - * flow, a run not known to have run the armed body, or a run that cannot be - * read is never "ended": `ended: false` means "not known to have stopped". + * unless the run provably ran that body (`ranArmedBody`, + * `./run-body-witness.ts`): the content checksum the run's durable row + * recorded equals the armed body's, so a restart or a re-registration of + * the same content keeps the answer, and a flow edited or rolled back after + * the run, to drop its `subflow` say, is not judged by the edit. A request + * opened before the stamp, a child run's, a run of such a flow, a run not + * known to have run the armed body, or a run that cannot be read is never + * "ended": `ended: false` means "not known to have stopped". + * + * "Later" is a request of the same run opened after this one was decided + * (`routeOutcome`), not merely after it opened: one node fanning out to two + * approval steps over unconditional edges opens two requests of one run + * side by side, and the sibling is not where the approval went after this + * one (`flow-route.integration.test.ts` pins the fan-out). */ private async attachFlowRoute( row: ApprovalRequestRow, @@ -14929,7 +14939,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega labels?.stepLabel(flowName, nodeId) ?? (nodesById.get(nodeId)?.label || stored.get(nodeId) || nodeId); const runRoot = parseJson(raw?.node_config_json, undefined)?.__runRoot === true; const ended = row.status !== 'pending' && runRoot && !flowHostsChildRuns(flow) - && await this.runHasEnded(row.flow_run_id, flowName, flow); + && await this.runHasEnded(row.flow_run_id, flow); const route = flowRoute(row, flow, rows, label, ended); if (route) (row as any).flow_route = route; } catch { /* display-only — never fail the read */ } @@ -14937,45 +14947,32 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega /** * [#35863] Whether the flow run `runId` has stopped for good, having run - * `flow`: its status is one of {@link TERMINAL_RUN_STATUSES} and - * {@link ranArmedBody} holds for it. `false` when there is no `getRun`, no - * such run, or a read throws: display-only, so an unreadable run is only - * ever "not known to have ended", never a failed read. + * `flow`: its status is one of {@link TERMINAL_RUN_STATUSES} and the run's + * durable body checksum equals `flow`'s (`ranArmedBody`, + * `./run-body-witness.ts`). `false` when there is no `getRun`, no such run, + * or a read throws: display-only, so an unreadable run is only ever "not + * known to have ended", never a failed read. */ - private async runHasEnded(runId: string, flowName: string, flow: unknown): Promise { + private async runHasEnded(runId: string, flow: unknown): Promise { if (typeof this.automation?.getRun !== 'function') return false; try { const run = await this.automation.getRun(runId); const status = run?.status; - return !!status && TERMINAL_RUN_STATUSES.has(status) && this.ranArmedBody(run?.startedAt, flowName, flow); + return !!status && TERMINAL_RUN_STATUSES.has(status) && await this.ranArmedBody(runId, flow); } catch { return false; } } /** - * [#35863] Whether a run that started at `startedAt` provably ran `flow`, - * the body of `flowName` armed now: `flow` is the engine's NEWEST - * registration of the name (`getFlowVersionHistory`, the very object), and - * was registered strictly before the run started. A run starts on the body - * armed at its start and resumes pinned to it, so with nothing registered - * since, that body is `flow`. - * - * Every other case is "not known", never a guess: a body registered after - * the run started (an edit, or the registration a restart makes), a body - * armed without being the newest registration (a rollback re-arms an older - * one), no history for the name, or no start time. The run's `flowVersion` - * is not the witness: it is the author's number and an edit need not change - * it. + * [#35863] Whether run `runId` provably ran `flow`, the body armed now: the + * content checksum its durable row records equals `flow`'s. The witness and + * its fail-closed cases live in `./run-body-witness.ts`; "not known" (a run + * that recorded no checksum, a reader without the two engine reads) is + * never a guess. */ - private ranArmedBody(startedAt: unknown, flowName: string, flow: unknown): boolean { - if (typeof startedAt !== 'string' || typeof this.automation?.getFlowVersionHistory !== 'function') return false; - const history = this.automation.getFlowVersionHistory(flowName); - const newest = Array.isArray(history) && history.length > 0 ? history[history.length - 1] : undefined; - if (!newest || newest.definition !== flow) return false; - const registered = Date.parse(newest.createdAt); - const started = Date.parse(startedAt); - return Number.isFinite(registered) && Number.isFinite(started) && registered < started; + private ranArmedBody(runId: string, flow: unknown): Promise { + return runRanArmedBody(this.automation, runId, flow); } async listActions(requestId: string, context: ExecutionContext): Promise { diff --git a/packages/plugins/plugin-approvals/src/flow-route.integration.test.ts b/packages/plugins/plugin-approvals/src/flow-route.integration.test.ts index b9b8f4b88d2..c682a30865d 100644 --- a/packages/plugins/plugin-approvals/src/flow-route.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/flow-route.integration.test.ts @@ -45,10 +45,10 @@ * both sides on purpose: the trunk is served unchanged. */ -import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { describe, it, expect, beforeAll, beforeEach, afterAll } from 'vitest'; import { ObjectQL } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; -import { AutomationEngine, installBuiltinNodes } from '@objectstack/service-automation'; +import { AutomationEngine, InMemorySuspendedRunStore, installBuiltinNodes } from '@objectstack/service-automation'; import type { EngineQueryOptions } from '@objectstack/spec/data'; import { ApprovalService } from './approval-service.js'; import { ApprovalsServicePlugin } from './approvals-plugin.js'; @@ -529,3 +529,220 @@ describe('[#26668] the approvals get serves the route a request takes, not the f expect(rows.map((r: any) => [r.id, 'flow_route' in r, 'flow_steps' in r])).toEqual([[manager.id, false, false]]); }); }); + +/** + * "Ended" is judged against the content of the body the run ran, as its + * durable run row records it, not against this process's registrations. + * + * The rig is the one above, plus a durable suspended-run store shared by + * every engine here: a second engine on the same store is a restart, or a + * second replica. Every pin reads a request whose root run has ended. + * + * ⚠️ Direction, measured on the registration-time witness this replaces: the + * restart and same-content re-registration pins were RED there (`outcome` + * absent: the body armed now was registered after the run started), and the + * two pins for a body the run did not run were RED the other way (`ended: + * true` served for the edited body). The controls are green on both. + */ +describe('the approval-ended witness is the content of the body the run ran, durable across restarts', () => { + let engine: ObjectQL; + let store: InMemorySuspendedRunStore; + let now = Date.parse('2026-11-30T09:00:00.000Z'); + let seq = 0; + + /** An engine over the shared store, with the built-ins, the approval node and `flows` registered. */ + const bootEngine = (svc: ApprovalService, ...flows: any[]): AutomationEngine => { + const automation = new AutomationEngine(silent); + installBuiltinNodes(automation, { logger: silent, getService() { throw new Error('none'); } } as any); + automation.setSuspendedRunStore(store); + svc.attachAutomation(automation as any); + registerApprovalNode(automation as any, svc, silent); + for (const flow of flows) automation.registerFlow(flow.name, flow); + return automation; + }; + /** The get, as the submitter reads it, through `svc`. */ + const read = async (svc: ApprovalService, req: any): Promise => svc.getRequest(req.id, asUser(SUBMITTER)); + const newService = (): ApprovalService => new ApprovalService({ + engine: engine as any, + clock: { now: () => new Date(now += 1000) }, + logger: silent, + }); + const pendingOn = async (recordId: string): Promise => { + const rows: any[] = await engine.find('sys_approval_request', { + where: { record_id: recordId, status: 'pending' }, context: SYSTEM, + } satisfies EngineQueryOptions); + return rows[0]; + }; + const submit = async (automation: AutomationEngine, flow: string): Promise => { + const record = { id: `D_${++seq}`, title: `Contract D${seq}`, amount: 100, route_legal: false, route_finance: false }; + await engine.insert('crm_contract', record, { context: SYSTEM } as any); + const run = await automation.execute(flow, { object: 'crm_contract', record, userId: SUBMITTER } as any); + expect(run.status, `${flow} paused on its first step`).toBe('paused'); + return pendingOn(record.id); + }; + const decide = async (svc: ApprovalService, req: any, decider: string, decision: 'approve' | 'reject'): Promise => { + const out = await svc.decide(req.id, { decision, actorId: decider, ...(decision === 'reject' ? { comment: 'Not this quarter' } : {}) }, asUser(decider)); + expect([out.finalized, out.resumed], `${decider} ${decision}d ${req.flow_node_id}`).toEqual([true, true]); + return pendingOn(req.record_id); + }; + /** LINEAR under its own name: no child run anywhere, so "ended" turns on the witness alone. */ + const linear = (name: string) => ({ ...LINEAR, name }); + /** The manager, then legal in a child run: the body a run must not be judged by once edited away. */ + const hosting = (name: string, version: number) => ({ ...REVIEWED_THEN_LEGAL, name, version }); + /** The same flow edited to drop its child run. */ + const dropped = (name: string, version: number) => { + const { nodes, edges } = REVIEWED_THEN_LEGAL; + return { + ...REVIEWED_THEN_LEGAL, name, version, + nodes: nodes.filter((n) => n.id !== 'legal'), + edges: [...edges.filter((e) => e.source !== 'legal' && e.target !== 'legal'), { id: 'r5', source: 'manager_review', target: 'done', label: 'approve' }], + }; + }; + /** A three-step linear run walked to its end on `automation`: its last request, decided. */ + const runLinearToEnd = async (svc: ApprovalService, automation: AutomationEngine, name: string): Promise => { + const manager = await submit(automation, name); + const director = await decide(svc, manager, 'u_mgr', 'approve'); + const gm = await decide(svc, director, 'u_dir', 'approve'); + expect(await decide(svc, gm, 'u_gm', 'approve'), 'nothing pending at the end').toBeUndefined(); + expect((await automation.getRun(gm.flow_run_id))?.status, 'the run has ended').toBe('completed'); + return gm; + }; + + beforeAll(async () => { + engine = new ObjectQL(); + engine.registerDriver(new SqlDriver({ + client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true, + }), true); + await engine.init(); + for (const def of [sysUser, contract, ...(await packageObjects())]) { + engine.registry.registerObject(def as any, 'approvals-witness-test', 'approvals-witness-test'); + } + await engine.syncSchemas(); + await installDefaultOrganization(engine); + for (const u of USERS) await engine.insert('sys_user', u, { context: SYSTEM } as any); + }); + + beforeEach(() => { + store = new InMemorySuspendedRunStore(); + }); + + afterAll(async () => { + try { await engine?.destroy(); } catch { /* noop */ } + }); + + it('a run, then a restart that registers the same body again: the read still serves "ended"', async () => { + const svc = newService(); + const name = 'witness_restart'; + const first = bootEngine(svc, linear(name)); + const gm = await runLinearToEnd(svc, first, name); + expect((await read(svc, gm)).flow_route.outcome).toEqual({ status: 'approved', ended: true }); + + // The restart: a new engine over the same store, nothing of the run in memory, the body registered after the run. + const second = bootEngine(svc, linear(name)); + expect(await second.getRunFlowChecksum(gm.flow_run_id), 'the run\'s identity is read off its durable row').toMatch(/^sha256:/); + expect((await read(svc, gm)).flow_route.outcome).toEqual({ status: 'approved', ended: true }); + }); + + it('a run, then the same content registered again in the same process: the read still serves "ended"', async () => { + const svc = newService(); + const name = 'witness_reregistered'; + const automation = bootEngine(svc, linear(name)); + const gm = await runLinearToEnd(svc, automation, name); + automation.registerFlow(name, linear(name) as any); + expect((await read(svc, gm)).flow_route.outcome).toEqual({ status: 'approved', ended: true }); + }); + + it('a rollback made before the run started and undone after it: the body armed again is not the one the run ran', async () => { + const svc = newService(); + const name = 'witness_rollback_undone'; + // Version 1 hosts the legal child run; version 2, the newest registration, drops it. + const automation = bootEngine(svc, CHILD, hosting(name, 1), dropped(name, 2)); + automation.rollbackFlow(name, 1); + await new Promise((r) => setTimeout(r, 5)); // every registration strictly before the run starts + const manager = await submit(automation, name); + const legal = await decide(svc, manager, 'u_mgr', 'approve'); + expect(legal.flow_run_id, 'the run ran version 1: legal is a child run').not.toBe(manager.flow_run_id); + await decide(svc, legal, 'u_legal', 'reject'); + expect((await automation.getRun(manager.flow_run_id))?.status, 'the root run has ended').toBe('completed'); + + // Version 2 armed again, by the rollback undone: no new registration, registered before the run started. + automation.rollbackFlow(name, 2); + expect(automation.getFlowVersionHistory(name).at(-1)?.definition, 'the armed body is the newest registration').toBe(await automation.getFlow(name)); + // Not "the approval ended here, approved": it went on to legal, whose rejection was the last decision. + expect((await read(svc, manager)).flow_route).toEqual({ + steps: [{ id: 'manager_review', label: 'Manager', state: 'done' }], + ahead: 'decided', + }); + }); + + it('two replicas: the reading one registered an edit before the run started on the other, which ran the older body', async () => { + const runner = newService(); + const reader = newService(); + const name = 'witness_replicas'; + // The reader holds the edit (no child run) before the run starts; the runner still holds the older body. + const readerEngine = bootEngine(reader, dropped(name, 2)); + const runnerEngine = bootEngine(runner, CHILD, hosting(name, 1)); + await new Promise((r) => setTimeout(r, 5)); // the reader's registration strictly before the run starts + const manager = await submit(runnerEngine, name); + const legal = await decide(runner, manager, 'u_mgr', 'approve'); + await decide(runner, legal, 'u_legal', 'reject'); + expect((await runnerEngine.getRun(manager.flow_run_id))?.status, 'the root run has ended').toBe('completed'); + + expect(Date.parse(readerEngine.getFlowVersionHistory(name).at(-1)!.createdAt), 'the reader registered its body before the run started') + .toBeLessThan(Date.parse((await readerEngine.getRun(manager.flow_run_id))!.startedAt)); + expect((await read(reader, manager)).flow_route).toEqual({ + steps: [{ id: 'manager_review', label: 'Manager', state: 'done' }], + ahead: 'decided', + }); + // CONTROL: the runner, which holds the body the run ran, serves the same: the run hosts a child run. + expect('outcome' in (await read(runner, manager)).flow_route).toBe(false); + }); + + it('[N2] a node fanning out to two approval steps opens two requests of one run; the sibling is not where the decided one went', async () => { + const svc = newService(); + const fan = { + name: 'witness_fan_out', label: 'Fan out', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + step('a_review', 'A', 'u_mgr'), + step('b_review', 'B', 'u_dir'), + { id: 'ok', type: 'end', label: 'Ok' }, + ], + // Two unconditional edges out of one node: the engine runs both targets together. + edges: [ + { id: 'f1', source: 'start', target: 'a_review' }, + { id: 'f2', source: 'start', target: 'b_review' }, + { id: 'f3', source: 'a_review', target: 'ok', label: 'approve' }, + { id: 'f4', source: 'b_review', target: 'ok', label: 'approve' }, + ], + }; + const automation = bootEngine(svc, fan); + const first = await submit(automation, fan.name); + const opened: any[] = await engine.find('sys_approval_request', { + where: { flow_run_id: first.flow_run_id }, context: SYSTEM, + } satisfies EngineQueryOptions); + // Measured, not assumed: the flow parses and both steps open, pending side by side in ONE run. + expect(opened.map((r) => [r.flow_node_id, r.status]).sort()).toEqual([['a_review', 'pending'], ['b_review', 'pending']]); + const a = opened.find((r) => r.flow_node_id === 'a_review'); + const b = opened.find((r) => r.flow_node_id === 'b_review'); + expect(b.created_at > a.created_at, 'b opened after a, while a was pending').toBe(true); + + await decide(svc, a, 'u_mgr', 'approve'); + const outcome = (await read(svc, a)).flow_route.outcome; + // Read from the opening, b (opened after a opened) would be served as where a's approval went. + expect(outcome?.step, 'the sibling opened before a was decided is not a later step').toBeUndefined(); + expect(outcome?.status).toBe('approved'); + }); + + it('CONTROL: a run of the edited body itself, read on a replica that holds that body, serves "ended"', async () => { + const runner = newService(); + const reader = newService(); + const name = 'witness_replicas_same'; + const readerEngine = bootEngine(reader, dropped(name, 2)); + const runnerEngine = bootEngine(runner, dropped(name, 2)); + const manager = await submit(runnerEngine, name); + expect(await decide(runner, manager, 'u_mgr', 'approve'), 'nothing pending at the end').toBeUndefined(); + expect(await readerEngine.getRunFlowChecksum(manager.flow_run_id)).toBe(readerEngine.getFlowBodyChecksum(await readerEngine.getFlow(name))); + expect((await read(reader, manager)).flow_route.outcome).toEqual({ status: 'approved', ended: true }); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/run-body-witness.ts b/packages/plugins/plugin-approvals/src/run-body-witness.ts new file mode 100644 index 00000000000..afcefa076ec --- /dev/null +++ b/packages/plugins/plugin-approvals/src/run-body-witness.ts @@ -0,0 +1,60 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Whether a flow run ran the body of its flow armed now: the witness a + * decided request's `flow_route.outcome.ended` stands on + * (`ApprovalService.attachFlowRoute`; the contract is `ApprovalRequestRow`'s + * `flow_route` in `@objectstack/spec/contracts`). + * + * "Ended" reads the body armed now (does it hold a `subflow` or `map` node?), + * so it may only be served for a run that ran that body. The witness is the + * body's CONTENT: the checksum the run recorded of the body it ran + * (`AutomationEngine.getRunFlowChecksum`, kept on the run's durable row) + * against the checksum of the body armed now + * (`AutomationEngine.getFlowBodyChecksum`). Both are `hashSpec(body, 'flow')`, + * the identity the metadata history keys a stored flow's versions by, so: + * + * - a restart, or a re-registration of the same content (a package reload, + * a save that changed nothing), keeps the answer: the content is the same; + * - an edit, a rollback, or a body this process received later or earlier + * than the process that ran the run, changes the content, so the run is + * not judged by the body armed now, however the registrations are timed. + * + * It replaces a witness built on this process's registration history (the + * newest registration, registered before the run started), which every + * restart and re-registration defeated, and which a rollback undone after the + * run started, or a replica that registered an edit before another replica + * started the run on the older body, could satisfy for a body the run did not + * run. + * + * Fail-closed: no answer, a missing reader, a run that recorded no checksum + * (one that finished before runs kept it), a body that has none, or a read + * that throws, is "not known", never a guess. + */ + +/** The two engine reads the witness needs. Both optional: absent, nothing is witnessed. */ +export interface RunBodyWitnessReader { + /** The content checksum of the body run `runId` ran, as its durable row records it. */ + getRunFlowChecksum?(runId: string): Promise; + /** The content checksum of `flow`, a body the engine holds. */ + getFlowBodyChecksum?(flow: unknown): string | undefined; +} + +/** Whether run `runId` provably ran `flow`, a body the engine holds now. */ +export async function ranArmedBody( + automation: RunBodyWitnessReader | undefined, + runId: string, + flow: unknown, +): Promise { + if (typeof automation?.getRunFlowChecksum !== 'function' || typeof automation.getFlowBodyChecksum !== 'function') { + return false; + } + try { + const armed = automation.getFlowBodyChecksum(flow); + if (typeof armed !== 'string' || armed === '') return false; + const ran = await automation.getRunFlowChecksum(runId); + return ran === armed; + } catch { + return false; + } +} diff --git a/packages/services/service-automation/src/dag-traversal.ts b/packages/services/service-automation/src/dag-traversal.ts index a091a2b3d12..8007e54d629 100644 --- a/packages/services/service-automation/src/dag-traversal.ts +++ b/packages/services/service-automation/src/dag-traversal.ts @@ -69,6 +69,7 @@ import { readPartialSteps } from './partial-steps.js'; import { isRegionSuspensionRefusal, refuseRegionSuspension } from './region-suspension-refusal.js'; import { stampFlowRunSlot } from './flow-slots.js'; import { stampRootRun } from './root-run.js'; +import { stampRunFlowChecksum } from './run-flow-checksum.js'; import { copyForScopeDescent, copyHeldValue, isSkippedScopeKey, scopeContainer } from './scope-key-segments.js'; /** @@ -1440,6 +1441,8 @@ export async function executeWithoutRetry( // [ADR-0162 item 7] Each attempt is a run of its own, and its own root // when it has no parent, as `execute()` stamps it. stampRootRun(runContext, { runId, flowName, startedAt }); + // The body this attempt runs, by content, as `execute()` stamps it. + stampRunFlowChecksum(runContext, runId, this.flowChecksumOf(flow)); try { const startNode = flow.nodes.find(n => n.type === 'start'); diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index cefe9541a99..648fd2f10ac 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -65,6 +65,7 @@ export const DEFAULT_BRANCH_LABEL = 'default'; import { runTriggerUserId, type SeededRunContext } from './runtime-identity.js'; import { flowContentChecksum } from './flow-identity.js'; +import { getRunFlowChecksum, runRecordFlowChecksum, stampRunFlowChecksum } from './run-flow-checksum.js'; import { HeldValueCycleError, hasReservedVariableKeySegment } from './scope-key-segments.js'; import { carriedRefusalOfResult, readCarriedRefusal, type CarriedRefusal } from './inner-refusal.js'; import { summarizeRun } from './run-summary.js'; @@ -2159,6 +2160,19 @@ export interface RunRecord { * ⛔ Not a run state. See {@link ConsumedSuspension}. */ consumedSuspension?: SuspendedRun; + /** + * The checksum of the flow body the run ran ({@link SuspendedRun.flowChecksum}), + * stamped on the run's context where it starts (`./run-flow-checksum.ts`) + * and carried here from it, so a finished run still says which body it ran + * after a restart or a re-registration of its flow. Absent for a run whose + * context carries none (its body could not be hashed, it was parked + * before the stamp and its suspension pinned none, or it resumed on + * another body once the one it started on could no longer be found), for + * a record that carries {@link consumedSuspension} (a strand can be + * restored, and its row's `flow_checksum` is that pause's pin, not this), + * and on rows written before this field existed. + */ + flowChecksum?: string; /** * [#13937] The store could not persist the snapshot this run had — the * object store DROPS one over its row byte budget rather than truncating @@ -3320,6 +3334,12 @@ export class AutomationEngine implements IAutomationService { * {@link flowVersionHistory}, or a pinned body read back on resume. */ private readonly flowChecksums = new WeakMap(); + /** + * The body checksum each in-memory run entry's record carried — see + * {@link getRunFlowChecksum}. Beside the entry, never on it: the entry is + * served verbatim by the run-detail route. + */ + private readonly entryFlowChecksums = new WeakMap(); /** [#28405] Where a pinned body is read back by its identity — see {@link setFlowHistorySource}. */ private flowHistorySource?: FlowHistorySource; private nodeExecutors = new Map(); @@ -7963,6 +7983,37 @@ export class AutomationEngine implements IAutomationService { return key === undefined ? [] : this.flowVersionHistory.get(key) ?? []; } + /** + * The content checksum of the flow body the FINISHED run `runId` ran + * ({@link RunRecord.flowChecksum}): durable, so it answers after a + * restart, on another replica, and after the flow is registered again. + * Read as {@link getRun} reads a finished run (ring, then terminal row). + * `undefined` for a run not finished, one that recorded none, or one not + * found; throws when the store throws. The body lives in + * `./run-flow-checksum.ts`. + */ + getRunFlowChecksum(runId: string): Promise { + const readStore = () => this.store; + const host: ThisParameterType = { + executionLogs: this.executionLogs, + entryFlowChecksums: this.entryFlowChecksums, + get store() { return readStore(); }, + }; + return getRunFlowChecksum.call(host, runId); + } + + /** + * The content checksum of `flow`, a body this engine holds (the object + * {@link getFlow}, {@link getRunFlow} or {@link getFlowSlot} answered): + * the identity a run of it records ({@link getRunFlowChecksum}), equal for + * two registrations of the same content, a restart's included. + * `undefined` for an object this engine did not register, or a body that + * could not be hashed. + */ + getFlowBodyChecksum(flow: unknown): string | undefined { + return flow !== null && typeof flow === 'object' ? this.flowChecksumOf(flow as FlowParsed) : undefined; + } + /** Rollback flow to a specific version */ rollbackFlow(name: string, version: number): void { // The body lives in ./flow-definitions.ts (#25222). @@ -8483,6 +8534,8 @@ export class AutomationEngine implements IAutomationService { stampFlowRunSlot(runContext, flowName, runPackage); // [ADR-0162 item 7] The run's root run: itself, or its parent's. stampRootRun(runContext, { runId, flowName, startedAt }); + // The body this run runs, by content: its own, never its parent's. + stampRunFlowChecksum(runContext, runId, this.flowChecksumOf(flow)); try { // Find the start node @@ -10840,7 +10893,11 @@ export class AutomationEngine implements IAutomationService { compactStepsForHistory: (...a) => this.compactStepsForHistory(...a), consumedSuspensions: this.consumedSuspensions, }; - return recordLog.call(host, entry, context, consumedSuspension); + const logged = recordLog.call(host, entry, context, consumedSuspension); + // The body a finished run ran, beside its ring entry (see {@link getRunFlowChecksum}). + const checksum = runRecordFlowChecksum(context, logged.id, consumedSuspension); + if (checksum !== undefined && isTerminalRunStatus(logged.status)) this.entryFlowChecksums.set(logged, checksum); + return logged; } /** diff --git a/packages/services/service-automation/src/flow-version-pinning.test.ts b/packages/services/service-automation/src/flow-version-pinning.test.ts index d88f281bd55..0b3cd5831f2 100644 --- a/packages/services/service-automation/src/flow-version-pinning.test.ts +++ b/packages/services/service-automation/src/flow-version-pinning.test.ts @@ -230,3 +230,96 @@ describe('a suspended run resumes on the flow body it started on (#28405)', () = expect(history).toHaveBeenLastCalledWith('expense', hashSpec(v1, 'flow')); }); }); + +/** + * The run's identity outlives the run: the terminal record carries the + * checksum of the body the run ran (`run-flow-checksum.ts`), and the engine + * answers it (`getRunFlowChecksum`) beside the checksum of a body it holds + * (`getFlowBodyChecksum`), so a reader can ask "did this finished run run the + * body armed now?" after a restart, on another engine, and after the same + * content is registered again. + */ +describe('a finished run says which body it ran, by content, after a restart', () => { + it('parked, resumed to its end: the terminal record carries the checksum of the body it ran', async () => { + const store = new InMemorySuspendedRunStore(); + const { engine } = engineOver(store); + const v1 = taggedFlow('expense', { tag: 'v1' }); + engine.registerFlow('expense', v1 as never); + const runId = await park(engine, 'expense'); + expect((await engine.resume(runId)).success).toBe(true); + + expect((await store.loadTerminal(runId))?.flowChecksum).toBe(hashSpec(v1, 'flow')); + expect(await engine.getRunFlowChecksum(runId), 'from the in-memory entry').toBe(hashSpec(v1, 'flow')); + expect(engine.getFlowBodyChecksum(await engine.getFlow('expense'))).toBe(hashSpec(v1, 'flow')); + }); + + it('a restart, the same content registered again: the new engine reads the run\'s identity off its row, equal to the armed body\'s', async () => { + const store = new InMemorySuspendedRunStore(); + const first = engineOver(store); + first.engine.registerFlow('expense', taggedFlow('expense', { tag: 'v1' }) as never); + const runId = await park(first.engine, 'expense'); + expect((await first.engine.resume(runId)).success).toBe(true); + + const second = engineOver(store); + second.engine.registerFlow('expense', taggedFlow('expense', { tag: 'v1' }) as never); + const armed = second.engine.getFlowBodyChecksum(await second.engine.getFlow('expense')); + expect(armed).toMatch(/^sha256:/); + expect(await second.engine.getRunFlowChecksum(runId)).toBe(armed); + + // An edit, under the same version number, is another body. + second.engine.registerFlow('expense', taggedFlow('expense', { tag: 'v1-edited' }) as never); + expect(second.engine.getFlowBodyChecksum(await second.engine.getFlow('expense'))).not.toBe(armed); + }); + + it('resumed after an edit: the record names the body the run started on and finished on, not the edit', async () => { + const store = new InMemorySuspendedRunStore(); + const { engine, ran } = engineOver(store); + const v1 = taggedFlow('expense', { tag: 'v1' }); + engine.registerFlow('expense', v1 as never); + const runId = await park(engine, 'expense'); + engine.registerFlow('expense', taggedFlow('expense', { tag: 'v2', version: 2 }) as never); + expect((await engine.resume(runId)).success).toBe(true); + expect(ran).toEqual(['v1']); + expect((await store.loadTerminal(runId))?.flowChecksum).toBe(hashSpec(v1, 'flow')); + }); + + it('a run whose pinned body was lost resumes on another body, and records none: it ran no single body', async () => { + const store = new InMemorySuspendedRunStore(); + const first = engineOver(store); + first.engine.registerFlow('expense', taggedFlow('expense', { tag: 'v1' }) as never); + const runId = await park(first.engine, 'expense'); + + const second = engineOver(store); + second.engine.registerFlow('expense', taggedFlow('expense', { tag: 'v2', version: 2 }) as never); + expect((await second.engine.resume(runId)).success).toBe(true); + expect(second.ran).toEqual(['v2']); + expect((await store.loadTerminal(runId))?.flowChecksum).toBeUndefined(); + expect(await second.engine.getRunFlowChecksum(runId)).toBeUndefined(); + }); + + it('a run parked before its context carried the stamp: the record carries the identity its suspension pinned', async () => { + const store = new InMemorySuspendedRunStore(); + const { engine } = engineOver(store); + const v1 = taggedFlow('expense', { tag: 'v1' }); + engine.registerFlow('expense', v1 as never); + const runId = await park(engine, 'expense'); + const row = (await store.load(runId))!; + delete (row.context as Record).$flowChecksum; + await store.save(row); + (engine as unknown as { suspendedRuns: Map }).suspendedRuns.delete(runId); + + expect((await engine.resume(runId)).success).toBe(true); + expect((await store.loadTerminal(runId))?.flowChecksum).toBe(hashSpec(v1, 'flow')); + }); + + it('a context that carries another run\'s stamp (a child\'s copy of its parent\'s) is not this run\'s identity', async () => { + const store = new InMemorySuspendedRunStore(); + const { engine } = engineOver(store); + const v1 = taggedFlow('expense', { tag: 'v1' }); + engine.registerFlow('expense', v1 as never); + const parent = { $flowChecksum: { runId: 'run_parent', checksum: 'sha256:parent' } }; + const parked = await engine.execute('expense', parent as never); + expect((await engine.resume(parked.runId!)).success).toBe(true); + expect((await store.loadTerminal(parked.runId!))?.flowChecksum).toBe(hashSpec(v1, 'flow')); + }); +}); diff --git a/packages/services/service-automation/src/run-flow-checksum.ts b/packages/services/service-automation/src/run-flow-checksum.ts new file mode 100644 index 00000000000..c57023d267b --- /dev/null +++ b/packages/services/service-automation/src/run-flow-checksum.ts @@ -0,0 +1,160 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The content identity of the flow body a run ran, kept for the whole life of + * the run and after it ends. + * + * [#28405] A run records the checksum of the body it executes + * (`flowContentChecksum`, `./flow-identity.ts`) on its suspension, so a resume + * continues on that body. Before this module the identity ended there: a run + * that resumed and finished wrote a terminal `sys_automation_run` row with an + * empty `flow_checksum`, and nothing outside the engine could ask which body a + * finished run had run. A reader that must not judge a run by a body it did + * not run (the approvals plugin, deciding whether the record's approval has + * ended) could only compare in-process registration times, which every + * restart and every re-registration of the flow defeats. + * + * So the engine stamps the checksum on the run's own context + * ({@link RUN_FLOW_CHECKSUM_CONTEXT_KEY}) where the run starts, beside its slot + * and its root run. The stamp rides every suspension of the run (the context + * crosses JSON to the durable store and back, so it is plain data) and every + * resume, and the terminal record carries it to the row + * (`RunRecord.flowChecksum`). + * + * The stamp names the run it belongs to. A child run (a `subflow` body, a + * `map` item) builds its context from its parent's, and a caller's context + * can be a parent run's; a stamp read for any other run id is not this run's + * and reads as none. A child is stamped again at its own start with its own + * body's checksum. + * + * Two reads answer from it (`AutomationEngine.getRunFlowChecksum` and + * `AutomationEngine.getFlowBodyChecksum`); the bodies live here, the engine + * only calls them. + */ + +import type { ExecutionLogEntry, RunRecord, SuspendedRun } from './engine.js'; + +/** The context key the run's body checksum rides on. Engine-owned, like `$rootRun`. */ +export const RUN_FLOW_CHECKSUM_CONTEXT_KEY = '$flowChecksum'; + +/** + * The stamp: the run it belongs to, and its body's checksum, or `null` when + * the run ran no body known by content (a body that could not be hashed, a + * run that resumed on another body than the one it started on, a run parked + * before identities were recorded). + */ +interface RunFlowChecksumStamp { + runId: string; + checksum: string | null; +} + +function isChecksum(value: unknown): value is string { + return typeof value === 'string' && value !== ''; +} + +/** The stamp `context` carries for `runId`, or `undefined` when it carries none for that run. */ +function stampOf(context: unknown, runId: string): RunFlowChecksumStamp | undefined { + if (context === null || typeof context !== 'object') return undefined; + const raw = (context as Record)[RUN_FLOW_CHECKSUM_CONTEXT_KEY] as Record | null | undefined; + if (!raw || typeof raw !== 'object' || raw.runId !== runId) return undefined; + return { runId, checksum: isChecksum(raw.checksum) ? raw.checksum : null }; +} + +/** + * Stamp a starting run's own context (the run context the engine built for + * it, never the caller's) with the checksum of the body it runs. Always + * written, never inherited: whatever a parent's copy carried is replaced. + */ +export function stampRunFlowChecksum(runContext: object, runId: string, checksum: string | undefined): void { + const stamp: RunFlowChecksumStamp = { runId, checksum: isChecksum(checksum) ? checksum : null }; + (runContext as Record)[RUN_FLOW_CHECKSUM_CONTEXT_KEY] = stamp; +} + +/** + * A resumed run's context, as the segment about to run carries it: a copy + * where it changes, so the persisted context is left as it parked. + * + * - A run whose pinned body could not be recovered resumes on another body + * (`resolveResumeTarget`'s `unrecovered`): from here it has run no single + * body, so it is stamped `null`, whatever it carried. + * - A run that carries its own stamp keeps it: the resume runs that body. + * - A run parked before the stamp existed carries none: it gets the identity + * its suspension pinned (#28405), the body it resumes on, or `null` when + * the suspension pinned none. + */ +export function resumeRunFlowChecksum( + context: T, + runId: string, + pinned: string | undefined, + unrecovered: boolean, +): T { + const own = stampOf(context, runId); + if (unrecovered) { + return own && own.checksum === null + ? context + : { ...context, [RUN_FLOW_CHECKSUM_CONTEXT_KEY]: { runId, checksum: null } satisfies RunFlowChecksumStamp }; + } + if (own) return context; + const stamp: RunFlowChecksumStamp = { runId, checksum: isChecksum(pinned) ? pinned : null }; + return { ...context, [RUN_FLOW_CHECKSUM_CONTEXT_KEY]: stamp }; +} + +/** + * The checksum the record of run `runId` carries: the run's own stamp on + * `context`, `null` reading as none on purpose. None, too, for a record that + * carries the suspension a resume consumed before the run failed (a strand): + * an operator can restore that pause and the run goes on, so it has not + * stopped for good, and the row's `flow_checksum` there is the pause's pin + * for that restore, which need not be the body the run ran (a run that lost + * its pinned body and parked again on another is pinned to the other). + */ +export function runRecordFlowChecksum( + context: unknown, + runId: string, + consumedSuspension?: SuspendedRun, +): string | undefined { + if (consumedSuspension !== undefined) return undefined; + return stampOf(context, runId)?.checksum ?? undefined; +} + +/** What {@link getRunFlowChecksum} reads. */ +export interface RunFlowChecksumHost { + /** The in-memory run ring, newest last. */ + readonly executionLogs: readonly ExecutionLogEntry[]; + /** The checksum each TERMINAL ring entry's record carried, keyed by the entry object. */ + readonly entryFlowChecksums: WeakMap; + /** The durable store, when one is attached. */ + readonly store?: { + loadTerminal?(runId: string): Promise; + }; +} + +/** + * The body of `AutomationEngine.getRunFlowChecksum`: the checksum of the body + * the FINISHED run `runId` ran — the newest ring entry, else the terminal row, + * in the order `getRun` reads them — so the identity and the terminal status a + * caller reads beside it describe the same record, in this process or after a + * restart. `undefined` for a run that has not finished (the newest entry is + * not terminal, or there is only a paused row), and for one that recorded + * none: it finished before terminal records carried one, its body could not + * be hashed, it was parked before the stamp and its suspension pinned none, + * it resumed on another body once the one it started on could no longer be + * found, or it failed after a resume and can be restored (a strand). + * + * A paused run is not answered on purpose: its suspension's pin is what its + * next resume looks its body up by, not a record of the body it ran, and the + * first consumer (the approvals `ended` witness) asks only of a finished run. + * + * Throws when the store throws: unlike `getRun`, which degrades an outage to + * "no such run", this answers a question a caller must not read as "no + * identity" — a caller that cannot afford a throw catches it and reads it as + * "not known". + */ +export async function getRunFlowChecksum(this: RunFlowChecksumHost, runId: string): Promise { + for (let i = this.executionLogs.length - 1; i >= 0; i--) { + const entry = this.executionLogs[i]; + if (entry.id === runId) return this.entryFlowChecksums.get(entry); + } + if (!this.store?.loadTerminal) return undefined; + return (await this.store.loadTerminal(runId))?.flowChecksum; +} diff --git a/packages/services/service-automation/src/run-history.ts b/packages/services/service-automation/src/run-history.ts index 79ee881efdb..644dcea572f 100644 --- a/packages/services/service-automation/src/run-history.ts +++ b/packages/services/service-automation/src/run-history.ts @@ -17,6 +17,7 @@ import type { ExecutionStatus, FlowParsed } from '@objectstack/spec/automation'; import type { AutomationContext, AutomationResult, RunListResult } from '@objectstack/spec/contracts'; import { summarizeRun, formatRunSummaryLine } from './run-summary.js'; import { describeThrownForLog } from './thrown-cause-diagnostics.js'; +import { runRecordFlowChecksum } from './run-flow-checksum.js'; // The values below (`buildRunTrigger` and `isTerminalRunStatus`) are read only // inside the function bodies, at call time, never while a module is evaluating, // so the import cycle with ./engine.js is safe under ESM live bindings; the @@ -674,6 +675,8 @@ export function recordLog( // restored and then finishes CLEARS its own snapshot instead of // leaving a stale one an operator could restore a second time. consumedSuspension, + // The body the run ran, by content (`./run-flow-checksum.ts`). + flowChecksum: runRecordFlowChecksum(context, entry.id, consumedSuspension), }; // [#13937] The journal entry this record describes, when it is a // strand's: `journalConsumedSuspension` ran just above in the diff --git a/packages/services/service-automation/src/run-resume.ts b/packages/services/service-automation/src/run-resume.ts index 80a10896af4..6e75bdf76a4 100644 --- a/packages/services/service-automation/src/run-resume.ts +++ b/packages/services/service-automation/src/run-resume.ts @@ -16,6 +16,7 @@ */ import { withFlowRunSlot } from './flow-slots.js'; +import { resumeRunFlowChecksum } from './run-flow-checksum.js'; import { deriveRunLinks, isRunLinkStamped, RECORD_RUN_CONTEXT_KEY, ROOT_RUN_CONTEXT_KEY, type RunLinkDerivation } from './root-run.js'; import type { FlowParsed, FlowRunSummary } from '@objectstack/spec/automation'; import type { DroppedFieldsEvent } from '@objectstack/spec/data'; @@ -2015,7 +2016,15 @@ export async function resumeInternal( // [#31696] A persisted context keeps no slot stamp: a run of a slot // whose name two slots hold is stamped again, so its subflow calls // resolve from its own package. - const context = withFlowRunSlot(segmentContext, run.flowName); + // The body this segment runs, by content (`./run-flow-checksum.ts`): + // the run's own stamp, the pin of a run parked before the stamp, or + // none once the pinned body was lost and the run moved bodies. + const context = resumeRunFlowChecksum( + withFlowRunSlot(segmentContext, run.flowName), + runId, + run.flowChecksum, + target.unrecovered !== undefined, + ); try { // [#18714] The child this run is parked on REFUSED — on either diff --git a/packages/services/service-automation/src/suspended-run-store.test.ts b/packages/services/service-automation/src/suspended-run-store.test.ts index 2a8d85985da..ec9b614ec58 100644 --- a/packages/services/service-automation/src/suspended-run-store.test.ts +++ b/packages/services/service-automation/src/suspended-run-store.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { AutomationEngine } from './engine.js'; -import { ObjectStoreSuspendedRunStore, type SuspendedRunStoreEngine } from './suspended-run-store.js'; +import { InMemorySuspendedRunStore, ObjectStoreSuspendedRunStore, type SuspendedRunStoreEngine } from './suspended-run-store.js'; import type { RunRecord, SuspendedRun } from './engine.js'; import { defineActionDescriptor } from '@objectstack/spec/automation'; import { RESUME_AUTHORITY_SERVICE } from '@objectstack/spec/contracts'; @@ -1776,3 +1776,89 @@ describe('ObjectStoreSuspendedRunStore — the terminal write runs outside the o expect(engine.rows.has('run_r1')).toBe(true); }); }); + +describe('ObjectStoreSuspendedRunStore — a terminal row carries the body the run ran', () => { + const snapshot = (flowChecksum?: string): SuspendedRun => ({ + runId: 'r1', flowName: 'busy_flow', nodeId: 'hold', variables: {}, steps: [], context: {}, + startedAt: '2026-01-01T00:00:01.000Z', startTime: 0, ...(flowChecksum ? { flowChecksum } : {}), + }); + + it('writes `flow_checksum` on a completed run\'s row and reads it back', async () => { + const engine = createFakeEngine(); + const store = new ObjectStoreSuspendedRunStore(engine, createTestLogger()); + await store.recordTerminal(terminalRecord(1, { flowChecksum: 'sha256:ran' })); + expect(engine.rows.get('run_r1').flow_checksum).toBe('sha256:ran'); + expect((await store.loadTerminal('r1'))!.flowChecksum).toBe('sha256:ran'); + }); + + it('a record that carries none writes NULL, so an upsert clears an identity the run no longer has', async () => { + const engine = createFakeEngine(); + const store = new ObjectStoreSuspendedRunStore(engine, createTestLogger()); + await store.recordTerminal(terminalRecord(1, { flowChecksum: 'sha256:ran' })); + await store.recordTerminal(terminalRecord(1)); + expect(engine.rows.get('run_r1').flow_checksum).toBeNull(); + expect((await store.loadTerminal('r1'))!.flowChecksum).toBeUndefined(); + }); + + it('a strand\'s row keeps its snapshot\'s pin for a restore, and never answers it as the run\'s identity', async () => { + // The engine's record of a strand carries no identity (`runRecordFlowChecksum`); the column holds the pause's pin. + const record = terminalRecord(1, { status: 'failed', consumedSuspension: snapshot('sha256:pinned') }); + const engine = createFakeEngine(); + const store = new ObjectStoreSuspendedRunStore(engine, createTestLogger()); + await store.recordTerminal(record); + expect(engine.rows.get('run_r1').flow_checksum).toBe('sha256:pinned'); + const loaded = (await store.loadTerminal('r1'))!; + expect(loaded.consumedSuspension!.flowChecksum, 'a restore re-arms the pause on its pin').toBe('sha256:pinned'); + expect(loaded.flowChecksum, 'the pin is not the body the run ran').toBeUndefined(); + + // The in-memory store answers the same. + const memory = new InMemorySuspendedRunStore(); + await memory.recordTerminal(record); + expect((await memory.loadTerminal('r1'))!.flowChecksum).toBeUndefined(); + }); + + it('a run that lost its pinned body, parked again on another and then failed: after a restart it names no body', async () => { + // Over the persistent store: what a second process reads goes through the `flow_checksum` column. + const rows = createFakeEngine(); + const store = new ObjectStoreSuspendedRunStore(rows, createTestLogger()); + const engineOn = (flow: Record) => { + const e = new AutomationEngine(createTestLogger(), store); + e.registerNodeExecutor({ + type: 'pause_node', descriptor: PAUSE_NODE_DESCRIPTOR, + async execute() { return { success: true, suspend: true, correlation: 'areq_1' }; }, + }); + e.registerNodeExecutor({ type: 'boom', async execute() { throw new Error('tail exploded'); } } as never); + e.registerFlow('lost_body', flow as never); + e.sealNodeTypeVocabulary(); + return e; + }; + const node = (id: string, type: string) => ({ id, type, label: id }); + const edge = (source: string, target: string) => ({ id: `${source}_${target}`, source, target }); + // A: start -> first -> end. B (another body, the pin A is lost under): start -> first -> second -> boom -> end. + const A = { name: 'lost_body', label: 'A', type: 'autolaunched', + nodes: [node('start', 'start'), node('first', 'pause_node'), node('end', 'end')], + edges: [edge('start', 'first'), edge('first', 'end')] }; + const B = { name: 'lost_body', label: 'B', type: 'autolaunched', + nodes: [node('start', 'start'), node('first', 'pause_node'), node('second', 'pause_node'), node('boom', 'boom'), node('end', 'end')], + edges: [edge('start', 'first'), edge('first', 'second'), edge('second', 'boom'), edge('boom', 'end')] }; + + const first = engineOn(A); + const parked = await first.execute('lost_body', {} as never); + expect(parked.status).toBe('paused'); + const runId = parked.runId!; + + // A restart that holds only B: the resume cannot recover A, runs B, and parks again, pinned to B. + const second = engineOn(B); + expect((await second.resume(runId)).status).toBe('paused'); + const bChecksum = second.getFlowBodyChecksum(await second.getFlow('lost_body')); + expect((await store.load(runId))?.flowChecksum, 'the second pause is pinned to B').toBe(bChecksum); + const failed = await second.resume(runId); + expect(failed.success, 'the node after the second pause threw: a strand').toBe(false); + expect(rows.rows.get(`run_${runId}`).flow_checksum, 'the strand row keeps its pin for a restore').toBe(bChecksum); + + // Another restart, B armed: the run ran A, then B, so it names no body. + const third = engineOn(B); + expect(third.getFlowBodyChecksum(await third.getFlow('lost_body'))).toBe(bChecksum); + expect(await third.getRunFlowChecksum(runId)).toBeUndefined(); + }); +}); diff --git a/packages/services/service-automation/src/suspended-run-store.ts b/packages/services/service-automation/src/suspended-run-store.ts index d925cc5eb86..b252efe76c3 100644 --- a/packages/services/service-automation/src/suspended-run-store.ts +++ b/packages/services/service-automation/src/suspended-run-store.ts @@ -727,6 +727,7 @@ export class ObjectStoreSuspendedRunStore implements SuspendedRunStore { private async writeTerminal(record: RunRecord): Promise { const now = new Date().toISOString(); const id = HISTORY_PREFIX + record.runId; + const snapshot = serializeConsumedSuspension(record.consumedSuspension, this.logger); const row = { id, // [#10101, the cloud#1395 Option A ruling] SUBJECT first, actor second: @@ -808,7 +809,13 @@ export class ObjectStoreSuspendedRunStore implements SuspendedRunStore { // `node_type` rides along because the resume authority gate (#3801) keys // on it: a suspension restored without it is one a `resumeAuthority` // check can only fall back on the live flow for. - ...serializeConsumedSuspension(record.consumedSuspension, this.logger), + ...snapshot, + // The body the run ran, by content (`RunRecord.flowChecksum`), on every + // terminal row, so a finished run still says which body it ran. A + // strand's row carries its snapshot's pin instead, the body a restore + // re-arms the pause on (#28405); it is never read back as the run's + // identity (`readTerminalFlowChecksum`). + flow_checksum: snapshot.flow_checksum ?? record.flowChecksum ?? null, }; const existing = await this.engine.find(TABLE, { where: { id }, limit: 1, context: SYSTEM_CTX, @@ -926,6 +933,10 @@ export class ObjectStoreSuspendedRunStore implements SuspendedRunStore { // say", which is a different and false statement. refusalMessage: row.refusal_message ?? undefined, nodeId: row.node_id ?? undefined, + // The body the run ran, by content (`RunRecord.flowChecksum`); none on + // a row written before terminal rows carried it, and none on a strand's + // row, whose column is the consumed pause's pin for a restore. + flowChecksum: readTerminalFlowChecksum(row), organizationId: row.organization_id ?? null, userId: row.user_id ?? undefined, // #7533 — read the trigger columns back. `?? undefined` (not `?? ''`): @@ -1155,6 +1166,21 @@ function readFlowChecksum(row: any): string | undefined { return typeof row.flow_checksum === 'string' && row.flow_checksum !== '' ? row.flow_checksum : undefined; } +/** + * A terminal row's `RunRecord.flowChecksum`: its `flow_checksum`, except on a + * row that carries a consumed suspension or its drop notice (`variables_json`, + * which nothing but that path writes on a terminal row — the discriminator + * {@link deserializeConsumedSuspension} keys on). There the column is the + * pause's pin, which a restore re-arms, not the body the run ran: a run that + * lost its pinned body and parked again on another is pinned to the other. + * A strand records no identity, as the engine's record of it carries none + * (`runRecordFlowChecksum`), so both stores answer alike. + */ +function readTerminalFlowChecksum(row: any): string | undefined { + if (row.variables_json != null && row.variables_json !== '') return undefined; + return readFlowChecksum(row); +} + /** * [#32284] A paused row's (or a consumed snapshot's) wait clock, as * `SuspendedRun.activeMs` — nothing for a row written before the column diff --git a/packages/services/service-automation/src/sys-automation-run.object.ts b/packages/services/service-automation/src/sys-automation-run.object.ts index e8a180bbe77..f158ace225f 100644 --- a/packages/services/service-automation/src/sys-automation-run.object.ts +++ b/packages/services/service-automation/src/sys-automation-run.object.ts @@ -176,9 +176,12 @@ export const SysAutomationRun = ObjectSchema.create({ // continues on the body with this identity, not on the definition // registered under `flow_name` now; `flow_version` stays the author's // display number. Nullable: a row written before this column reads as "no - // identity" and resumes on the registered definition, as before. On a - // terminal row it is written only beside a consumed suspension (the - // snapshot columns below), so a restore re-arms the pause pinned to it. + // identity" and resumes on the registered definition, as before. A + // terminal row carries the body the run ran (`RunRecord.flowChecksum`, + // `run-flow-checksum.ts`), so a finished run still says which body it ran + // after a restart; beside a consumed suspension (the snapshot columns + // below) it is that snapshot's pin, so a restore re-arms the pause pinned + // to it. flow_checksum: Field.text({ label: 'Flow Checksum', required: false, diff --git a/packages/spec/src/contracts/approval-service.ts b/packages/spec/src/contracts/approval-service.ts index 9f1d4fdc2c0..8245c84036c 100644 --- a/packages/spec/src/contracts/approval-service.ts +++ b/packages/spec/src/contracts/approval-service.ts @@ -397,7 +397,9 @@ export interface ApprovalRequestRow { * * - `step` — the run's latest request, when that is a later one than * this request: a request of the same `flow_run_id` opened after this - * one, on any node (a later round of this request's own node too). A + * one was decided, on any node (a later round of this request's own node + * too). A request of the run opened while this one was still pending (a + * node that fans out to two approval steps) is not a later one. A * pending one wins over a decided one. Absent when no later request was * opened in that run, so the approval stands at this request as far as * the run's own requests tell. A request a `subflow` body or a `map` @@ -413,15 +415,22 @@ export interface ApprovalRequestRow { * its regions included (a child run started from it may have opened * requests, after this one too, that the run's own requests do not * show), and the run has stopped for good. The body the run ran is - * known only when the body armed now is the flow's newest registration - * and was registered before the run started; a flow edited, rolled back - * or re-registered since the run started is not judged by its current - * body. When `status` is not `pending`, it is then the last decision the - * record's approval took. `false` means "not known to have stopped": - * the run is still going, is a child run, ran a body that can start a - * child run, ran a body that is not known (its flow was registered - * again since it started), was opened before the platform recorded - * which runs are root runs, or cannot be read. + * known only by its content: the run's durable record names the + * content checksum of the body it ran, and the body armed now has the + * same checksum. A restart, another server, or the same content + * registered again keeps the answer; a body armed now with other + * content (an edit, a rollback, an edit one server received before or + * after another) is never judged in the run's place, however its + * registration is timed. When `status` is not `pending`, it is then the + * last decision the record's approval took. `false` means "not known to + * have stopped": the run is still going, is a child run, ran a body that + * can start a child run, ran a body other than the one armed now, + * recorded no checksum (it finished before runs kept one, its body could + * not be hashed, it was parked before runs kept one and its pause pinned + * none, it resumed on another body when the one it started on could no + * longer be found, or it failed after a resume and can still be + * restored), was opened before the platform recorded which runs are root + * runs, or cannot be read. * * Absent when nothing past this request is known: no later request was * opened and the approval is not known to have ended, or several later