Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions .changeset/37218-approval-ended-durable-witness.md
Original file line number Diff line number Diff line change
@@ -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.
19 changes: 13 additions & 6 deletions content/docs/automation/approvals.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
28 changes: 28 additions & 0 deletions packages/plugins/plugin-approvals/src/approval-route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
});
});
26 changes: 17 additions & 9 deletions packages/plugins/plugin-approvals/src/approval-route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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<RouteRequestRow>,
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 });
}
}
Expand Down Expand Up @@ -208,7 +216,7 @@ export function routeOutcome(
* names no node.
*/
export function flowRoute(
row: Pick<ApprovalRequestRow, 'id' | 'flow_node_id' | 'created_at' | 'status'>,
row: Pick<ApprovalRequestRow, 'id' | 'flow_node_id' | 'created_at' | 'completed_at' | 'status'>,
flow: RouteFlowGraph,
runRows: ReadonlyArray<RouteRequestRow>,
label: RouteStepLabel,
Expand Down
77 changes: 37 additions & 40 deletions packages/plugins/plugin-approvals/src/approval-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<string | undefined>;
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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -14929,53 +14939,40 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
labels?.stepLabel(flowName, nodeId) ?? (nodesById.get(nodeId)?.label || stored.get(nodeId) || nodeId);
const runRoot = parseJson<any>(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 */ }
}

/**
* [#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<boolean> {
private async runHasEnded(runId: string, flow: unknown): Promise<boolean> {
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<boolean> {
return runRanArmedBody(this.automation, runId, flow);
}

async listActions(requestId: string, context: ExecutionContext): Promise<ApprovalActionRow[]> {
Expand Down
Loading
Loading