From 13731a0582160855a25b0e61a57ff25247eddc5e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 14:56:12 +0000 Subject: [PATCH 01/23] chore(approvals): carry the plugin half of the reworked reconciler as it stood at 46ca8ff561 The starting point of the plugin-core rebuild; the cases that follow are red on this tree. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jSFBvAjuff7Brz9Rf9 --- .changeset/37767-reconciler.md | 24 + content/docs/automation/approvals.mdx | 80 +- .../plugins/plugin-approvals.md | 16 +- ...roval-reconciler-37767.integration.test.ts | 667 +++++++++++++ .../plugin-approvals/src/approval-service.ts | 934 +++++++++++++++--- .../plugin-approvals/src/approvals-plugin.ts | 4 + .../src/translations/messages.ts | 22 + .../src/preference-options.ts | 1 + 8 files changed, 1607 insertions(+), 141 deletions(-) create mode 100644 .changeset/37767-reconciler.md create mode 100644 packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts diff --git a/.changeset/37767-reconciler.md b/.changeset/37767-reconciler.md new file mode 100644 index 00000000000..bbc11de84ec --- /dev/null +++ b/.changeset/37767-reconciler.md @@ -0,0 +1,24 @@ +--- +'@objectstack/plugin-approvals': patch +--- + +feat(approvals): the reconciler, and the door reads every run of an approval (ADR-0162 Execution item 8) + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened: `ApprovalService` gains `reconcileMarkedApprovals(options?)`, which the plugin runs on the sweep clock beside the escalation, dead-run and stranded-request sweeps; the `getRun` member of the automation surface the plugin declares types the step log's `childRunIds`, the run's `trigger` and `completedAt`, and an optional `{ strict }` read; the plugin's message catalog gains `approvalFlowNotContinuedTitle` and `approvalFlowNotContinuedBody` in all 11 locale packs, sent to the organization's administrators on the topic `approval.flow_not_continued`. + +Only for an approval the check stamped when it opened (one with a step that can act on an object that declares `closedStates`): + +- **The door reads every run of the approval.** Where it read the run that carries the record and the latest request's own run, it now walks the tree from the run that carries the record, following the child runs each delegating step records: every `subflow` child, and every `map` item run that does not carry another record (an item that is a record carries an approval of its own). One run decides for the whole approval: one that another process is advancing, or that the store could not answer for, makes it cannot tell; one parked at a node a step can follow, in progress; one that ended between two steps, abandoned. So a sibling child whose failure the flow routed, a middle run two levels down that failed, an item run that failed before its step, and a run between two others that is being advanced are no longer read as finished. A failure routed to a pause no step follows is read as abandoned, as on the base. A stop is answered where a request of the approval opened after it. A tree of more than 200 runs is cannot tell. +- **The plugin keeps what it read.** At each door, and as each request opens, the approval's latest request keeps, in its config snapshot, the runs the plugin read, which of them ended (and so are not read again), and a failure between two steps it found in a run that ended. A history the automation engine trims afterwards is not needed again, so an approval whose early child run was trimmed, or whose refused outcome is tried again after its run's history went, is judged as it would have been. +- **A run that stopped, placed by the step last decided.** A run the engine has no row for (its history is gone, or a process stopped while advancing it), and the latest request's own run still parked at the step its decision was recorded on (a process stopped before the run was resumed), are cannot tell for an hour from the approval's marks (the age bound). Past it, they have stopped at the step last decided. Where a later step can follow that step, the approval is abandoned: the record is put back, the submitter is told and submits again, the decisions already made stay on their requests, and the run still parked there is cancelled. At the last step, the outcome is written, the administrators are told that the flow did not go on after that step, and the run's pause is left for an operator. +- **The reconciler.** Each pass reads two windows of at most 200 marked requests (`unjudged_since`): the oldest marks, and the next page of a walk over every marked request by id, so that marks which stay cannot keep the newer ones from being read. It judges each approval among them once, as the door would have: it writes the outcome in the name of the request's recorded decider, abandons the approval, or, where nothing was held back, clears the mark and writes nothing. It ends what no door saw: a run that was cancelled, a parent run cancelled while its child's request was pending, and the stopped runs above. Past the age bound it also reads as stopped where it stood a run that reports paused while its pause is gone, and a run parked at a `subflow` or a `map` whose child run has ended or has no row. +- **A refused write is tried again.** A refused outcome or put-back leaves the marks, and the next pass tries it again. The timeline line and the administrators' notice (keyed per request and status) are left once for one refusal; the same holds for the line an abandoned approval leaves. +- **A deleted record.** Where the approval's record was deleted, the reconciler clears the marks of its requests and writes nothing: no retry and no notice. +- **The stranded-request report** (`inspectStrandedRequests`) leaves a decided request the check stamped to the door and the reconciler, and still reports a returned one. + +- **A refusing end is an end.** The door reads a run that reached an end of the flow as having ended there, a refusing end (`outcome: 'refused'`) included, as it already did for a completed run. + +Unchanged: an object that declares no `closedStates`; an approval that opened before its object declared the key. diff --git a/content/docs/automation/approvals.mdx b/content/docs/automation/approvals.mdx index 3639c51f278..f9a157b1c7a 100644 --- a/content/docs/automation/approvals.mdx +++ b/content/docs/automation/approvals.mdx @@ -1517,7 +1517,8 @@ not swallowed: One more ground is the host's, not the author's. An approval any step of which can act on an object that declares `closedStates`, concerned or not, opens only on a host that runs the approvals plugin's sweeps, which needs a `job` service. -The sweeps are what release a record held by a dead run, below. +The sweeps are what release a record held by a dead run, and what judge an +approval that no action judged, below. ### An approval that does not mirror onto the closing field @@ -1590,9 +1591,14 @@ request stays the rule. These are left to the first request: Three writers abandon a request: its submitter's recall, of a pending request or of a returned one in its revise window; an administrator's override of a pending request, the override arm of the same recall; and the sweep that releases a -record held by a dead run. Each records `recalled` on the request. Where the -object closes on the mirror field at any value, one of its own or a status, an -abandoned request never writes a closed value of that field: +record held by a dead run. Each records `recalled` on the request. The platform +also abandons an approval whose run ended between two steps, below, at the +action that found it or in the reconciler: the requests keep the decisions +already made, a line with no actor on the latest request's timeline says that +the approval did not go on, why, and what the record was put back to, and the +submitter is told, and submits again. Where the object closes on the mirror +field at any value, one of its own or a status, an abandoned request never +writes a closed value of that field: 1. **A closed value the approval did not write is left alone.** Where the field holds a closed value that no request of this approval on this record had as @@ -1624,6 +1630,72 @@ write of empty is refused: the field keeps the value it holds, and the refusal i logged, and reported as above where the object closes on the field at `approved` or `rejected`. +### When the outcome lands on the record + +Where the object closes on a step's mirror field at `approved` or `rejected`, +the step's decision is held back: the request records it, and the field keeps +`pending` until the approval is over for the record. Every other status is +written as before: `pending` as a request opens, `returned` at a send-back, and +what an abandoned request leaves. + +After each action that moves a run of the approval on (a decision, by a person +or by the escalation clock, a send-back, a resubmission, a recall, and the +continuation of a restored run), the platform reads the approval's requests on +the record and every run of the approval: the run that carries the record and, +through the steps that started them, every `subflow` child under it, and every +`map` item run that does not carry another record (an item that is a record has +an approval of its own). It answers one of: + +- **In progress.** A request is pending or returned on the record, or a run is + parked at a node between two steps. Nothing is written. +- **Ended between two steps.** A run stopped on a node a step could still follow + (it failed or was cancelled there), a failure the flow routed at the top level + of a run ended it, to an end or to a pause no step follows, or a later step + could not open, and no request of the approval opened after it. The approval + is abandoned, above. +- **Cannot tell.** A run is being advanced by another process, the store did + not answer for a run, or the requests cannot be read. Nothing is written. +- **Finished**, otherwise: every run reached an end of the flow, a refusing end + included, stopped after the last step, or is parked at a pause no step can + follow. The latest request's decision is written, in the name of the person + who decided it. + +The platform keeps what it read on the approval's own requests, at each of these +actions and as each request opens: which runs it read, which of them ended, and a +failure between two steps it found in one. A run that ended is not read again, +so a flow run history the platform trims later, as it trims every flow's history, +does not hold the approval. + +Two more states cannot tell at first: a run with no history left to read, which +the platform never read to its end (a process stopped while it was advancing +it), and a decided request whose run is still parked at that request's own step +(a process stopped before the run was resumed). An hour after the approval's +marks were set, either has stopped at the step last decided. Where a later step +could follow that step, the approval is abandoned, above, and a run still parked +there is cancelled, so nothing resumes it; the decisions already made stay on +their requests, and the submitter submits again. Where the step was the last, +its decision is written, the organization's administrators are told that the +flow did not go on after that step (the notice `approval.flow_not_continued`), +and the run's pause is left, so that an operator can continue the flow's +remaining nodes or cancel the run. + +Every decision on an approval any step of which can act on an object that +declares `closedStates` leaves a mark on its request (`unjudged_since`), also +where nothing is held back. The mark is cleared once the approval is judged, or +when its next request opens. The plugin's sweeps run a reconciler that judges +every approval whose mark still stands, as the action would have: after a run +that was cancelled, a parent run cancelled while its child's request was pending, +or a process that stopped, as above. Each sweep reads the oldest marks and the +next page of a walk over every marked request, so that approvals that stay in +progress do not keep the newer ones from being judged. Once the mark has stood +for an hour, it also reads as stopped where it stood a run that reports paused +while its pause is gone, and a run parked at a `subflow` or a `map` whose child +run has ended or has no history left. +Where nothing was held back it clears the mark and writes nothing. A write that +a rule or a hook refuses is reported as above, once, and tried again on each +sweep while the mark stands. Where the record was deleted, the reconciler clears +the mark and writes nothing. + ## Why Separating *who configures* from *who approves* from *as whom it runs* is the same capability/assignment/requirement decoupling as the rest of authorization (ADR-0066). The `runAs` default of `user` means an approval flow can't silently grant the submitter cross-tenant or cross-owner reach — elevation is opt-in and auditable. That is the safe-by-default posture: the common case respects RLS; the elevated case is explicit. 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 607d59f8519..45b009061f5 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 | 49 | -| Object name statically decidable | 47 | +| Write call sites | 50 | +| Object name statically decidable | 48 | | Object name chosen at run time | 2 | -| Object name spelled inline | 45 | +| Object name spelled inline | 46 | | 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 | 47 | +| Against a tenancy-enabled object | 48 | | Against an object declaring tenancy off | 0 | -| Threading a tenant context | 49 | +| Threading a tenant context | 50 | | 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 | 47 | +| Threading a decidably elevated (`isSystem`) context | 48 | | Threading a decidably non-elevated context | 0 | | Threading a context of undecidable elevation | 2 | -| Receiver carried a readable engine type | 49 | +| Receiver carried a readable engine type | 50 | | 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 | @@ -54,7 +54,7 @@ a row or a number here — fix the code, or the census, and regenerate. | `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 | -| `packages/plugins/plugin-approvals/src/approval-service.ts` | `update` | `sys_approval_request` | enabled | elevated | 14 | +| `packages/plugins/plugin-approvals/src/approval-service.ts` | `update` | `sys_approval_request` | enabled | elevated | 15 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_token` | enabled | elevated | 1 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `update` | `sys_approval_token` | enabled | elevated | 1 | | `packages/plugins/plugin-approvals/src/backfill-platform-row-organizations.ts` | `update` | `objectPlan.object` | undecidable | context, elevation undecidable | 1 | diff --git a/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts new file mode 100644 index 00000000000..bf73aaf22ec --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts @@ -0,0 +1,667 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5, Execution item 8 "The reconciler", #37767 piece 4] The door + * reads every run of an approval's tree, and the reconciler judges every + * approval whose mark no door cleared. + * + * The door follows the child runs each delegating step records + * (`childRunIds`): a sibling `subflow` child, a middle run two levels down, + * a run another process is advancing. The reconciler scans the mark oldest + * first and judges each approval as the door would have: a parent run that + * was cancelled while its child's request was pending, a process that died + * between a decision and the write of its outcome, an approval whose field + * the object does not close on, a record deleted in a passage, and, past + * the age bound, a run whose pause is gone and a run parked at a `subflow` + * whose child has ended. + * + * 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 { APPROVAL_REVISE_NODE_TYPE } from '@objectstack/spec/automation'; +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, RECONCILER_AGE_BOUND_MS } from './approval-service.js'; +import { registerApprovalNode } from './approval-node.js'; +import { SysApprovalRequest } from './sys-approval-request.object.js'; +import { SysApprovalAction } from './sys-approval-action.object.js'; +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. */ +const invoice = { name: 'crm_invoice', label: 'Invoice', fields, closedStates: { approval_status: ['approved', 'rejected'] } }; +/** Closes on `approved` alone: a rejected order moves on. */ +const order = { name: 'crm_order', label: 'Order', fields, closedStates: { approval_status: ['approved'] } }; +/** Closes on `rejected` alone: an approved claim moves on. */ +const claim = { name: 'crm_claim', label: 'Claim', fields, closedStates: { approval_status: ['rejected'] } }; +/** Declares closed states, on another field than the approval's: its approval holds nothing back. */ +const ticket = { name: 'crm_ticket', label: 'Ticket', fields, closedStates: { stage: ['done'] } }; +/** Declares no closed state: the control, which behaves as before. */ +const memo = { name: 'crm_memo', label: 'Memo', fields }; + +const step = (id: string, approver: string, extra: Record = {}) => ({ + id, type: 'approval', label: id, + config: { approvers: [{ type: 'user', value: approver }], approvalStatusField: 'approval_status', ...extra }, +}); +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, type?: string) => + ({ id: `${source}_${target}_${label ?? type ?? ''}`, source, target, ...(label ? { label } : {}), ...(type ? { type } : {}) }); +const flow = (name: string, nodes: unknown[], edges: unknown[], extra: Record = {}) => + ({ name, label: name, type: 'autolaunched', nodes: [START, ...nodes, END], edges, ...extra }); +/** `a` then `b`, each step's reject edge to the end. */ +const decided = (a: string, b: string) => [edge(a, b, 'approve'), edge(a, 'end', 'reject')]; + +/** A start node whose condition never holds: the flow is skipped and starts no run. */ +const GATED_START = { id: 'start', type: 'start', label: 'Start', config: { condition: '1 == 2' } }; +const WAIT = { id: 'hold', type: 'wait', label: 'Hold', waitEventConfig: { eventType: 'timer', timerDuration: 'PT1H' } }; + +const FLOWS = [ + // [M1] A child flow its start condition skips: the call starts no run. + { name: 'child_gated', label: 'child_gated', type: 'autolaunched', nodes: [GATED_START, mark('noop'), END], edges: [edge('start', 'noop'), edge('noop', 'end')] }, + flow('gated_sub_between', [step('first', 'approver'), { id: 'gate', type: 'subflow', label: 'Gate', config: { flowName: 'child_gated' } }, step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'gate', 'approve'), edge('first', 'end', 'reject'), edge('gate', 'second'), ...decided('second', 'end')]), + // [ruling A3] A child that ends before the first step opens. + flow('child_noop', [mark('noop')], [edge('start', 'noop'), edge('noop', 'end')]), + flow('early_sub_two_step', [{ id: 'prep', type: 'subflow', label: 'Prepare', config: { flowName: 'child_noop' } }, step('first', 'approver'), step('second', 'approver2')], + [edge('start', 'prep'), edge('prep', 'first'), ...decided('first', 'second'), ...decided('second', 'end')]), + // [M3] A node between the two steps that fails, routed to a pause no step follows. + flow('routed_to_wait', [step('first', 'approver'), mark('boom'), WAIT, step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'boom', 'approve'), edge('first', 'end', 'reject'), edge('boom', 'second'), + edge('boom', 'hold', undefined, 'fault'), edge('hold', 'end'), ...decided('second', 'end')]), + // [S3] A map item run that holds no request: its node fails before the item's step, routed to its end. + flow('first_then_items', [step('first', 'approver'), { id: 'each', type: 'map', label: 'Each', config: { flowName: 'child_boom_then_step', collection: [1] } }], + [edge('start', 'first'), edge('first', 'each', 'approve'), edge('first', 'end', 'reject'), edge('each', 'end')]), + flow('child_one_step', [step('only', 'approver')], [edge('start', 'only'), edge('only', 'end', 'approve'), edge('only', 'end', 'reject')]), + // A sibling child after the child that holds the first step: a node that + // fails before its step, routed to the child's end. + flow('child_boom_then_step', [mark('boom'), step('second', 'approver2')], + [edge('start', 'boom'), edge('boom', 'second'), edge('boom', 'end', undefined, 'fault'), ...decided('second', 'end')]), + flow('parent_two_subs', [ + { id: 'sub1', type: 'subflow', label: 'First', config: { flowName: 'child_one_step' } }, + { id: 'sub2', type: 'subflow', label: 'Second', config: { flowName: 'child_boom_then_step' } }], + [edge('start', 'sub1'), edge('sub1', 'sub2'), edge('sub2', 'end')]), + // Two levels down: the root delegates to a middle run, which delegates the + // first step and holds the second after a node that fails, unrouted. + flow('middle_boom', [{ id: 'inner', type: 'subflow', label: 'Inner', config: { flowName: 'child_one_step' } }, mark('boom'), step('second', 'approver2')], + [edge('start', 'inner'), edge('inner', 'boom'), edge('boom', 'second'), ...decided('second', 'end')]), + flow('root_of_middle', [{ id: 'mid', type: 'subflow', label: 'Middle', config: { flowName: 'middle_boom' } }], + [edge('start', 'mid'), edge('mid', 'end'), edge('mid', 'end', undefined, 'fault')]), + // A child step, then a step in the parent. + flow('sub_then_second', [{ id: 'sub', type: 'subflow', label: 'Approval', config: { flowName: 'child_one_step' } }, step('second', 'approver2')], + [edge('start', 'sub'), edge('sub', 'second'), ...decided('second', 'end')]), + // A node between the two steps that fails, unrouted: the run fails there. + flow('boom_between', [step('first', 'approver'), mark('boom'), step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'boom', 'approve'), edge('first', 'end', 'reject'), edge('boom', 'second'), ...decided('second', 'end')]), + flow('two_step', [step('first', 'approver'), step('second', 'approver2')], + [edge('start', 'first'), ...decided('first', 'second'), ...decided('second', 'end')]), + // A send-back past the limit auto-rejects the second step, whose reject + // edge runs a node that fails before the third step, routed to the end. + flow('spent_then_boom', [step('first', 'approver'), step('second', 'approver2', { maxRevisions: 0 }), + { id: 'revise', type: APPROVAL_REVISE_NODE_TYPE, label: 'Revise' }, mark('boom'), step('third', 'approver')], + [edge('start', 'first'), ...decided('first', 'second'), edge('second', 'third', 'approve'), edge('second', 'boom', 'reject'), + edge('second', 'revise', 'revise'), { id: 'back', source: 'revise', target: 'second', label: 'resubmit', type: 'back' }, + edge('boom', 'third'), edge('boom', 'end', undefined, 'fault'), ...decided('third', 'end')]), +]; + +describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges what no door did', () => { + let kernel: ObjectKernel; + let ql: ObjectQL; + let automation: AutomationEngine; + let svc: ApprovalService; + /** Nodes of type `mark` that throw, by id. */ + let throwOn: Set; + /** What each `read` node saw on the record's field. */ + let seen: unknown[]; + let notices: Array<{ topic: string; audience: string[] }>; + let infos: string[]; + + afterEach(async () => { + try { await kernel?.shutdown(); } catch { /* noop */ } + }); + + beforeEach(async () => { + throwOn = new Set(); + seen = []; + 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, order, claim, ticket, memo, 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: () => {} }; + infos = []; + const heard = { ...quiet, info: (m: unknown) => { infos.push(String(m)); } }; + svc = new ApprovalService({ engine: ql, logger: heard 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, _variables: any, context: any) { + if (throwOn.has(node.id)) throw new Error(`${node.id} failed`); + if (node.id === 'read') { + const id = context?.record?.id; + seen.push((await ql.find(context?.object ?? 'crm_invoice', { where: { id }, context: SYS }))[0]?.approval_status); + } + return { success: true }; + }, + }); + for (const f of FLOWS) automation.registerFlow(f.name, f as any); + }); + + const read = async (object: string, id: string) => (await ql.find(object, { where: { id }, context: SYS }))[0]; + const field = async (object: string, id: string) => (await read(object, 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 marks = async (id: string) => (await requestsOn(id)).map((r) => r.unjudged_since != null); + const pendingOn = async (id: string) => (await requestsOn(id)).find((r) => r.status === 'pending' || r.status === 'returned'); + 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) => [a.action, a.actor_id ?? null, a.comment ?? null]); + const seed = (object: string, id: string) => + ql.insert(object, { id, name: id, organization_id: ORG }, { context: { isSystem: true, tenantId: ORG } }); + const start = async (name: string, object: string, id: string) => { + await seed(object, id); + return automation.execute(name, { object, record: await read(object, id), userId: 'owner' } as any) as Promise; + }; + const decide = async (id: string, decision: 'approve' | 'reject', who: string) => + svc.decide(String((await requestsOn(id)).find((r) => r.status === 'pending').id), { decision, actorId: who, ...(decision === 'reject' ? { comment: 'no' } : {}) } as any, asPerson(who)); + const settle = (p: Promise) => p.then((v) => ({ ok: v as T }), (e: any) => ({ error: e as Error })); + + + /** 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; } + }; + /** Move every mark on the record's requests past the reconciler's age bound. */ + const age = async (id: string) => { + const past = new Date(Date.now() - 2 * RECONCILER_AGE_BOUND_MS).toISOString(); + for (const r of await requestsOn(id)) { + if (r.unjudged_since != null) await ql.update('sys_approval_request', { id: r.id, unjudged_since: past }, { context: SYS }); + } + }; + const recordWrites = (object: string) => { + const writes: unknown[] = []; + const original = ql.update.bind(ql); + (ql as any).update = async (o: string, data: any, options?: any) => { + if (o === object && 'approval_status' in (data ?? {})) writes.push([data.approval_status, options?.context?.userId ?? null]); + return original(o, data, options); + }; + return writes; + }; + + describe('the door reads every run of the approval', () => { + it('a sibling subflow child whose node failed before its step, routed to its end: abandoned, not finished', async () => { + await start('parent_two_subs', 'crm_invoice', 'i_sib'); + throwOn.add('boom'); + await decide('i_sib', 'approve', 'approver'); + const [first] = await requestsOn('i_sib'); + expect((await automation.getRun(String(first.record_run_id)))?.status, 'the carrying run completed').toBe('completed'); + expect(await steps('i_sib'), 'the second step was never asked').toEqual([['only', 'approved']]); + expect(await field('crm_invoice', 'i_sib')).toBe('recalled'); + expect((await timeline(String(first.id))).at(-1)![2]).toMatch(/its node 'boom' failed between two steps/); + expect(await marks('i_sib')).toEqual([false]); + }); + + it('the delegating steps record the child runs they started', async () => { + await start('parent_two_subs', 'crm_invoice', 'i_links'); + await decide('i_links', 'approve', 'approver'); + const [first] = await requestsOn('i_links'); + const root: any = await automation.getRun(String(first.record_run_id)); + const sub1 = root.steps.filter((s: any) => s.nodeId === 'sub1'); + expect(sub1.length).toBeGreaterThan(0); + for (const s of sub1) expect(s.childRunIds).toEqual([String(first.flow_run_id)]); + const sub2 = root.steps.find((s: any) => s.nodeId === 'sub2'); + expect(sub2.childRunIds).toHaveLength(1); + expect(sub2.childRunIds[0]).not.toBe(String(first.flow_run_id)); + expect(root.steps.find((s: any) => s.nodeId === 'start').childRunIds).toBeUndefined(); + }); + + it('a middle run, two levels down, that failed between two steps: abandoned', async () => { + await start('root_of_middle', 'crm_invoice', 'i_mid'); + throwOn.add('boom'); + await settle(decide('i_mid', 'approve', 'approver')); + const [first] = await requestsOn('i_mid'); + expect(await steps('i_mid')).toEqual([['only', 'approved']]); + expect(await field('crm_invoice', 'i_mid')).toBe('recalled'); + expect((await timeline(String(first.id))).at(-1)![2]).toMatch(/ended failed at node 'boom', between two steps/); + }); + + it('a middle run another process is advancing: nothing is written, and the mark stays', async () => { + await start('root_of_middle', 'crm_invoice', 'i_mid_busy'); + const [first] = await requestsOn('i_mid_busy'); + const root: any = await automation.getRun(String(first.record_run_id)); + const middle = String(root.steps.find((s: any) => s.nodeId === 'mid').childRunIds[0]); + expect(middle).not.toBe(String(first.flow_run_id)); + const original = automation.getRun.bind(automation); + (automation as any).getRun = async (id: string) => { + const run: any = await original(id); + return id === middle ? { ...run, status: 'running' } : run; + }; + throwOn.add('boom'); + await settle(decide('i_mid_busy', 'approve', 'approver')); + expect(await field('crm_invoice', 'i_mid_busy')).toBe('pending'); + expect(await marks('i_mid_busy')).toEqual([true]); + expect(infos.some((m) => m.includes(`the run '${middle}' is running, so another process may be advancing it`))).toBe(true); + }); + + it('an abandoned auto-rejection sends the abandoned notice and no auto-rejected one', async () => { + await start('spent_then_boom', 'crm_invoice', 'i_spent'); + await decide('i_spent', 'approve', 'approver'); + throwOn.add('boom'); + const second = await pendingOn('i_spent'); + notices.length = 0; + const out: any = await svc.sendBack(String(second.id), { actorId: 'approver2' } as any, asPerson('approver2')); + expect(out.autoRejected).toBe(true); + expect(await field('crm_invoice', 'i_spent')).toBe('recalled'); + expect(notices.filter((n) => n.topic === 'approval.abandoned').map((n) => n.audience)).toEqual([['owner']]); + expect(notices.some((n) => n.topic === 'approval.returned'), 'no auto-rejected notice').toBe(false); + }); + }); + + describe('the reconciler', () => { + it('a parent run cancelled while its child\'s request is pending, which no door judged: abandoned', async () => { + await start('sub_then_second', 'crm_invoice', 'i_cancel'); + const [child] = await requestsOn('i_cancel'); + await automation.cancelRun(String(child.record_run_id)); + await withoutDoor(() => settle(decide('i_cancel', 'approve', 'approver'))); + expect(await field('crm_invoice', 'i_cancel'), 'held: no door judged').toBe('pending'); + expect(await marks('i_cancel')).toEqual([true]); + + const out = await svc.reconcileMarkedApprovals(); + expect(out.judged).toEqual({ abandoned: 1 }); + expect(await steps('i_cancel')).toEqual([['only', 'approved']]); + expect(await field('crm_invoice', 'i_cancel')).toBe('recalled'); + expect(await marks('i_cancel')).toEqual([false]); + expect((await svc.reconcileMarkedApprovals()).scanned, 'nothing left to judge').toBe(0); + }); + + it('a process that died between the last decision and the write of its outcome: written in the decider\'s name', async () => { + await start('two_step', 'crm_invoice', 'i_died'); + await decide('i_died', 'approve', 'approver'); + await withoutDoor(() => decide('i_died', 'approve', 'approver2')); + expect(await field('crm_invoice', 'i_died')).toBe('pending'); + expect(await marks('i_died')).toEqual([false, true]); + + const writes = recordWrites('crm_invoice'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(writes).toEqual([['approved', 'approver2']]); + expect(await field('crm_invoice', 'i_died')).toBe('approved'); + expect(await marks('i_died')).toEqual([false, false]); + }); + + it('a refused outcome is tried again while the mark stands, noted once and told under one key', async () => { + await start('two_step', 'crm_invoice', 'i_refuse'); + await decide('i_refuse', 'approve', 'approver'); + await withoutDoor(() => decide('i_refuse', 'approve', 'approver2')); + const original = ql.update.bind(ql); + let refuse = true; + (ql as any).update = async (o: string, data: any, options?: any) => { + if (refuse && o === 'crm_invoice' && data?.approval_status === 'approved') throw new Error('VALIDATION_FAILED: a rule of the app'); + return original(o, data, options); + }; + (svc as any).organizationAdministrators = async () => ({ ids: ['org_admin'] }); + const keys: unknown[] = []; + svc.attachMessaging({ emit: async (n: any) => { if (n.topic === 'approval.status_mirror_refused') keys.push([n.audience, n.dedupKey]); } } as any); + await svc.reconcileMarkedApprovals(); + await svc.reconcileMarkedApprovals(); + expect(await field('crm_invoice', 'i_refuse')).toBe('pending'); + expect(await marks('i_refuse')).toEqual([false, true]); + const [, last] = await requestsOn('i_refuse'); + // The notice is keyed per request and status, so the messaging service sends it once. + expect(keys).toEqual([[['org_admin'], `approval-mirror-refused-${last.id}-approved`], [['org_admin'], `approval-mirror-refused-${last.id}-approved`]]); + const lines = (await timeline(String(last.id))).filter(([, actor, text]) => actor === null && /could not|NOT|refused/i.test(String(text))); + expect(lines, 'the refusal is noted on the timeline once').toHaveLength(1); + + refuse = false; + await svc.reconcileMarkedApprovals(); + expect(await field('crm_invoice', 'i_refuse')).toBe('approved'); + expect(await marks('i_refuse')).toEqual([false, false]); + }); + + it('an approval whose field the object does not close on: the hold ends, the mark is cleared and nothing is written', async () => { + await start('two_step', 'crm_ticket', 't_died'); + await decide('t_died', 'approve', 'approver'); + await withoutDoor(() => decide('t_died', 'approve', 'approver2')); + expect(await field('crm_ticket', 't_died'), 'written at once, as on main').toBe('approved'); + expect(await marks('t_died')).toEqual([false, true]); + + const writes = recordWrites('crm_ticket'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(writes).toEqual([]); + expect(await marks('t_died')).toEqual([false, false]); + }); + + it('a record deleted in a passage: the marks are cleared once, with nothing written and no notice', async () => { + await start('two_step', 'crm_invoice', 'i_gone'); + await decide('i_gone', 'approve', 'approver'); + await withoutDoor(() => decide('i_gone', 'approve', 'approver2')); + await ql.delete('crm_invoice', { where: { id: 'i_gone' }, context: SYS } as any); + expect(await read('crm_invoice', 'i_gone')).toBeUndefined(); + notices.length = 0; + + const out = await svc.reconcileMarkedApprovals(); + expect(out.deletedRecords).toBe(1); + expect(out.judged).toEqual({}); + expect(await marks('i_gone')).toEqual([false, false]); + expect(notices).toEqual([]); + expect((await svc.reconcileMarkedApprovals()).scanned, 'cleared once: not scanned again').toBe(0); + }); + + it('past the age bound, a run that reports paused while its pause is gone stopped where it stood: abandoned', async () => { + await start('two_step', 'crm_invoice', 'i_lost'); + const [first] = await requestsOn('i_lost'); + // The shape a process that died after the decision's row landed and as + // its run's pause was consumed leaves: decided, marked, and a run that + // reports paused with no pause. + await ql.update('sys_approval_request', { id: first.id, status: 'approved', unjudged_since: new Date().toISOString() }, { context: SYS }); + const runId = String(first.flow_run_id); + const suspensionOf = (automation as any).suspensionOf.bind(automation); + (automation as any).suspensionOf = async (id: string) => (id === runId ? undefined : suspensionOf(id)); + expect((await automation.getRun(runId))?.status).toBe('paused'); + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound: cannot tell').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_lost')).toBe('pending'); + expect(await marks('i_lost')).toEqual([true]); + + await age('i_lost'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ abandoned: 1 }); + expect(await field('crm_invoice', 'i_lost')).toBe('recalled'); + expect((await timeline(String(first.id))).at(-1)![2]).toMatch(/reports paused at a pause that is gone, so it will not go on, between two steps\./); + expect(await marks('i_lost')).toEqual([false]); + }); + + it('past the age bound, a run parked at a subflow whose child has ended, which nothing will resume: abandoned', async () => { + await start('sub_then_second', 'crm_invoice', 'i_orphan'); + const [child] = await requestsOn('i_orphan'); + // The child's step was decided and its run ended, and the parent was never resumed. + await ql.update('sys_approval_request', { id: child.id, status: 'approved', unjudged_since: new Date().toISOString() }, { context: SYS }); + await automation.cancelRun(String(child.flow_run_id)); + expect((await automation.getRun(String(child.record_run_id)))?.status).toBe('paused'); + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound: the parent is parked between two steps').toEqual({ in_progress: 1 }); + expect(await marks('i_orphan')).toEqual([true]); + + await age('i_orphan'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ abandoned: 1 }); + expect(await field('crm_invoice', 'i_orphan')).toBe('recalled'); + expect((await timeline(String(child.id))).at(-1)![2]).toMatch(/parked at 'sub' on a child run that has ended, so nothing will resume it, between two steps\./); + expect(await marks('i_orphan')).toEqual([false]); + }); + + it('scans the oldest mark first, and at most its limit in each of its two windows', async () => { + for (const id of ['i_a', 'i_b']) { + await start('two_step', 'crm_invoice', id); + await decide(id, 'approve', 'approver'); + await withoutDoor(() => decide(id, 'approve', 'approver2')); + } + await age('i_b'); + const out = await svc.reconcileMarkedApprovals({ limit: 1 }); + expect(out.scanned).toBeLessThanOrEqual(2); + expect(await field('crm_invoice', 'i_b'), 'the older mark').toBe('approved'); + }); + + it('the stranded-request report leaves a stamped request to the reconciler, and still reports an unstamped one', async () => { + throwOn.add('boom'); + await start('boom_between', 'crm_invoice', 'i_report'); + await settle(decide('i_report', 'approve', 'approver')); + await start('boom_between', 'crm_memo', 'm_report'); + await settle(decide('m_report', 'approve', 'approver')); + const [stamped] = await requestsOn('i_report'); + const [unstamped] = await requestsOn('m_report'); + expect((await automation.getRun(String(stamped.flow_run_id)))?.status).toBe('failed'); + expect(stamped.between_steps_json).toBeTruthy(); + expect(unstamped.between_steps_json ?? null).toBeNull(); + const reported = (await svc.inspectStrandedRequests()).stranded.map((r: any) => String(r.requestId)); + expect(reported).toContain(String(unstamped.id)); + expect(reported).not.toContain(String(stamped.id)); + + // [S4] A returned request of a stamped approval (a send-back sets no + // mark, and no judgement places it) is reported as before. + await ql.update('sys_approval_request', { id: stamped.id, status: 'returned' }, { context: SYS }); + const again = (await svc.inspectStrandedRequests()).stranded.map((r: any) => String(r.requestId)); + expect(again).toContain(String(stamped.id)); + }); + + it('[S2] marks that stay cannot hold the head of the scan: a newer approval is still judged', async () => { + // Two approvals that stay in progress, oldest, and a newer one that a process left unjudged. + for (const id of ['i_hold_a', 'i_hold_b']) { + await start('sub_then_second', 'crm_invoice', id); + const [child] = await requestsOn(id); + await ql.update('sys_approval_request', { id: child.id, status: 'approved', unjudged_since: new Date(Date.now() - 1000).toISOString() }, { context: SYS }); + } + await start('two_step', 'crm_invoice', 'i_new'); + await decide('i_new', 'approve', 'approver'); + await withoutDoor(() => decide('i_new', 'approve', 'approver2')); + for (let pass = 0; pass < 3 && (await field('crm_invoice', 'i_new')) !== 'approved'; pass++) { + await svc.reconcileMarkedApprovals({ limit: 1 }); + } + expect(await field('crm_invoice', 'i_new')).toBe('approved'); + expect(await marks('i_hold_a'), 'still in progress').toEqual([true]); + }); + }); + + describe('the rulings on #37767 piece 4 (A3 and B2: one rule), and the fixes of 7255916895', () => { + /** Runs whose history the engine no longer holds: `getRun` answers no row. */ + let trimmed: Set; + let storeDown: Set; + beforeEach(() => { + trimmed = new Set(); + storeDown = new Set(); + const original = automation.getRun.bind(automation); + (automation as any).getRun = async (id: string, options?: { strict?: boolean }) => { + if (storeDown.has(id)) { + if (options?.strict) throw new Error('the run store did not answer'); + return null; + } + return trimmed.has(id) ? null : original(id, options); + }; + (svc as any).organizationAdministrators = async () => ({ ids: ['org_admin'] }); + }); + /** The decision is recorded, and the process stops before the run is resumed. */ + const withoutResume = async (fn: () => Promise): Promise => { + const resume = (svc as any).resumeRecordedOutcome; + (svc as any).resumeRecordedOutcome = async () => { throw new Error('the process stopped'); }; + try { return await fn(); } finally { (svc as any).resumeRecordedOutcome = resume; } + }; + const kept = (r: any) => JSON.parse(String(r.node_config_json ?? '{}')).__runsRead; + const notified = (topic: string) => notices.filter((n) => n.topic === topic).map((n) => n.audience); + + it('[M1] a subflow its child flow skipped names no run, and the approval finishes at the door', async () => { + await start('gated_sub_between', 'crm_invoice', 'i_gated'); + await decide('i_gated', 'approve', 'approver'); + await decide('i_gated', 'approve', 'approver2'); + const [first] = await requestsOn('i_gated'); + const root: any = await automation.getRun(String(first.record_run_id)); + expect(root.steps.find((s: any) => s.nodeId === 'gate').childRunIds).toBeUndefined(); + expect(await field('crm_invoice', 'i_gated')).toBe('approved'); + expect(await marks('i_gated')).toEqual([false, false]); + }); + + it('[M3] a failure between two steps routed to a pause no step follows: abandoned, not finished', async () => { + await start('routed_to_wait', 'crm_invoice', 'i_wait'); + throwOn.add('boom'); + await decide('i_wait', 'approve', 'approver'); + const [first] = await requestsOn('i_wait'); + expect((await automation.getRun(String(first.flow_run_id)))?.status, 'parked at the pause').toBe('paused'); + expect(await steps('i_wait')).toEqual([['first', 'approved']]); + expect(await field('crm_invoice', 'i_wait')).toBe('recalled'); + expect((await timeline(String(first.id))).at(-1)![2]).toMatch(/its node 'boom' failed between two steps/); + }); + + it('[S3] a map item run that holds no request, whose node failed before its step: abandoned', async () => { + await start('first_then_items', 'crm_invoice', 'i_items'); + throwOn.add('boom'); + await decide('i_items', 'approve', 'approver'); + expect(await steps('i_items')).toEqual([['first', 'approved']]); + expect(await field('crm_invoice', 'i_items')).toBe('recalled'); + }); + + it('[A3] a child that ended before the first step is kept as read: its trimmed history does not hold the approval', async () => { + await start('early_sub_two_step', 'crm_invoice', 'i_early'); + const [first] = await requestsOn('i_early'); + const root: any = await automation.getRun(String(first.record_run_id)); + const child = String(root.steps.find((s: any) => s.nodeId === 'prep').childRunIds[0]); + await decide('i_early', 'approve', 'approver'); + const [, second] = await requestsOn('i_early'); + expect(kept(second)?.ended, 'kept as the next request opened').toContain(child); + trimmed.add(child); + await decide('i_early', 'approve', 'approver2'); + expect(await field('crm_invoice', 'i_early'), 'written at the door').toBe('approved'); + expect(await marks('i_early')).toEqual([false, false]); + }); + + it('[A3] a refused outcome tried again after the run that carries the record was trimmed: written, not held', async () => { + await start('two_step', 'crm_invoice', 'i_retry'); + await decide('i_retry', 'approve', 'approver'); + const original = ql.update.bind(ql); + let refuse = true; + (ql as any).update = async (o: string, data: any, options?: any) => { + if (refuse && o === 'crm_invoice' && data?.approval_status === 'approved') throw new Error('VALIDATION_FAILED: a rule of the app'); + return original(o, data, options); + }; + await decide('i_retry', 'approve', 'approver2'); + expect(await field('crm_invoice', 'i_retry')).toBe('pending'); + const [, last] = await requestsOn('i_retry'); + expect(kept(last)?.ended, 'the door kept the run it read to its end').toContain(String(last.record_run_id)); + trimmed.add(String(last.record_run_id)); + refuse = false; + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_retry')).toBe('approved'); + }); + + it('[A3] a run with no row after the last decision: within the bound held, past it written, and the administrators are told', async () => { + await start('two_step', 'crm_invoice', 'i_norow'); + await decide('i_norow', 'approve', 'approver'); + await withoutDoor(() => decide('i_norow', 'approve', 'approver2')); + const [, last] = await requestsOn('i_norow'); + trimmed.add(String(last.record_run_id)); + notices.length = 0; + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound: cannot tell').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_norow')).toBe('pending'); + expect(await marks('i_norow')).toEqual([false, true]); + + await age('i_norow'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_norow'), 'the last step: its decision stands').toBe('approved'); + expect(await marks('i_norow')).toEqual([false, false]); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + }); + + it('[A3] a run with no row after a step a later step follows: past the bound, abandoned', async () => { + await start('two_step', 'crm_invoice', 'i_norow_mid'); + await settle(withoutResume(() => decide('i_norow_mid', 'approve', 'approver'))); + const [first] = await requestsOn('i_norow_mid'); + trimmed.add(String(first.record_run_id)); + await age('i_norow_mid'); + notices.length = 0; + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ abandoned: 1 }); + expect(await steps('i_norow_mid'), 'the decision stays on its request').toEqual([['first', 'approved']]); + expect(await field('crm_invoice', 'i_norow_mid')).toBe('recalled'); + expect(notified('approval.abandoned')).toEqual([['owner']]); + expect(notified('approval.flow_not_continued')).toEqual([]); + }); + + it('[A3] a store that does not answer is not a run with no row: held at any age', async () => { + await start('two_step', 'crm_invoice', 'i_down'); + await decide('i_down', 'approve', 'approver'); + await withoutDoor(() => decide('i_down', 'approve', 'approver2')); + const [, last] = await requestsOn('i_down'); + storeDown.add(String(last.record_run_id)); + await age('i_down'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_down')).toBe('pending'); + expect(await marks('i_down')).toEqual([false, true]); + }); + + it('[B2] a decision whose run was never resumed, at a step a later step follows: past the bound abandoned, and the run cancelled', async () => { + await start('two_step', 'crm_invoice', 'i_parked'); + await settle(withoutResume(() => decide('i_parked', 'approve', 'approver'))); + const [first] = await requestsOn('i_parked'); + expect((await automation.getRun(String(first.flow_run_id)))?.status).toBe('paused'); + expect(await field('crm_invoice', 'i_parked'), 'held at the door').toBe('pending'); + expect(await marks('i_parked')).toEqual([true]); + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound: the run may still be resumed').toEqual({ undetermined: 1 }); + expect(await marks('i_parked')).toEqual([true]); + + await age('i_parked'); + notices.length = 0; + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ abandoned: 1 }); + expect(await steps('i_parked'), 'the decision stays on its request').toEqual([['first', 'approved']]); + expect(await field('crm_invoice', 'i_parked')).toBe('recalled'); + expect(await marks('i_parked')).toEqual([false]); + expect(notified('approval.abandoned')).toEqual([['owner']]); + expect((await automation.getRun(String(first.flow_run_id)))?.status, 'nothing resumes it').toBe('cancelled'); + expect((await timeline(String(first.id))).at(-1)![2]).toMatch(/still parked at the step 'first' its decision was recorded on/); + }); + + it('[B2] a decision whose run was never resumed, at the last step: past the bound written, the administrators told, and the pause left', async () => { + await start('two_step', 'crm_invoice', 'i_parked_last'); + await decide('i_parked_last', 'approve', 'approver'); + await settle(withoutResume(() => decide('i_parked_last', 'approve', 'approver2'))); + const [, last] = await requestsOn('i_parked_last'); + expect(await field('crm_invoice', 'i_parked_last'), 'held at the door').toBe('pending'); + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound').toEqual({ undetermined: 1 }); + + await age('i_parked_last'); + notices.length = 0; + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_parked_last')).toBe('approved'); + expect(await marks('i_parked_last')).toEqual([false, false]); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + expect(notified('approval.abandoned')).toEqual([]); + expect((await automation.getRun(String(last.flow_run_id)))?.status, 'the pause is left for an operator').toBe('paused'); + }); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index b089f84ad54..12e18c216f6 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -370,13 +370,20 @@ export interface ApprovalResumeSurface { * (`ExecutionLogEntry.steps`, which the engine already answers): the door * that judges an approval places where the run stopped, and a failure the * flow routed, against the set the approval's requests carry. A step inside - * a region names its container (`parentNodeId`). - */ - getRun?(runId: string): Promise<{ + * a region names its container (`parentNodeId`). A delegating step names + * the child runs it started (`childRunIds`), which the door reads in turn, + * and a run names the record it carries (`trigger`). The door reads with + * `strict`: a store that does not answer throws, so that it is not taken + * for a run with no row (an engine that does not know the option reads as + * before). + */ + getRun?(runId: string, options?: { strict?: boolean }): Promise<{ status?: string; flowName?: string; startedAt?: string; - steps?: ReadonlyArray<{ nodeId?: string; nodeType?: string; status?: string; parentNodeId?: string; startedAt?: string }>; + completedAt?: string; + trigger?: { object?: string; recordId?: string }; + steps?: ReadonlyArray<{ nodeId?: string; nodeType?: string; status?: string; parentNodeId?: string; startedAt?: string; childRunIds?: readonly string[] }>; } | null>; /** * Whether a suspension still exists for `runId` — the pre-flight that keeps @@ -1857,6 +1864,14 @@ const REFUSED_MIRROR_TOPIC = 'approval.status_mirror_refused'; */ const ABANDONED_APPROVAL_TOPIC = 'approval.abandoned'; +/** + * [ADR-0162 Execution item 8, ruling B2 on #37767] The topic of the notice + * the organization's administrators get when an approval was decided at its + * last step and its outcome written, while its flow was not seen to go on + * after that step. + */ +const FLOW_NOT_CONTINUED_TOPIC = 'approval.flow_not_continued'; + /** * [ADR-0162 Execution item 8] The keys of a request's config snapshot that the * judgement of an approval leaves: the approval was abandoned (`__abandoned`), @@ -1886,9 +1901,12 @@ const REACHED_AN_END: ReadonlySet = new Set(['completed', 'refused']); * `loop`, `parallel` or `try_catch` region), else the last step. An * unrouted failure is the last step a run logs, and a run that was cancelled, * failed by a child's failure or settled as unresumable logs nothing after - * the node it stood on, so the last step names the node in every case; an - * earlier failure that the flow routed on is not where the run stopped. - * `undefined` for a run that reached an `end` ({@link REACHED_AN_END}). + * the node it stood on, so the last step names that node; an earlier failure + * that the flow routed on is not where the run stopped. Two failures log no + * step for the node the run died on: the engine's re-entry guard, and a + * suspension refused inside a region. There the last step logged is the node + * before it, and the run is placed by that node. `undefined` for a run that + * reached an `end` ({@link REACHED_AN_END}). */ function stopOf(log: ReadonlyArray<{ nodeId?: unknown; parentNodeId?: unknown }>, status: string): string | undefined { if (REACHED_AN_END.has(status)) return undefined; @@ -1896,6 +1914,116 @@ function stopOf(log: ReadonlyArray<{ nodeId?: unknown; parentNodeId?: unknown }> return last && typeof last.nodeId === 'string' ? last.nodeId : undefined; } +/** [ADR-0162 Execution item 8] One step of a run's log, as the door reads it. */ +type RunStepRead = { + nodeId?: unknown; nodeType?: unknown; status?: unknown; parentNodeId?: unknown; startedAt?: unknown; childRunIds?: unknown; +}; + +/** + * [ADR-0162 Execution item 8] How many runs one judgement of an approval + * reads, at most. Past it the door answers that it cannot tell, and the + * approval keeps its mark. + */ +const MAX_RUNS_READ_PER_APPROVAL = 200; + +/** + * [ADR-0162 Execution item 8] How long an approval's mark stands before the + * reconciler reads a run that will not move again as stopped where it stood: + * a run that reports paused while its pause is gone, and a run parked at a + * `subflow` or a `map` whose child run has ended. One hour: far past any + * passage a live process completes (a passage is the work between a decision + * and the next step, run in the same call), and short enough that a record a + * dead process left held is released the same working session. + */ +export const RECONCILER_AGE_BOUND_MS = 60 * 60 * 1000; + +/** [ADR-0162 Execution item 8] A child run a step names, and whether a `map` step started it. */ +interface ChildRunRef { + readonly id: string; + readonly item: boolean; +} + +/** + * [ADR-0162 Execution item 8] The child runs a run's steps name + * (`childRunIds`), to read next: every child of a `subflow` step, and every + * item run of a `map` step, which the walk reads to tell whether it carries + * another record (an item that is a record carries an approval of its own). + */ +function childRunsOf(steps: readonly RunStepRead[]): ChildRunRef[] { + const out: ChildRunRef[] = []; + for (const s of steps) { + if (!Array.isArray(s?.childRunIds)) continue; + for (const id of s.childRunIds) { + if (typeof id !== 'string' || !id) continue; + out.push({ id, item: s.nodeType === 'map' }); + } + } + return out; +} + +/** [ADR-0162 Execution item 8] The child run a parked `subflow` or `map` waits on, from its correlation. */ +function childOfCorrelation(correlation: string): string | undefined { + for (const prefix of ['subflow:', 'map:']) { + if (correlation.startsWith(prefix)) return correlation.slice(prefix.length) || undefined; + } + return undefined; +} + +/** + * [ADR-0162 Execution item 8, ruling A3 on #37767] The key of a request's + * config snapshot that keeps what the plugin read of its approval's runs, at + * each door and as each request opens, so that a later judgement does not + * depend on run histories the automation engine is free to trim. + */ +const RUNS_READ_KEY = '__runsRead'; + +/** + * [ADR-0162 Execution item 8, ruling A3 on #37767] What the plugin kept of + * an approval's runs, in the thin form: + * + * - `runs`: every run of the approval it read; + * - `ended`: those a later judgement does not read again: a run read in a + * terminal status, and an item run of a `map` that carries another record; + * - `between`: a failure between two steps it found in a run that ended, + * with its instant, which counts while no later request of the approval + * opened after it (an instant it could not read always counts). + */ +interface RunsRead { + readonly runs: readonly string[]; + readonly ended: readonly string[]; + readonly between?: { readonly why: string; readonly at: string | null }; +} + +/** The instant of an ISO date, or `NaN`. */ +function instantOf(v: unknown): number { + return v == null || v === '' ? NaN : new Date(v as string).getTime(); +} + +/** [ruling A3] What the requests of one approval kept of its runs, merged ({@link RUNS_READ_KEY}). */ +function runsReadOf(approval: readonly any[]): RunsRead { + const runs = new Set(); + const ended = new Set(); + let between: RunsRead['between']; + for (const r of approval) { + const kept = parseJson>(r?.node_config_json, {})[RUNS_READ_KEY] as Partial | undefined; + if (!kept || typeof kept !== 'object') continue; + for (const id of Array.isArray(kept.runs) ? kept.runs : []) if (typeof id === 'string' && id) runs.add(id); + for (const id of Array.isArray(kept.ended) ? kept.ended : []) if (typeof id === 'string' && id) ended.add(id); + const b = kept.between; + if (b && typeof b === 'object' && typeof b.why === 'string') { + const at = typeof b.at === 'string' ? b.at : null; + // The latest kept failure: the one a later opening is least likely to have answered. + if (!between || !(instantOf(at) <= instantOf(between.at))) between = { why: b.why, at }; + } + } + return { runs: [...runs], ended: [...ended], ...(between ? { between } : {}) }; +} + +/** Whether two kept readings say the same. */ +function sameRunsRead(a: RunsRead, b: RunsRead): boolean { + return JSON.stringify(a) === JSON.stringify(b); +} + /** * [ADR-0162 Execution item 8] What the door answered for an approval after it * resumed or cancelled one of its runs (`ApprovalService.judgeApprovalAfterDoor`). @@ -2530,6 +2658,8 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * walk again, which costs a repeat, never a miss. */ private strandScanCursor: string | null = null; + /** [ADR-0162 Execution item 8] Where the reconciler's walk over the marked requests stopped ({@link reconcileMarkedApprovals}). */ + private reconcileScanCursor: string | null = null; private readonly getConsoleUrl?: ConsolePageComposer; private tenancyPosture?: () => string | undefined; private fieldVisibility?: FieldVisibilitySource; @@ -5282,23 +5412,33 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * * The approval is the request's root run, on the request's record. The door * asks its own table for the approval's requests on the record and reads - * the run that carries the record (`record_run_id`), and answers one of: + * every run of the approval, from the run that carries the record + * (`record_run_id`) down the child runs its steps name, beside what the + * approval kept of runs it read before ({@link readCarryingRun}; what this + * reading showed is kept in turn, {@link keepRunsRead}). It answers one of: * * - **in progress**: a request of the approval is pending or returned on - * the record, or the run is parked at a pause a step can follow (a node + * the record, or a run is parked at a pause a step can follow (a node * of the set the request carries). Nothing is written, and the mark * stays. - * - **finished**: the run completed, stopped on a node outside the set, or - * is parked at a pause outside it, and no failure it routed, nor a later - * step that could not open, ended it between two steps. The mirror writes - * the decision of the approval's latest request on the record, where that - * request was decided and its decision was held back, in the name of - * whoever decided it ({@link attributedMirrorContext}). - * - **abandoned**: the run ended between two steps - * ({@link abandonApproval}). - * - **cannot tell**: another process is advancing the run, or the run or - * the table cannot be read. Nothing is written, and the mark stays for - * the reconciler. + * - **finished**: every run completed, stopped on a node outside the set, + * or is parked at a pause outside it, and no failure a run routed, nor a + * later step that could not open, ended the approval between two steps. + * The mirror writes the decision of the approval's latest request on the + * record, where that request was decided and its decision was held back, + * in the name of whoever decided it ({@link attributedMirrorContext}). + * - **abandoned**: a run ended between two steps ({@link abandonApproval}). + * - **cannot tell**: another process is advancing a run, a run or the + * table cannot be read, or, within the age bound, a run has no row or + * the latest request's own run is still parked at its own node. Nothing + * is written, and the mark stays for the reconciler. + * + * Past the age bound (`opts.ageBoundMs`, the reconciler's), the last two + * have stopped at the step last decided (rulings A3 and B2 on #37767): where + * a step can follow it, the approval is abandoned and a run still parked + * there is cancelled ({@link cancelStoppedRun}); where none can, it is + * finished, and the administrators are told that its flow did not go on + * after its last step ({@link reportFlowNotContinued}). * * In an approval that holds nothing back, finished and abandoned both end * the hold: the mark is cleared and nothing is written. Where the approval's @@ -5316,6 +5456,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega request: { id?: unknown } | null | undefined, door: string, decided?: { requestId: string; actorId: string | null }, + opts?: { ageBoundMs?: number }, ): Promise { const requestId = request?.id != null ? String(request.id) : ''; if (!requestId) return 'unstamped'; @@ -5346,7 +5487,18 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega return 'judged'; } - const reading = await this.readCarryingRun(latest, stamp, approval); + // The reconciler's age bound: every mark of the approval has stood past + // it, so a run that has not moved since will not move again. + const now = this.clock.now().getTime(); + const aged = opts?.ageBoundMs != null && marked.every((r) => { + const at = new Date(r.unjudged_since).getTime(); + return Number.isFinite(at) && now - at >= opts.ageBoundMs!; + }); + const reading = await this.readCarryingRun(latest, stamp, approval, aged); + // [ruling A3 on #37767] What the runs showed is kept on the approval's + // latest request, whatever the answer, so that a later judgement does + // not need those runs again. + await this.keepRunsRead(latest, approval, reading.kept); if (reading.answer === 'undetermined') { this.logger?.info?.( `[approvals] after ${door}, the approval of ${row.object_name}/${row.record_id} could not be judged yet: ${reading.why} ` @@ -5361,7 +5513,27 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const field = typeof config.approvalStatusField === 'string' && config.approvalStatusField ? config.approvalStatusField : undefined; const holds = !!field && this.holdsBackDecision(latest, field); - if (reading.answer === 'finished') { + // [rulings A3 and B2 on #37767, one rule] Past the age bound, a run that + // cannot be read, or the latest request's own run still parked at its + // own node, has stopped at the step last decided: where a step can + // follow it, the approval ended between two steps; where none can, it + // is finished, and the administrators are told that its flow did not + // go on after its last step. + let lastStepStopped: string | undefined; + let parkedRun: string | undefined; + let answer: 'finished' | 'abandoned' = reading.answer === 'placed' ? 'finished' : reading.answer; + let why = reading.answer === 'abandoned' || reading.answer === 'placed' ? reading.why : ''; + if (reading.answer === 'placed') { + const stepNode = String(latest.flow_node_id ?? latest.current_step ?? ''); + if (stepNode && standsBetweenSteps(stamp, reading.flow, stepNode)) { + answer = 'abandoned'; + parkedRun = reading.parkedRun; + } else { + lastStepStopped = reading.why; + } + why = reading.why; + } + if (answer === 'finished') { if (!holds) { await this.clearMarks(marked); return 'finished'; @@ -5373,6 +5545,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega latest.object_name, latest.record_id, field!, String(latest.status), actor, latest.organization_id ?? null, undefined, { request: latest, step: latest.flow_node_id ?? latest.current_step ?? null }, ); + if (lastStepStopped !== undefined) await this.reportFlowNotContinued(latest, lastStepStopped); if (!refusal) await this.clearMarks(marked); return 'finished'; } @@ -5380,7 +5553,10 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega await this.clearMarks(marked); return 'ended'; } - await this.abandonApproval(latest, marked, field!, reading.why); + await this.abandonApproval(latest, marked, field!, why); + // [ruling B2] The run parked at the decided step is cancelled, so that + // nothing resumes it on a record that was put back. + if (parkedRun) await this.cancelStoppedRun(latest, parkedRun, why); return 'abandoned'; } catch (err: any) { this.logger?.warn?.( @@ -5393,124 +5569,365 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega } /** - * [ADR-0162 D5, Execution item 8] Read the run that carries `latest`'s - * record, once no request of the approval is pending or returned on it, and - * place where it stopped against `stamp`. - * - * - A run another process is advancing, or one that cannot be read: - * `undetermined`. - * - Parked: at a node of the set, `in_progress`; elsewhere it is over. - * - Ended (completed, failed, cancelled, timed out, refused): over. - * - * Over, it ended between two steps where a later step of the approval was - * reached and could not open (the note on `latest`, {@link noteLaterStepNotOpened}), - * whatever the flow did with that failure; where a node of the set failed at - * the top level of the run and the flow routed the failure, and no request - * of the approval opened after it (N46 c′: a failure handled in a - * `try_catch` region is the author's statement that it needs no later step); - * and where the run stopped on a node of the set. Otherwise it finished: an - * end after the last step is the approval's end, also where a node after - * the last step failed. + * [ADR-0162 D5, Execution item 8] Read every run of the approval, once no + * request of it is pending or returned on its record, and place where each + * stopped against `stamp`. The walk starts at the run that carries the + * record, the latest request's own run, and every run a request of the + * approval kept as read and not ended ({@link RUNS_READ_KEY}), and follows + * the child runs each delegating step records (`childRunIds` on the step + * log): every `subflow` child, and every `map` item run that does not carry + * another record (an item that is a record carries an approval of its own). + * A run kept as ended is not read again: what it showed is in `kept`. + * + * - A run that cannot be read because the store did not answer, that + * another process is advancing, or that reports paused with no pause to + * be found (within the age bound): `undetermined`. + * - A run parked at a node of the set: `in_progress`. So is the latest + * request's own run, parked at the latest request's own node, within the + * bound: its decision is recorded and the run may still be resumed. + * - Otherwise, a failure between two steps that no later request answered, + * read now or kept, or a later step that could not open (the note on + * `latest`, {@link noteLaterStepNotOpened}): `abandoned`. + * - Otherwise, a run with no row, or the latest request's own run still + * parked at its own node: within the bound `undetermined`, past it + * `placed`: the run has stopped at the step last decided (ruling A3 and + * B2 on #37767, one rule), and {@link judgeApprovalAfterDoor} ends the + * approval by whether a step can follow that step. + * - Otherwise `finished`. + * + * A failure between two steps is a failure the flow routed, of a node of + * the set at the top level of a run (N46 c′: a failure handled in a + * `try_catch` region is the author's statement that it needs no later + * step), or a run that ended on a node of the set ({@link stopOf}); it is + * answered where a request of the approval opened after it. An end after + * the last step is the approval's end, also where a node after the last + * step failed. + * + * `aged` is the reconciler's: every mark of the approval has stood past + * {@link RECONCILER_AGE_BOUND_MS}, so a run that has not moved since will + * not move again. Then a run that reports paused while its pause is gone is + * read as stopped at its last step, and a run parked at a `subflow` or a + * `map` whose child run has ended, or has no row, as stopped at that node. + * + * Every answer carries `kept`: what this reading adds to what the approval + * kept, which the door writes on the latest request. */ private async readCarryingRun( latest: any, stamp: readonly StampedNode[], approval: readonly any[], + aged = false, ): Promise< - | { answer: 'undetermined'; why: string; runId?: string } - | { answer: 'in_progress' } - | { answer: 'finished' } - | { answer: 'abandoned'; why: string } + | { answer: 'undetermined'; why: string; runId?: string; kept?: RunsRead } + | { answer: 'in_progress'; kept?: RunsRead } + | { answer: 'finished'; kept?: RunsRead } + | { answer: 'abandoned'; why: string; kept?: RunsRead } + | { answer: 'placed'; why: string; parkedRun?: string; flow?: string; kept?: RunsRead } > { - const runId = String(latest.record_run_id ?? latest.root_run_id ?? ''); + const rootId = String(latest.record_run_id ?? latest.root_run_id ?? ''); const automation = this.automation; - if (!runId) return { answer: 'undetermined', why: 'the request records no run that carries its record.' }; + if (!rootId) return { answer: 'undetermined', why: 'the request records no run that carries its record.' }; if (typeof automation?.getRun !== 'function') { - return { answer: 'undetermined', why: 'no automation engine that reports a run is attached.', runId }; + return { answer: 'undetermined', why: 'no automation engine that reports a run is attached.', runId: rootId }; + } + + const config = parseJson>(latest.node_config_json, {}); + const notOpened = config[LATER_STEP_NOT_OPENED_KEY] as { node?: unknown; reason?: unknown } | undefined; + const lastOpened = approval.reduce((acc, r) => { + const at = instantOf(r?.created_at); + return Number.isFinite(at) && at > acc ? at : acc; + }, -Infinity); + const ownRuns = new Set(approval.map((r) => (r?.flow_run_id != null ? String(r.flow_run_id) : '')).filter(Boolean)); + const prior = runsReadOf(approval); + const settled = new Set(prior.ended); + const runs = new Set(prior.runs); + const ended = new Set(prior.ended); + let between = prior.between && !(instantOf(prior.between.at) < lastOpened) ? prior.between : undefined; + const kept = (): RunsRead => ({ + runs: [...runs].slice(0, MAX_RUNS_READ_PER_APPROVAL), + ended: [...ended].slice(0, MAX_RUNS_READ_PER_APPROVAL), + ...(between ? { between } : {}), + }); + + const ownRunId = latest.flow_run_id != null ? String(latest.flow_run_id) : ''; + const queue: ChildRunRef[] = [{ id: rootId, item: false }]; + if (ownRunId && ownRunId !== rootId) queue.push({ id: ownRunId, item: false }); + for (const id of prior.runs) if (!settled.has(id)) queue.push({ id, item: false }); + const seen = new Set(); + const missing: string[] = []; + let parkedAtOwnNode: { runId: string; flow?: string } | undefined; + let endedWhy: string | undefined; + while (queue.length > 0) { + const next = queue.shift()!; + const runId = next.id; + if (seen.has(runId) || settled.has(runId)) continue; + if (seen.size >= MAX_RUNS_READ_PER_APPROVAL) { + return { answer: 'undetermined', why: `its runs number more than ${MAX_RUNS_READ_PER_APPROVAL}, past what one judgement reads.`, runId, kept: kept() }; + } + seen.add(runId); + const one = await this.readApprovalRun(runId, { + stamp, lastOpened, aged, item: next.item && !ownRuns.has(runId), latest, + }); + if (one.answer === 'undetermined') return { answer: 'undetermined', why: one.why, runId, kept: kept() }; + if (one.answer === 'missing') { + missing.push(runId); + continue; + } + runs.add(runId); + if (one.answer === 'foreign') { + ended.add(runId); + continue; + } + if (one.answer === 'in_progress') return { answer: 'in_progress', kept: kept() }; + if (one.answer === 'own_node') { + parkedAtOwnNode = { runId, flow: one.flow }; + } else { + if (one.ended) ended.add(runId); + if (one.endedWhy !== undefined && endedWhy === undefined) { + endedWhy = one.endedWhy; + if (one.ended && !between) between = { why: one.endedWhy, at: one.endedAt ?? null }; + } + } + queue.push(...one.children); } - let run: { status?: string; flowName?: string; steps?: unknown } | null; + if (notOpened && typeof notOpened === 'object') { + return { + answer: 'abandoned', + why: `its step '${String(notOpened.node ?? '')}' could not open (${String(notOpened.reason ?? 'no reason recorded')}).`, + kept: kept(), + }; + } + const failed = endedWhy ?? between?.why; + if (failed) return { answer: 'abandoned', why: failed, kept: kept() }; + if (parkedAtOwnNode || missing.length > 0) { + const what = parkedAtOwnNode + ? `its run '${parkedAtOwnNode.runId}' is still parked at the step '${String(latest.flow_node_id ?? '')}' its decision was recorded on, so the run did not go on after it` + : `its run '${missing[0]}' has no row the automation engine can read, so where it stopped cannot be read`; + if (!aged) return { answer: 'undetermined', why: `${what}, and a process may still be moving it.`, runId: parkedAtOwnNode?.runId ?? missing[0], kept: kept() }; + return { + answer: 'placed', + why: `${what}; past the age bound it has stopped at that step.`, + ...(parkedAtOwnNode ? { parkedRun: parkedAtOwnNode.runId, flow: parkedAtOwnNode.flow } : {}), + kept: kept(), + }; + } + return { answer: 'finished', kept: kept() }; + } + + /** + * [ADR-0162 D5, Execution item 8] One run of an approval's tree, for + * {@link readCarryingRun}: whether it can be read and is still, whether it + * is parked between two steps or at the latest request's own node, whether + * it ended (and so is not read again) and ended between two steps, and the + * child runs to read next. `item`: the run is an item run of a `map` that + * is not the run of a request of the approval; one that carries a record + * other than the approval's is `foreign`, and is not followed. + */ + private async readApprovalRun( + runId: string, + at: { stamp: readonly StampedNode[]; lastOpened: number; aged: boolean; item: boolean; latest: any }, + ): Promise< + | { answer: 'undetermined'; why: string } + | { answer: 'missing' } + | { answer: 'foreign' } + | { answer: 'in_progress' } + | { answer: 'own_node'; flow?: string; children: ChildRunRef[] } + | { answer: 'read'; ended: boolean; endedWhy?: string; endedAt?: string; children: ChildRunRef[] } + > { + const { stamp, lastOpened, aged, item, latest } = at; + const automation = this.automation!; + let run: { status?: string; flowName?: string; completedAt?: string; trigger?: { object?: string; recordId?: string }; steps?: unknown } | null; try { - run = await automation.getRun(runId); + run = await automation.getRun!(runId, { strict: true }); } catch (err: any) { - return { answer: 'undetermined', why: `the run '${runId}' could not be read (${err?.message ?? err}).`, runId }; + return { answer: 'undetermined', why: `the run '${runId}' could not be read (${err?.message ?? err}).` }; + } + if (!run) return { answer: 'missing' }; + if (item) { + const object = run.trigger?.object; + const record = run.trigger?.recordId; + if (record != null && record !== '' && (String(record) !== String(latest.record_id) || (object != null && String(object) !== String(latest.object_name)))) { + return { answer: 'foreign' }; + } } - const status = typeof run?.status === 'string' ? run.status : ''; - if (!run || !status) return { answer: 'undetermined', why: `the run '${runId}' reports no status.`, runId }; + const status = typeof run.status === 'string' ? run.status : ''; + if (!status) return { answer: 'undetermined', why: `the run '${runId}' reports no status.` }; if (ADVANCING_RUN_STATUSES.has(status)) { - return { answer: 'undetermined', why: `the run '${runId}' is ${status}, so another process may be advancing it.`, runId }; + return { answer: 'undetermined', why: `the run '${runId}' is ${status}, so another process may be advancing it.` }; } const flow = typeof run.flowName === 'string' ? run.flowName : undefined; - const steps = (Array.isArray(run.steps) ? run.steps : []) as Array<{ - nodeId?: unknown; nodeType?: unknown; status?: unknown; parentNodeId?: unknown; startedAt?: unknown; - }>; + const steps = (Array.isArray(run.steps) ? run.steps : []) as RunStepRead[]; + const children = childRunsOf(steps); + + // A failure the flow routed, at the top level of the run, on a node of + // the set, after which no request of the approval opened. Read for a + // paused run as for an ended one: a failure routed to a pause outside + // the set ended the approval as surely as one routed to an end. + const routedFailure = (stop: string | undefined) => steps.find((s) => s?.status === 'failure' + && !s.parentNodeId + && typeof s.nodeId === 'string' + && s.nodeId !== stop + && standsBetweenSteps(stamp, flow, s.nodeId) + && !(instantOf(s.startedAt) < lastOpened)); + const routedWhy = (s: RunStepRead) => `its node '${String(s.nodeId)}' failed between two steps, and the flow went on without asking the next step.`; - let stoppedAt: string | undefined; if (status === 'paused') { - let parked: { nodeId?: string; flowName?: string } | undefined; + let parked: { nodeId?: string; flowName?: string; correlation?: string } | undefined; try { parked = await automation.suspensionOf?.(runId); } catch (err: any) { - return { answer: 'undetermined', why: `where the run '${runId}' is parked could not be read (${err?.message ?? err}).`, runId }; + return { answer: 'undetermined', why: `where the run '${runId}' is parked could not be read (${err?.message ?? err}).` }; } - if (!parked?.nodeId) return { answer: 'undetermined', why: `the run '${runId}' reports paused, and no pause of it can be found.`, runId }; - if (standsBetweenSteps(stamp, parked.flowName ?? flow, parked.nodeId)) return { answer: 'in_progress' }; - } else if (!TERMINAL_RUN_STATUSES.has(status)) { - return { answer: 'undetermined', why: `the run '${runId}' reports the status '${status}', which the plugin does not place.`, runId }; - } else { - stoppedAt = stopOf(steps, status); + if (!parked?.nodeId) { + if (!aged) return { answer: 'undetermined', why: `the run '${runId}' reports paused, and no pause of it can be found.` }; + const stop = stopOf(steps, 'failed'); + const routed = routedFailure(stop); + if (routed) return { answer: 'read', ended: false, endedWhy: routedWhy(routed), children }; + return { + answer: 'read', ended: false, children, + ...(stop && standsBetweenSteps(stamp, flow, stop) + ? { endedWhy: `its run '${runId}' reports paused at a pause that is gone, so it will not go on, between two steps.` } + : {}), + }; + } + // [ruling B2 on #37767] The latest request's own run, still parked at + // the node its decision was recorded on: the run was not resumed. + if (String(runId) === String(latest.flow_run_id ?? '') && parked.nodeId === String(latest.flow_node_id ?? '')) { + return { answer: 'own_node', flow: parked.flowName ?? flow, children }; + } + if (standsBetweenSteps(stamp, parked.flowName ?? flow, parked.nodeId)) { + const child = typeof parked.correlation === 'string' ? childOfCorrelation(parked.correlation) : undefined; + if (!aged || !child || !(await this.childRunHasEnded(child))) return { answer: 'in_progress' }; + return { + answer: 'read', ended: false, children, + endedWhy: `its run '${runId}' is parked at '${parked.nodeId}' on a child run that has ended, so nothing will resume it, between two steps.`, + }; + } + // Parked outside the set (M3 of 7255916895): a routed failure before + // the pause still ended the approval between two steps. + const routed = routedFailure(undefined); + return { answer: 'read', ended: false, children, ...(routed ? { endedWhy: routedWhy(routed) } : {}) }; + } + if (!TERMINAL_RUN_STATUSES.has(status)) { + return { answer: 'undetermined', why: `the run '${runId}' reports the status '${status}', which the plugin does not place.` }; } - const config = parseJson>(latest.node_config_json, {}); - const notOpened = config[LATER_STEP_NOT_OPENED_KEY] as { node?: unknown; reason?: unknown } | undefined; - if (notOpened && typeof notOpened === 'object') { - return { - answer: 'abandoned', - why: `its step '${String(notOpened.node ?? '')}' could not open (${String(notOpened.reason ?? 'no reason recorded')}).`, - }; + const stop = stopOf(steps, status); + const routed = routedFailure(stop); + if (routed) { + return { answer: 'read', ended: true, endedWhy: routedWhy(routed), endedAt: typeof routed.startedAt === 'string' ? routed.startedAt : undefined, children }; } - // A failure the flow routed, at the top level of the run, on a node of the - // set, after which no request of the approval opened; or a stop on a node - // of the set. Read on the run that carries the record, and on the latest - // request's own run where that is another (a `subflow` body runs in a - // child run of its own, whose steps the carrying run does not log). - const instant = (v: unknown): number => (v == null || v === '' ? NaN : new Date(v as string).getTime()); - const lastOpened = approval.reduce((acc, r) => { - const at = instant(r?.created_at); - return Number.isFinite(at) && at > acc ? at : acc; - }, -Infinity); - const endedBetween = ( - log: ReadonlyArray<{ nodeId?: unknown; status?: unknown; parentNodeId?: unknown; startedAt?: unknown }>, - logFlow: string | undefined, - logStatus: string, - stop: string | undefined, - ): string | undefined => { - const routed = log.find((s) => s?.status === 'failure' - && !s.parentNodeId - && typeof s.nodeId === 'string' - && s.nodeId !== stop - && standsBetweenSteps(stamp, logFlow, s.nodeId) - && !(instant(s.startedAt) < lastOpened)); - if (routed) return `its node '${String(routed.nodeId)}' failed between two steps, and the flow went on to its end without asking the next step.`; - if (logStatus === 'paused' || REACHED_AN_END.has(logStatus)) return undefined; - if (!stop) return `its run ended ${logStatus}, at a node the plugin cannot place.`; - if (standsBetweenSteps(stamp, logFlow, stop)) return `its run ended ${logStatus} at node '${stop}', between two steps.`; - return undefined; - }; - const carried = endedBetween(steps, flow, status, stoppedAt); - if (carried) return { answer: 'abandoned', why: carried }; - const ownRunId = latest.flow_run_id != null ? String(latest.flow_run_id) : ''; - if (ownRunId && ownRunId !== runId) { - let own: { status?: string; flowName?: string; steps?: unknown } | null = null; - try { own = await automation.getRun(ownRunId); } catch { own = null; } - const ownStatus = typeof own?.status === 'string' ? own.status : ''; - if (own && TERMINAL_RUN_STATUSES.has(ownStatus)) { - const ownSteps = (Array.isArray(own.steps) ? own.steps : []) as typeof steps; - const ownStop = stopOf(ownSteps, ownStatus); - const inChild = endedBetween(ownSteps, typeof own.flowName === 'string' ? own.flowName : undefined, ownStatus, ownStop); - if (inChild) return { answer: 'abandoned', why: inChild }; + if (REACHED_AN_END.has(status)) return { answer: 'read', ended: true, children }; + // A run that ended before the approval's latest request opened did not + // stop it: the approval went on. + const answered = instantOf(run.completedAt) < lastOpened; + const endedAt = typeof run.completedAt === 'string' ? run.completedAt : undefined; + if (!stop) { + return { answer: 'read', ended: true, children, ...(answered ? {} : { endedWhy: `its run '${runId}' ended ${status}, at a node the plugin cannot place.`, endedAt }) }; + } + if (!answered && standsBetweenSteps(stamp, flow, stop)) { + return { answer: 'read', ended: true, endedWhy: `its run '${runId}' ended ${status} at node '${stop}', between two steps.`, endedAt, children }; + } + return { answer: 'read', ended: true, children }; + } + + /** + * [ADR-0162 Execution item 8] Whether `runId`, a child a parked run waits + * on, has ended: read in a terminal status, or with no row (it will not + * answer the run that waits on it). A store that does not answer is not + * an answer. + */ + private async childRunHasEnded(runId: string): Promise { + if (typeof this.automation?.getRun !== 'function') return false; + try { + const run = await this.automation.getRun(runId, { strict: true }); + return !run || (typeof run.status === 'string' && TERMINAL_RUN_STATUSES.has(run.status)); + } catch { + return false; + } + } + + /** + * [ADR-0162 Execution item 8, ruling A3 on #37767] Keep `kept` on + * `latest`'s snapshot ({@link RUNS_READ_KEY}), where it adds to what the + * approval kept; `latest` is updated in place, so a later write of its + * snapshot in the same judgement carries it. Best-effort: a write that + * fails leaves the runs to be read again. + */ + private async keepRunsRead(latest: any, approval: readonly any[], kept: RunsRead | undefined): Promise { + if (!kept || !latest?.id) return; + if (sameRunsRead(runsReadOf(approval), kept)) return; + const snapshot = parseJson>(latest.node_config_json, {}); + const node_config_json = JSON.stringify({ ...snapshot, [RUNS_READ_KEY]: kept }); + try { + await this.engine.update('sys_approval_request', { id: latest.id, node_config_json }, { context: SYSTEM_CTX }); + latest.node_config_json = node_config_json; + } catch (err: any) { + this.logger?.warn?.('[approvals] could not keep what was read of an approval\'s runs; the next judgement reads them again', { + request: latest.id, error: err?.message ?? String(err), + }); + } + } + + /** + * [ADR-0162 Execution item 8, ruling A3 on #37767] What a request that is + * opening keeps of its approval's runs: every run the plugin can read + * from the run that carries the record and the request's own run, down the + * child runs their steps name, with those that ended (and the item runs of + * another record) kept as ended. Every failure before this opening is + * answered by it, so none is kept. A run being advanced is read from what + * it logged when it last paused, so the run opening the approval's first + * request, which has logged nothing yet, is read at the first door. + * `undefined` where there is nothing to read. Best-effort and never + * throws: a run it cannot read is read at the next door. + */ + private async runsReadAtOpening(row: { + root_run_id?: unknown; record_run_id?: unknown; flow_run_id?: unknown; object_name?: unknown; record_id?: unknown; + }): Promise { + const rootId = String(row.record_run_id ?? row.root_run_id ?? ''); + if (!rootId || !row.root_run_id || typeof this.automation?.getRun !== 'function') return undefined; + try { + const approval: any[] = (await this.engine.find('sys_approval_request', { + where: { root_run_id: row.root_run_id, object_name: row.object_name, record_id: row.record_id }, + fields: ['id', 'flow_run_id', 'node_config_json'], limit: 500, context: SYSTEM_CTX, + })) ?? []; + const prior = runsReadOf(approval); + const ownRuns = new Set([...approval.map((r) => String(r?.flow_run_id ?? '')), String(row.flow_run_id ?? '')].filter(Boolean)); + const runs = new Set(prior.runs); + const ended = new Set(prior.ended); + const queue: ChildRunRef[] = [{ id: rootId, item: false }]; + if (row.flow_run_id && String(row.flow_run_id) !== rootId) queue.push({ id: String(row.flow_run_id), item: false }); + for (const id of prior.runs) if (!ended.has(id)) queue.push({ id, item: false }); + const seen = new Set(); + while (queue.length > 0 && seen.size < MAX_RUNS_READ_PER_APPROVAL) { + const { id, item } = queue.shift()!; + if (seen.has(id) || ended.has(id)) continue; + seen.add(id); + let run: { status?: string; trigger?: { object?: string; recordId?: string }; steps?: unknown } | null; + try { + run = await this.automation.getRun(id, { strict: true }); + } catch { + continue; + } + if (!run) continue; + runs.add(id); + const record = run.trigger?.recordId; + if (item && !ownRuns.has(id) && record != null && record !== '' + && (String(record) !== String(row.record_id) || (run.trigger?.object != null && String(run.trigger.object) !== String(row.object_name)))) { + ended.add(id); + continue; + } + if (typeof run.status === 'string' && TERMINAL_RUN_STATUSES.has(run.status)) ended.add(id); + queue.push(...childRunsOf((Array.isArray(run.steps) ? run.steps : []) as RunStepRead[])); } + if (runs.size === 0) return undefined; + return { runs: [...runs].slice(0, MAX_RUNS_READ_PER_APPROVAL), ended: [...ended].slice(0, MAX_RUNS_READ_PER_APPROVAL) }; + } catch (err: any) { + this.logger?.warn?.('[approvals] could not read an approval\'s runs as its request opened; the next door reads them', { + error: err?.message ?? String(err), + }); + return undefined; } - return { answer: 'finished' }; } /** @@ -5603,13 +6020,16 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega } try { - await this.engine.insert('sys_approval_action', await this.actionRow(latest, { - id: uid('aact'), request_id: latest.id, organization_id: org, - step_name: step, step_index: 0, action: 'comment', - actor_id: null, - comment: abandonedNoteText(why, left), - created_at: now, - }), { context: SYSTEM_CTX }); + // A put-back the reconciler tries again leaves its line once. + if (!(await this.hasTimelineLine(String(latest.id), abandonedNoteText(why, left)))) { + await this.engine.insert('sys_approval_action', await this.actionRow(latest, { + id: uid('aact'), request_id: latest.id, organization_id: org, + step_name: step, step_index: 0, action: 'comment', + actor_id: null, + comment: abandonedNoteText(why, left), + created_at: now, + }), { context: SYSTEM_CTX }); + } } catch (err: any) { this.logger?.warn?.('[approvals] could not note an abandoned approval on its request timeline', { request: latest.id, error: err?.message ?? String(err), @@ -5644,6 +6064,82 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega if (!refusal) await this.clearMarks(marked); } + /** + * [ADR-0162 Execution item 8, ruling B2 on #37767] Cancel the run of an + * approval that was abandoned while the run stood parked at the step its + * decision was recorded on, and the runs above it that wait on it through + * a `subflow` (cut below a `map`, whose batch stays a batch), deepest + * first: nothing resumes the approval on a record that was put back. A + * cancel that fails is logged; the approval stays abandoned, and the door + * that continues a restored run refuses it. + */ + private async cancelStoppedRun(latest: any, runId: string, why: string): Promise { + if (typeof this.automation?.cancelRun !== 'function') { + this.logger?.warn?.('[approvals] no automation engine in this process can cancel the run of an abandoned approval; it stays parked', { + request: latest?.id, run: runId, + }); + return; + } + const chain = await this.voidedRunChain( + String(latest.id), runId, latest.record_run_id ? String(latest.record_run_id) : undefined, + 'whose approval was abandoned when its run did not go on', + ); + const reason = `the approval of request ${String(latest.id)} was abandoned: ${why}`; + for (const id of [...chain].reverse()) { + try { + await this.automation.cancelRun(id, reason); + } catch (err: any) { + this.logger?.warn?.('[approvals] could not cancel a run of an abandoned approval; it may stay parked', { + request: latest.id, run: id, error: err?.message ?? String(err), + }); + return; + } + } + } + + /** + * [ADR-0162 Execution item 8, ruling B2 on #37767] Tell the organization's + * administrators that the approval of `latest`'s record was decided at its + * last step and its outcome written, while its flow was not seen to go on + * after that step, so the flow's nodes after it may not have run. The run's + * pause, where it has one, is left for an operator to continue or cancel. + * Sent once per request. + */ + private async reportFlowNotContinued(latest: any, why: string): Promise { + const object = String(latest.object_name); + const recordId = String(latest.record_id); + const org = latest.organization_id ?? null; + this.logger?.warn?.( + `[approvals] the approval of ${object}/${recordId} was decided at its last step, and its outcome was written, but ` + + `${why} The flow's nodes after that step may not have run; the organization's administrators were told.`, + { request: latest.id, object, record: recordId, run: latest.flow_run_id ?? null }, + ); + try { + const admins = await this.organizationAdministrators(org); + if ('ids' in admins && admins.ids.length) { + await this.notify({ + topic: FLOW_NOT_CONTINUED_TOPIC, + organizationId: org, + audience: admins.ids, + source: { object: 'sys_approval_request', id: String(latest.id) }, + dedupKey: `approval-flow-not-continued-${String(latest.id)}`, + about: { object, recordId }, + text: (subject) => approvalNotificationText({ + title: 'approvalFlowNotContinuedTitle', body: 'approvalFlowNotContinuedBody', params: subject, + }), + }); + } else if ('failure' in admins) { + this.logger?.warn?.('[approvals] could not read the organization\'s administrators to tell them a flow did not go on after its last step', { + request: latest.id, organizationId: org, error: admins.failure, + }); + } + } catch (err: any) { + this.logger?.warn?.('[approvals] could not tell the organization\'s administrators that a flow did not go on after its last step', { + request: latest.id, error: err?.message ?? String(err), + }); + } + } + /** * [ADR-0162 Execution item 8] Clear the mark on `rows`, one keyed update * each: the approval they belong to has been judged, or their requests' @@ -5663,6 +6159,24 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega } } + /** + * [ADR-0162 Execution item 8] Whether `requestId`'s timeline already holds a + * comment that reads `comment`, a sentence only the platform writes: a + * write the reconciler tries again on each pass reports its failure once. + * A read that fails answers `false`, and the line is left again. + */ + private async hasTimelineLine(requestId: string, comment: string): Promise { + try { + const rows = await this.engine.find('sys_approval_action', { + where: { request_id: requestId, action: 'comment', comment }, + fields: ['id'], limit: 1, context: SYSTEM_CTX, + }); + return Array.isArray(rows) && rows.length > 0; + } catch { + return false; + } + } + /** * [ADR-0162 Execution item 8] Clear the marks on the requests of `row`'s * approval on its record other than `row` itself. A recall, an override and @@ -6032,13 +6546,17 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega ); const now = this.clock.now().toISOString(); try { - await this.engine.insert('sys_approval_action', await this.actionRow(request, { - id: uid('aact'), request_id: requestId, organization_id: requestOrg ?? null, - step_name: about.step ?? request?.current_step ?? null, step_index: 0, action: 'comment', - actor_id: null, - comment: refusedMirrorNoteText(status, reason), - created_at: now, - }), { context: SYSTEM_CTX }); + // The reconciler tries a refused write again on each pass: the line is + // left once for one refusal. + if (!(await this.hasTimelineLine(requestId, refusedMirrorNoteText(status, reason)))) { + await this.engine.insert('sys_approval_action', await this.actionRow(request, { + id: uid('aact'), request_id: requestId, organization_id: requestOrg ?? null, + step_name: about.step ?? request?.current_step ?? null, step_index: 0, action: 'comment', + actor_id: null, + comment: refusedMirrorNoteText(status, reason), + created_at: now, + }), { context: SYSTEM_CTX }); + } } catch (err: any) { this.logger?.warn?.('[approvals] could not note a refused status write on the request timeline', { request: requestId, error: err?.message ?? String(err), @@ -6879,6 +7397,17 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const n = Array.isArray(prior) ? prior.length : 0; if (n > 0) configSnapshot.__round = n + 1; } catch { /* round display is best-effort */ } + // [ADR-0162 Execution item 8, ruling A3 on #37767] As the request opens, + // it keeps what the plugin can read of its approval's runs, so that a + // child run that ended before any door and was then trimmed is not + // needed again ({@link runsReadAtOpening}). + if (stampOf({ between_steps_json: betweenSteps }) !== undefined) { + const kept = await this.runsReadAtOpening({ + root_run_id: input.rootRun?.runId, record_run_id: input.recordRun?.runId, flow_run_id: input.runId, + object_name: input.object, record_id: input.recordId, + }); + if (kept) configSnapshot[RUNS_READ_KEY] = kept; + } const row: any = { id, process_name: processName, @@ -8938,11 +9467,12 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega requestId: string, runId: string, recordRunId: string | undefined, + whose = 'whose approval a record delete voided', ): Promise { if (!recordRunId || recordRunId === runId) return [runId]; const alone = (why: string, error?: unknown): string[] => { this.logger?.warn?.( - '[approvals] could not read the runs above a run whose approval a record delete voided — only that run ' + `[approvals] could not read the runs above a run ${whose} — only that run ` + 'is cancelled, and a run above it may stay parked', { request: requestId, run: runId, recordRun: recordRunId, why, ...(error ? { error: (error as any)?.message ?? String(error) } : {}) }, ); @@ -10382,6 +10912,12 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega for (const raw of rows) { const runId = raw?.flow_run_id ? String(raw.flow_run_id) : ''; if (!runId) continue; // not node-driven — no run was ever supposed to move + // [ADR-0162 Execution item 8] A decided request of an approval the check + // stamped is the door's and the reconciler's ({@link reconcileMarkedApprovals}), + // which judge it and end its hold: this report does not name it as + // well. A returned one (a send-back sets no mark, and no judgement + // places a returned request) is reported as before. + if (stampOf(raw) !== undefined && (raw.status === 'approved' || raw.status === 'rejected')) continue; let suspended: boolean; try { @@ -11080,6 +11616,146 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega }; } + /** + * [ADR-0162 D5, Execution item 8] The reconciler: judge every approval whose + * mark no door cleared. For an approval on an object that declares + * `closedStates` it takes the place of {@link inspectStrandedRequests}, + * which skips the marked requests the check stamped. It rides the sweep + * clock. + * + * One pass reads two windows of at most `limit` (default 200) marked + * requests: the oldest marks, and the next page of a walk over every marked + * request by id, so that one pass is bounded and marks that stay cannot + * keep newer ones from being read. It judges each approval among them + * once, as the door would have ({@link judgeApprovalAfterDoor}): it is + * finished and its outcome is written in the name of the request's + * recorded decider ({@link deciderOf}), or it ended between two steps and + * is abandoned, or, where nothing was held back, the mark is cleared and + * nothing is written. It places what the door does not see: a run that was + * cancelled, a parent run that is gone. Once every mark of an approval has + * stood past {@link RECONCILER_AGE_BOUND_MS}, it also places a run that + * will not move again (rulings A3 and B2 on #37767): a run that reports + * paused while its pause is gone, a run parked at a `subflow` or a `map` + * whose child run has ended or has no row, and, as one rule, a run with no + * row the engine can read and the latest request's own run still parked + * at the step its decision was recorded on, each of which has stopped at + * the step last decided. Where a step can follow it, the approval is + * abandoned (and a run still parked there is cancelled); where none can, + * the outcome is written and the administrators are told that the flow did + * not go on after its last step. + * + * A refused outcome or put-back leaves the marks, so the next pass tries it + * again; the mirror's notice to the administrators is keyed per request and + * status, so it is sent once. For a record that was deleted, the marks of + * its approval are cleared and nothing is written: no retry and no notice. + * An approval it cannot tell about keeps its marks for the next pass. + * + * Best-effort: one approval's failure costs only that approval. + */ + async reconcileMarkedApprovals(options?: { limit?: number }): Promise<{ + scanned: number; + judged: Partial>; + deletedRecords: number; + }> { + const judged: Partial> = {}; + let deletedRecords = 0; + let rows: any[]; + // S2 of 7255916895: two windows of at most `limit` rows each, as the + // stranded-request report reads (#37808). The OLDEST marks, so that an + // approval left waiting longest is judged first; and the next page of a + // WALK over every marked request by id, resumed where the previous pass + // stopped and restarted once it runs out, so that marks which stay + // (an approval in progress, or one that cannot be told yet) cannot hold + // the head of every scan and keep the newer ones from being read. + const limit = options?.limit ?? 200; + const marked = { $null: false }; + try { + const oldest: any[] = (await this.engine.find('sys_approval_request', { + where: { unjudged_since: marked }, + orderBy: [{ field: 'unjudged_since', order: 'asc' }, { field: 'id', order: 'asc' }], + limit, context: SYSTEM_CTX, + })) ?? []; + const cursor = this.reconcileScanCursor; + const walked: any[] = (await this.engine.find('sys_approval_request', { + where: cursor ? { unjudged_since: marked, id: { $gt: cursor } } : { unjudged_since: marked }, + orderBy: [{ field: 'id', order: 'asc' }], + limit, context: SYSTEM_CTX, + })) ?? []; + this.reconcileScanCursor = walked.length < limit ? null : String(walked[walked.length - 1].id); + const inOldest = new Set(oldest.map((r) => String(r?.id))); + rows = [...oldest, ...walked.filter((r) => !inOldest.has(String(r?.id)))]; + } catch (err: any) { + this.logger?.warn?.('[approvals] the reconciler could not list the marked requests', { + error: err?.message ?? String(err), + }); + return { scanned: 0, judged, deletedRecords }; + } + + const seen = new Set(); + for (const raw of rows) { + if (!isMarked(raw)) continue; + const key = raw?.root_run_id + ? `${String(raw.root_run_id)}\u0000${String(raw.object_name)}\u0000${String(raw.record_id)}` + : `request\u0000${String(raw?.id)}`; + if (seen.has(key)) continue; + seen.add(key); + try { + if (await this.recordIsGone(raw)) { + await this.clearApprovalMarks(raw); + deletedRecords++; + this.logger?.info?.( + `[approvals] the reconciler cleared the marks of the approval of ${String(raw.object_name)}/${String(raw.record_id)}: ` + + 'the record was deleted, so nothing is written.', + { request: raw.id }, + ); + continue; + } + const answer = await this.judgeApprovalAfterDoor(raw, 'the reconciler', undefined, { ageBoundMs: RECONCILER_AGE_BOUND_MS }); + judged[answer] = (judged[answer] ?? 0) + 1; + // A mark on a request that carries no stamp or no root run can never + // be judged; left, it would hold its place at the head of every scan. + if (answer === 'unstamped') await this.clearMarks([raw]); + } catch (err: any) { + this.logger?.warn?.('[approvals] the reconciler could not judge an approval; its marks stand for the next pass', { + request: raw?.id, error: err?.message ?? String(err), + }); + } + } + return { scanned: rows.length, judged, deletedRecords }; + } + + /** + * [ADR-0162 Execution item 8] Whether `row`'s record was deleted: a read of + * it answers no row. A read that fails is not an answer, and the approval is + * judged as any other. + */ + private async recordIsGone(row: any): Promise { + const object = String(row?.object_name ?? ''); + const recordId = String(row?.record_id ?? ''); + if (!object || !recordId) return false; + try { + const found = await this.engine.find(object, { + where: { id: recordId }, fields: ['id'], limit: 1, context: SYSTEM_CTX, + }); + return Array.isArray(found) && found.length === 0; + } catch { + return false; + } + } + + /** [ADR-0162 Execution item 8] Clear the marks of every request of `row`'s approval on its record, `row` included. */ + private async clearApprovalMarks(row: any): Promise { + if (!row?.root_run_id) { + await this.clearMarks([row]); + return; + } + const rows = await this.engine.find('sys_approval_request', { + where: { root_run_id: row.root_run_id, object_name: row.object_name, record_id: row.record_id }, + fields: ['id', 'unjudged_since'], limit: 500, context: SYSTEM_CTX, + }); + await this.clearMarks(Array.isArray(rows) ? rows : [row]); + } + async releaseDeadRunRequests(): Promise<{ scanned: number; released: number }> { // No liveness oracle → no basis to declare anything dead. if (typeof this.automation?.getRun !== 'function') return { scanned: 0, released: 0 }; diff --git a/packages/plugins/plugin-approvals/src/approvals-plugin.ts b/packages/plugins/plugin-approvals/src/approvals-plugin.ts index be3dbb05f21..0995a3117aa 100644 --- a/packages/plugins/plugin-approvals/src/approvals-plugin.ts +++ b/packages/plugins/plugin-approvals/src/approvals-plugin.ts @@ -536,6 +536,10 @@ export class ApprovalsServicePlugin implements Plugin { // that really happened), so it rides the same clock purely to make // the finding surface without an operator knowing to go looking. svc.inspectStrandedRequests(), + // [ADR-0162 Execution item 8] The reconciler: judges every approval + // whose mark no door cleared, and ends its hold. It takes the + // place of the report above for the requests the check stamped. + svc.reconcileMarkedApprovals(), ]); for (const r of results) { if (r.status === 'rejected') { diff --git a/packages/plugins/plugin-approvals/src/translations/messages.ts b/packages/plugins/plugin-approvals/src/translations/messages.ts index 995fdafa78d..88f3faebc99 100644 --- a/packages/plugins/plugin-approvals/src/translations/messages.ts +++ b/packages/plugins/plugin-approvals/src/translations/messages.ts @@ -155,6 +155,8 @@ const enSentences = { approvalAutoRejectedBody: 'Your {{object}} {{record}} exceeded the revision limit ({{limit}}) and was rejected.', approvalAbandonedTitle: 'Approval did not finish', approvalAbandonedBody: 'The approval of your {{object}} {{record}} stopped between two of its steps, so it did not finish and the record was put back to an open status. Submit it again when it is ready.', + approvalFlowNotContinuedTitle: 'Approval flow did not go on', + approvalFlowNotContinuedBody: 'The approval of {{object}} {{record}} was decided at its last step and the decision was written, but its flow was not seen to go on after that step, so the steps that follow it may not have run. Check the approval\'s flow run, and continue or cancel it.', approvalReturnedTitle: 'Sent back for revision', approvalReturnedBody: 'Your {{object}} {{record}} needs rework before it can be approved.', approvalRequestInfoTitle: 'More information requested', @@ -305,6 +307,8 @@ export const zhCNMessages: ApprovalMessages = { approvalAutoRejectedBody: '您的{{object}} {{record}} 已超过退回修改次数上限({{limit}}),已被驳回。', approvalAbandonedTitle: '审批未能完成', approvalAbandonedBody: '您的{{object}} {{record}} 的审批在两个步骤之间停止,未能完成,记录已恢复为未关闭的状态。准备好后请重新提交。', + approvalFlowNotContinuedTitle: '审批流程未继续', + approvalFlowNotContinuedBody: '{{object}} {{record}} 的审批已在最后一步作出决定,决定也已写入,但未见其流程在该步之后继续,之后的步骤可能没有执行。请检查该审批的流程运行,并继续或取消它。', approvalReturnedTitle: '已退回修改', approvalReturnedBody: '您的{{object}} {{record}} 需要修改后才能获批。', approvalRequestInfoTitle: '需要补充信息', @@ -392,6 +396,8 @@ export const jaJPMessages: ApprovalMessages = { approvalAutoRejectedBody: 'あなたの{{object}} {{record}} は差し戻し回数の上限({{limit}})を超えたため却下されました。', approvalAbandonedTitle: '承認が完了しませんでした', approvalAbandonedBody: 'あなたの{{object}} {{record}} の承認は 2 つのステップの間で停止したため完了せず、レコードは閉じていないステータスに戻されました。準備ができたら再度申請してください。', + approvalFlowNotContinuedTitle: '承認フローが続行されませんでした', + approvalFlowNotContinuedBody: '{{object}} {{record}} の承認は最後のステップで決定され、その決定は書き込まれましたが、フローがそのステップの後に続行されたことを確認できないため、後続のステップが実行されていない可能性があります。承認のフロー実行を確認し、続行またはキャンセルしてください。', approvalReturnedTitle: '修正のため差し戻されました', approvalReturnedBody: 'あなたの{{object}} {{record}} は、承認を受ける前に修正が必要です。', approvalRequestInfoTitle: '追加情報が求められています', @@ -479,6 +485,8 @@ export const esESMessages: ApprovalMessages = { approvalAutoRejectedBody: 'Su {{object}} {{record}} superó el límite de revisiones ({{limit}}) y se ha rechazado.', approvalAbandonedTitle: 'La aprobación no terminó', approvalAbandonedBody: 'La aprobación de su {{object}} {{record}} se detuvo entre dos de sus pasos, así que no terminó y el registro volvió a un estado abierto. Envíelo de nuevo cuando esté listo.', + approvalFlowNotContinuedTitle: 'El flujo de la aprobación no continuó', + approvalFlowNotContinuedBody: 'La aprobación de {{object}} {{record}} se decidió en su último paso y la decisión se escribió, pero no se vio que su flujo continuara después de ese paso, así que es posible que los pasos siguientes no se hayan ejecutado. Revise la ejecución del flujo de la aprobación y continúela o cancélela.', approvalReturnedTitle: 'Devuelto para revisión', approvalReturnedBody: 'Su {{object}} {{record}} necesita cambios antes de poder aprobarse.', approvalRequestInfoTitle: 'Se solicita más información', @@ -566,6 +574,8 @@ export const zhHantMessages: ApprovalMessages = { approvalAutoRejectedBody: '你的{{object}} {{record}} 已超過退回修改次數上限({{limit}}),因此被駁回。', approvalAbandonedTitle: '核准未能完成', approvalAbandonedBody: '你的{{object}} {{record}} 的核准在兩個步驟之間停止,未能完成,記錄已恢復為未關閉的狀態。準備好後請重新送出。', + approvalFlowNotContinuedTitle: '核准流程未繼續', + approvalFlowNotContinuedBody: '{{object}} {{record}} 的核准已在最後一步作出決定,決定也已寫入,但未見其流程在該步之後繼續,之後的步驟可能沒有執行。請檢查該核准的流程執行,並繼續或取消它。', approvalReturnedTitle: '已退回修改', approvalReturnedBody: '你的{{object}} {{record}} 需要修改後才能獲得核准。', approvalRequestInfoTitle: '需要補充資訊', @@ -653,6 +663,8 @@ export const arMessages: ApprovalMessages = { approvalAutoRejectedBody: 'تجاوز طلبك بشأن {{object}} {{record}} حد المراجعات ({{limit}}) فرُفض.', approvalAbandonedTitle: 'لم تكتمل الموافقة', approvalAbandonedBody: 'توقفت الموافقة على {{object}} {{record}} بين خطوتين من خطواتها، فلم تكتمل وأُعيد السجل إلى حالة مفتوحة. أعد إرساله عندما يكون جاهزًا.', + approvalFlowNotContinuedTitle: 'لم يستمر مسار الموافقة', + approvalFlowNotContinuedBody: 'تم البت في الموافقة على {{object}} {{record}} في خطوتها الأخيرة وكُتب القرار، لكن لم يُرَ مسارها يستمر بعد تلك الخطوة، لذا ربما لم تُنفَّذ الخطوات التي تليها. راجع تشغيل مسار الموافقة، ثم تابعه أو ألغِه.', approvalReturnedTitle: 'أُعيد للمراجعة', approvalReturnedBody: 'يحتاج طلبك بشأن {{object}} {{record}} إلى تعديل قبل أن تمكن الموافقة عليه.', approvalRequestInfoTitle: 'مطلوب مزيد من المعلومات', @@ -740,6 +752,8 @@ export const frMessages: ApprovalMessages = { approvalAutoRejectedBody: 'Votre demande sur {{object}} {{record}} a dépassé la limite de révisions ({{limit}}) et a été rejetée.', approvalAbandonedTitle: 'L’approbation n’a pas abouti', approvalAbandonedBody: 'L’approbation de votre {{object}} {{record}} s’est arrêtée entre deux de ses étapes : elle n’a pas abouti et l’enregistrement est revenu à un statut ouvert. Soumettez-le à nouveau lorsqu’il est prêt.', + approvalFlowNotContinuedTitle: 'Le flux de l’approbation n’a pas continué', + approvalFlowNotContinuedBody: 'L’approbation de {{object}} {{record}} a été décidée à sa dernière étape et la décision a été écrite, mais son flux n’a pas été vu se poursuivre après cette étape : les étapes suivantes n’ont peut-être pas été exécutées. Vérifiez l’exécution du flux de l’approbation, puis poursuivez-la ou annulez-la.', approvalReturnedTitle: 'Renvoyé pour révision', approvalReturnedBody: 'Votre demande sur {{object}} {{record}} doit être retravaillée avant de pouvoir être approuvée.', approvalRequestInfoTitle: 'Informations complémentaires demandées', @@ -827,6 +841,8 @@ export const ptBRMessages: ApprovalMessages = { approvalAutoRejectedBody: 'Sua solicitação sobre {{object}} {{record}} excedeu o limite de revisões ({{limit}}) e foi rejeitada.', approvalAbandonedTitle: 'A aprovação não foi concluída', approvalAbandonedBody: 'A aprovação de {{object}} {{record}} parou entre duas de suas etapas, por isso não foi concluída e o registro voltou a um status aberto. Envie-o novamente quando estiver pronto.', + approvalFlowNotContinuedTitle: 'O fluxo da aprovação não continuou', + approvalFlowNotContinuedBody: 'A aprovação de {{object}} {{record}} foi decidida em sua última etapa e a decisão foi gravada, mas não se viu o fluxo continuar depois dessa etapa, então as etapas seguintes podem não ter sido executadas. Verifique a execução do fluxo da aprovação e continue-a ou cancele-a.', approvalReturnedTitle: 'Devolvido para revisão', approvalReturnedBody: 'Sua solicitação sobre {{object}} {{record}} precisa de ajustes antes de poder ser aprovada.', approvalRequestInfoTitle: 'Mais informações solicitadas', @@ -914,6 +930,8 @@ export const ruMessages: ApprovalMessages = { approvalAutoRejectedBody: 'Ваш запрос по {{object}} {{record}} превысил лимит доработок ({{limit}}) и был отклонён.', approvalAbandonedTitle: 'Согласование не завершено', approvalAbandonedBody: 'Согласование {{object}} {{record}} остановилось между двумя шагами, поэтому не завершилось, и запись возвращена в открытый статус. Отправьте её снова, когда она будет готова.', + approvalFlowNotContinuedTitle: 'Процесс согласования не продолжился', + approvalFlowNotContinuedBody: 'Согласование {{object}} {{record}} было решено на последнем шаге, и решение записано, но не видно, чтобы процесс продолжился после этого шага, поэтому следующие шаги могли не выполниться. Проверьте запуск процесса согласования и продолжите или отмените его.', approvalReturnedTitle: 'Возвращено на доработку', approvalReturnedBody: 'Ваш запрос по {{object}} {{record}} нужно доработать, прежде чем его можно будет одобрить.', approvalRequestInfoTitle: 'Запрошены дополнительные сведения', @@ -1001,6 +1019,8 @@ export const deMessages: ApprovalMessages = { approvalAutoRejectedBody: 'Ihre Anfrage zu {{object}} {{record}} hat das Überarbeitungslimit ({{limit}}) überschritten und wurde abgelehnt.', approvalAbandonedTitle: 'Genehmigung nicht abgeschlossen', approvalAbandonedBody: 'Die Genehmigung zu {{object}} {{record}} hat zwischen zwei ihrer Schritte angehalten. Sie wurde nicht abgeschlossen, und der Datensatz wurde auf einen offenen Status zurückgesetzt. Reichen Sie ihn erneut ein, wenn er bereit ist.', + approvalFlowNotContinuedTitle: 'Der Ablauf der Genehmigung wurde nicht fortgesetzt', + approvalFlowNotContinuedBody: 'Die Genehmigung zu {{object}} {{record}} wurde in ihrem letzten Schritt entschieden und die Entscheidung geschrieben, aber ihr Ablauf wurde nach diesem Schritt nicht fortgesetzt gesehen, sodass die folgenden Schritte möglicherweise nicht ausgeführt wurden. Prüfen Sie den Ablauf der Genehmigung und setzen Sie ihn fort oder brechen Sie ihn ab.', approvalReturnedTitle: 'Zur Überarbeitung zurückgesendet', approvalReturnedBody: 'Ihre Anfrage zu {{object}} {{record}} muss überarbeitet werden, bevor sie genehmigt werden kann.', approvalRequestInfoTitle: 'Weitere Informationen angefordert', @@ -1088,6 +1108,8 @@ export const koMessages: ApprovalMessages = { approvalAutoRejectedBody: '{{object}} {{record}}이(가) 수정 횟수 한도({{limit}})를 넘어 반려되었습니다.', approvalAbandonedTitle: '승인이 완료되지 않았습니다', approvalAbandonedBody: '{{object}} {{record}}의 승인이 두 단계 사이에서 멈춰 완료되지 않았고, 레코드는 열린 상태로 되돌아갔습니다. 준비가 되면 다시 제출하세요.', + approvalFlowNotContinuedTitle: '승인 흐름이 계속되지 않았습니다', + approvalFlowNotContinuedBody: '{{object}} {{record}}의 승인은 마지막 단계에서 결정되었고 결정도 기록되었지만, 그 단계 이후 흐름이 계속되는 것이 확인되지 않아 이후 단계가 실행되지 않았을 수 있습니다. 승인의 흐름 실행을 확인하고 계속하거나 취소하세요.', approvalReturnedTitle: '수정 요청됨', approvalReturnedBody: '{{object}} {{record}}을(를) 승인받으려면 먼저 수정해야 합니다.', approvalRequestInfoTitle: '추가 정보 요청', diff --git a/packages/services/service-messaging/src/preference-options.ts b/packages/services/service-messaging/src/preference-options.ts index f5d9b3fde07..dd1084bc933 100644 --- a/packages/services/service-messaging/src/preference-options.ts +++ b/packages/services/service-messaging/src/preference-options.ts @@ -55,6 +55,7 @@ export const PLATFORM_NOTIFICATION_TOPICS: readonly string[] = [ 'approval.comment', 'approval.escalated', + 'approval.flow_not_continued', 'approval.ooo_skipped', 'approval.ooo_substituted', 'approval.reassigned', From ae94d6ccaefa602146f936852c30d44b717da4e3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 15:17:32 +0000 Subject: [PATCH 02/23] test(approvals): the cases the reworked reconciler fails, before the fix (ADR-0162 item 8) Thirteen cases for contract review 7257527251 of the plugin half, each red on the tree as it stood at 46ca8ff561: - M4: a sibling child whose read threw once at the door, a child with no row under a run that ended at its step, a tree past the 200 runs one judgement reads, and a run read to its end over an unread child whose own row is gone by the next pass. Each answers finished on the second pass. - S1, nested: a decision in a child run whose parent is parked at its subflow between two steps, one level and two levels down, and under a map whose items are not records (N8). Each answers in progress for good. - S7 by seat reading 7257555103: a door that leaves the next request pending keeps nothing; a child whose row is gone under a run that went on past it holds the approval; and the failure-route pin, whose child with no row is written within the bound. - S6: a note written between the reading and the kept write is erased. - S8: the notice that the flow did not go on is sent on a refused write. - N9: a placed approval that held nothing back leaves no line in the log. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jSFBvAjuff7Brz9Rf9 --- ...roval-reconciler-37767.integration.test.ts | 328 ++++++++++++++++++ 1 file changed, 328 insertions(+) diff --git a/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts index bf73aaf22ec..e0f78e83a7e 100644 --- a/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts @@ -126,6 +126,27 @@ const FLOWS = [ [edge('start', 'first'), ...decided('first', 'second'), edge('second', 'third', 'approve'), edge('second', 'boom', 'reject'), edge('second', 'revise', 'revise'), { id: 'back', source: 'revise', target: 'second', label: 'resubmit', type: 'back' }, edge('boom', 'third'), edge('boom', 'end', undefined, 'fault'), ...decided('third', 'end')]), + // ── The fixtures of the rebuild on contract review 7257527251 ── + // A child that fails, unrouted. + flow('child_fail', [mark('boom')], [edge('start', 'boom'), edge('boom', 'end')]), + // The only step, then a child that fails: the run fails at `sub`, after its last step. + flow('fail_after_last', [step('only', 'approver'), { id: 'sub', type: 'subflow', label: 'Sub', config: { flowName: 'child_fail' } }, mark('after')], + [edge('start', 'only'), edge('only', 'sub', 'approve'), edge('only', 'end', 'reject'), edge('sub', 'after'), edge('after', 'end')]), + // The same, with the child's failure routed on: the run goes on along the fault edge and completes. + flow('fault_after_last', [step('only', 'approver'), { id: 'sub', type: 'subflow', label: 'Sub', config: { flowName: 'child_fail' } }, mark('after')], + [edge('start', 'only'), edge('only', 'sub', 'approve'), edge('only', 'end', 'reject'), edge('sub', 'after'), edge('sub', 'after', undefined, 'fault'), edge('after', 'end')]), + // A child between the two steps, which ends inside the passage. + flow('sub_between', [step('first', 'approver'), { id: 'mid', type: 'subflow', label: 'Mid', config: { flowName: 'child_noop' } }, step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'mid', 'approve'), edge('first', 'end', 'reject'), edge('mid', 'second'), ...decided('second', 'end')]), + // Two levels down: the root delegates to a middle run, which delegates the first step; the second step is the root's. + flow('mid_one_step', [{ id: 'inner', type: 'subflow', label: 'Inner', config: { flowName: 'child_one_step' } }], [edge('start', 'inner'), edge('inner', 'end')]), + flow('root_mid_then_second', [{ id: 'mid', type: 'subflow', label: 'Middle', config: { flowName: 'mid_one_step' } }, step('second', 'approver2')], + [edge('start', 'mid'), edge('mid', 'second'), ...decided('second', 'end')]), + // A root above the two sibling children: the middle run ends over a child the plugin may not have read. + flow('root_of_two_subs', [{ id: 'mid', type: 'subflow', label: 'Middle', config: { flowName: 'parent_two_subs' } }], [edge('start', 'mid'), edge('mid', 'end')]), + // A map whose two items are not records: each item's step is a step of the parent's record. + flow('first_then_two_items', [step('first', 'approver'), { id: 'each', type: 'map', label: 'Each', config: { flowName: 'child_boom_then_step', collection: [1, 2] } }], + [edge('start', 'first'), edge('first', 'each', 'approve'), edge('first', 'end', 'reject'), edge('each', 'end')]), ]; describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges what no door did', () => { @@ -663,5 +684,312 @@ describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges expect(notified('approval.abandoned')).toEqual([]); expect((await automation.getRun(String(last.flow_run_id)))?.status, 'the pause is left for an operator').toBe('paused'); }); + + describe('the rebuild on contract review 7257527251: the kept reading is safe to judge from', () => { + /** Flows whose runs have no row from the start: trimmed before the plugin read them. */ + let trimmedFlows: Set; + /** Flows for whose runs the run store does not answer. */ + let downFlows: Set; + beforeEach(() => { + trimmedFlows = new Set(); + downFlows = new Set(); + const original = automation.getRun.bind(automation); + (automation as any).getRun = async (id: string, options?: { strict?: boolean }) => { + const run: any = await original(id, options); + const name = String(run?.flowName ?? ''); + if (run && downFlows.has(name)) { + if (options?.strict) throw new Error('the run store did not answer'); + return null; + } + return run && trimmedFlows.has(name) ? null : run; + }; + }); + const statusOf = async (runId: unknown) => (await automation.getRun(String(runId)))?.status; + const lastLine = async (requestId: unknown) => String((await timeline(String(requestId))).at(-1)![2]); + /** Refuse the mirror's write of `approved` on the invoice while `on()` holds. */ + const refuseApproved = (on: () => boolean) => { + const original = ql.update.bind(ql); + (ql as any).update = async (o: string, data: any, options?: any) => { + if (on() && o === 'crm_invoice' && data?.approval_status === 'approved') throw new Error('VALIDATION_FAILED: a rule of the app'); + return original(o, data, options); + }; + }; + + it('[M4] a sibling child whose read threw at the door is read on the next pass: abandoned, not finished', async () => { + await start('parent_two_subs', 'crm_invoice', 'i_m4_throw'); + throwOn.add('boom'); + downFlows.add('child_boom_then_step'); + await decide('i_m4_throw', 'approve', 'approver'); + const [first] = await requestsOn('i_m4_throw'); + expect(await statusOf(first.record_run_id), 'the carrying run completed').toBe('completed'); + expect(await field('crm_invoice', 'i_m4_throw'), 'the door cannot tell').toBe('pending'); + expect(await marks('i_m4_throw')).toEqual([true]); + + downFlows.clear(); + expect((await svc.reconcileMarkedApprovals()).judged, 'the store answers now: the sibling is read').toEqual({ abandoned: 1 }); + expect(await steps('i_m4_throw'), 'the second step was never asked').toEqual([['only', 'approved']]); + expect(await field('crm_invoice', 'i_m4_throw')).toBe('recalled'); + expect(await lastLine(first.id)).toMatch(/its node 'boom' failed between two steps/); + expect(await marks('i_m4_throw')).toEqual([false]); + }); + + it('[M4] a child with no row under a run that ended at its step: nothing is written within the bound on any pass; past it, the one rule and the notice', async () => { + await start('fail_after_last', 'crm_invoice', 'i_m4_norow'); + throwOn.add('boom'); + trimmedFlows.add('child_fail'); + await settle(decide('i_m4_norow', 'approve', 'approver')); + const [only] = await requestsOn('i_m4_norow'); + expect(await statusOf(only.record_run_id), 'the run failed at the child\'s step').toBe('failed'); + expect(await field('crm_invoice', 'i_m4_norow'), 'the door cannot tell').toBe('pending'); + notices.length = 0; + + for (const pass of ['the next pass', 'the pass after it']) { + expect((await svc.reconcileMarkedApprovals()).judged, `${pass}, within the bound`).toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_m4_norow'), pass).toBe('pending'); + expect(await marks('i_m4_norow'), pass).toEqual([true]); + } + expect(notified('approval.flow_not_continued')).toEqual([]); + + await age('i_m4_norow'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_m4_norow'), 'the last step: its decision stands').toBe('approved'); + expect(await marks('i_m4_norow')).toEqual([false]); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + }); + + it('[M4] past the 200 runs one judgement reads: cannot tell, and the next pass reads on to the failure the first never reached', async () => { + await start('two_step', 'crm_invoice', 'i_m4_cap'); + await decide('i_m4_cap', 'approve', 'approver'); + await withoutDoor(() => decide('i_m4_cap', 'approve', 'approver2')); + const [, last] = await requestsOn('i_m4_cap'); + const rootId = String(last.record_run_id); + // A double of the run store for a tree the engine does not build + // cheaply: the run that carries the record names 250 child runs, each + // completed, and the last holds a failure the flow routed between two + // steps (matched by its node id, as a run of an unknown flow is). + const fan = Array.from({ length: 250 }, (_, i) => `run_fan_${i}`); + const at = new Date().toISOString(); + const real = automation.getRun.bind(automation); + (automation as any).getRun = async (id: string, options?: { strict?: boolean }) => { + if (id === rootId) { + const run: any = await real(id, options); + return { ...run, steps: [...run.steps, { nodeId: 'fan', nodeType: 'subflow', status: 'success', startedAt: at, childRunIds: fan }] }; + } + const i = fan.indexOf(id); + if (i < 0) return real(id, options); + return { + id, flowName: 'fan_child', status: 'completed', startedAt: at, completedAt: at, + trigger: { object: 'crm_invoice', recordId: 'i_m4_cap' }, + steps: i === fan.length - 1 ? [{ nodeId: 'first', nodeType: 'mark', status: 'failure', startedAt: at }] : [], + }; + }; + + expect((await svc.reconcileMarkedApprovals()).judged, 'the first 200 runs').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_m4_cap')).toBe('pending'); + expect(await marks('i_m4_cap')).toEqual([false, true]); + + expect((await svc.reconcileMarkedApprovals()).judged, 'the runs past them').toEqual({ abandoned: 1 }); + expect(await field('crm_invoice', 'i_m4_cap')).toBe('recalled'); + expect(await lastLine(last.id)).toMatch(/its node 'first' failed between two steps/); + }); + + it('[M4] a run read to its end over a child not read yet, whose own row is gone by the next pass, is not taken as passed', async () => { + await start('root_of_two_subs', 'crm_invoice', 'i_m4_owed'); + throwOn.add('boom'); + downFlows.add('child_boom_then_step'); + await decide('i_m4_owed', 'approve', 'approver'); + const [first] = await requestsOn('i_m4_owed'); + expect(await statusOf(first.record_run_id), 'the root went on past the middle run and completed').toBe('completed'); + expect(await field('crm_invoice', 'i_m4_owed'), 'the door cannot tell').toBe('pending'); + + // The store answers again, and the middle run's row is gone: the + // root's log says it went on past it, but the plugin read that run + // and knows a child of it was never read. + downFlows.clear(); + trimmedFlows.add('parent_two_subs'); + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_m4_owed')).toBe('pending'); + expect(await marks('i_m4_owed')).toEqual([true]); + + await age('i_m4_owed'); + expect((await svc.reconcileMarkedApprovals()).judged, 'placed by the step last decided, which a step can follow').toEqual({ abandoned: 1 }); + expect(await field('crm_invoice', 'i_m4_owed')).toBe('recalled'); + }); + + it('[S1] a decision in a child run whose parent is parked at its subflow between two steps: held within the bound, past it abandoned, and both runs cancelled', async () => { + await start('sub_then_second', 'crm_invoice', 'i_s1'); + await settle(withoutResume(() => decide('i_s1', 'approve', 'approver'))); + const [child] = await requestsOn('i_s1'); + expect(String(child.flow_run_id)).not.toBe(String(child.record_run_id)); + expect(await statusOf(child.flow_run_id), 'the child is parked at its decided step').toBe('paused'); + expect(await statusOf(child.record_run_id), 'the parent is parked at its subflow').toBe('paused'); + expect(await field('crm_invoice', 'i_s1'), 'held at the door').toBe('pending'); + expect(await marks('i_s1')).toEqual([true]); + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound: the run may still be resumed').toEqual({ undetermined: 1 }); + expect(await marks('i_s1')).toEqual([true]); + + await age('i_s1'); + notices.length = 0; + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ abandoned: 1 }); + expect(await steps('i_s1'), 'the decision stays on its request').toEqual([['only', 'approved']]); + expect(await field('crm_invoice', 'i_s1')).toBe('recalled'); + expect(await marks('i_s1')).toEqual([false]); + expect(notified('approval.abandoned')).toEqual([['owner']]); + expect(await lastLine(child.id)).toMatch(/still parked at the step 'only' its decision was recorded on/); + expect(await statusOf(child.flow_run_id), 'nothing resumes the child').toBe('cancelled'); + expect(await statusOf(child.record_run_id), 'nor the parent that waited on it').toBe('cancelled'); + expect((await svc.reconcileMarkedApprovals()).scanned, 'nothing left to judge').toBe(0); + }); + + it('[S1] the same two levels down: the walk reaches the decided step through both parked runs', async () => { + await start('root_mid_then_second', 'crm_invoice', 'i_s1_deep'); + await settle(withoutResume(() => decide('i_s1_deep', 'approve', 'approver'))); + const [child] = await requestsOn('i_s1_deep'); + const root: any = await automation.getRun(String(child.record_run_id)); + const middle = String(root.steps.find((s: any) => s.nodeId === 'mid').childRunIds[0]); + expect(middle).not.toBe(String(child.flow_run_id)); + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound').toEqual({ undetermined: 1 }); + + await age('i_s1_deep'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ abandoned: 1 }); + expect(await field('crm_invoice', 'i_s1_deep')).toBe('recalled'); + expect(await marks('i_s1_deep')).toEqual([false]); + expect([await statusOf(child.flow_run_id), await statusOf(middle), await statusOf(child.record_run_id)]).toEqual(['cancelled', 'cancelled', 'cancelled']); + }); + + it('[S1, N8] the same under a map whose items are not records: the batch above the item run is cancelled with it, and no later item opens', async () => { + await start('first_then_two_items', 'crm_invoice', 'i_n8'); + await decide('i_n8', 'approve', 'approver'); + await settle(withoutResume(() => decide('i_n8', 'approve', 'approver2'))); + const [, item] = await requestsOn('i_n8'); + expect(String(item.flow_run_id)).not.toBe(String(item.record_run_id)); + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound').toEqual({ undetermined: 1 }); + + await age('i_n8'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ abandoned: 1 }); + expect(await field('crm_invoice', 'i_n8')).toBe('recalled'); + expect(await statusOf(item.flow_run_id), 'the item run').toBe('cancelled'); + expect(await statusOf(item.record_run_id), 'the batch that waited on it').toBe('cancelled'); + expect(await steps('i_n8'), 'the second item\'s step never opens on a record that was put back').toEqual([['first', 'approved'], ['second', 'approved']]); + }); + + it('[S7 point 1] a door that leaves the next request pending still reads the runs it can reach, and keeps them', async () => { + await start('sub_between', 'crm_invoice', 'i_s7_door'); + await decide('i_s7_door', 'approve', 'approver'); + const [first, second] = await requestsOn('i_s7_door'); + expect(second.status).toBe('pending'); + const root: any = await automation.getRun(String(first.record_run_id)); + const child = String(root.steps.find((s: any) => s.nodeId === 'mid').childRunIds[0]); + // The child ended inside the passage: no opening could read it (the + // run that was being advanced had not logged its step yet), and the + // door that left the second request pending did. + expect(kept(second)?.ended, 'kept at the door').toContain(child); + }); + + it('[S7 point 2] a child whose row is gone before any read, under a run that went on past its step, is passed: finished at the door, with no notice', async () => { + trimmedFlows.add('child_noop'); + await start('early_sub_two_step', 'crm_invoice', 'i_s7_passed'); + await decide('i_s7_passed', 'approve', 'approver'); + notices.length = 0; + await decide('i_s7_passed', 'approve', 'approver2'); + expect(await field('crm_invoice', 'i_s7_passed'), 'written at the door').toBe('approved'); + expect(await marks('i_s7_passed')).toEqual([false, false]); + expect(notified('approval.flow_not_continued')).toEqual([]); + expect((await svc.reconcileMarkedApprovals()).scanned, 'nothing left to judge').toBe(0); + }); + + it('[S7, the failure route] a run that went on along a fault edge did not go on past the step: its child with no row is held, then placed', async () => { + await start('fault_after_last', 'crm_invoice', 'i_s7_fault'); + throwOn.add('boom'); + trimmedFlows.add('child_fail'); + await decide('i_s7_fault', 'approve', 'approver'); + const [only] = await requestsOn('i_s7_fault'); + const root: any = await automation.getRun(String(only.record_run_id)); + expect(root.status, 'the failure was routed, and the run completed').toBe('completed'); + expect(root.steps.find((s: any) => s.nodeId === 'sub').status).toBe('failure'); + expect(await field('crm_invoice', 'i_s7_fault'), 'not passed: the door cannot tell').toBe('pending'); + expect(await marks('i_s7_fault')).toEqual([true]); + notices.length = 0; + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_s7_fault')).toBe('pending'); + + await age('i_s7_fault'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_s7_fault')).toBe('approved'); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + }); + + it('[S6] a note another writer leaves on the request between the reading and the kept write survives it', async () => { + await start('parent_two_subs', 'crm_invoice', 'i_s6'); + throwOn.add('boom'); + downFlows.add('child_boom_then_step'); + const original = ql.update.bind(ql); + let landed = false; + (ql as any).update = async (o: string, data: any, options?: any) => { + if (!landed && o === 'sys_approval_request' && typeof data?.node_config_json === 'string' && data.node_config_json.includes('"__runsRead"')) { + landed = true; + // The kept reading is on its way to the row. Before it lands, + // another writer puts its notes on the same snapshot. + const [row] = await requestsOn('i_s6'); + await original('sys_approval_request', { + id: row.id, + node_config_json: JSON.stringify({ + ...JSON.parse(String(row.node_config_json)), + __laterStepNotOpened: { node: 'second', at: new Date().toISOString(), reason: 'no approver' }, + __strandedContinuation: { decision: 'approve' }, + }), + }, { context: SYS }); + } + return original(o, data, options); + }; + await decide('i_s6', 'approve', 'approver'); + expect(landed, 'the door kept what it read').toBe(true); + const [row] = await requestsOn('i_s6'); + const snapshot = JSON.parse(String(row.node_config_json)); + expect(snapshot.__laterStepNotOpened?.node, 'the note that a later step could not open').toBe('second'); + expect(snapshot.__strandedContinuation, 'the journal of a failed resume').toEqual({ decision: 'approve' }); + expect(snapshot.__runsRead?.ended, 'and the reading is kept beside them').toContain(String(row.flow_run_id)); + }); + + it('[S8] a refused outcome at a last step that was placed sends no notice that the flow did not go on; the pass on which the write lands sends it', async () => { + await start('two_step', 'crm_invoice', 'i_s8'); + await decide('i_s8', 'approve', 'approver'); + await settle(withoutResume(() => decide('i_s8', 'approve', 'approver2'))); + await age('i_s8'); + let refuse = true; + refuseApproved(() => refuse); + notices.length = 0; + + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_s8'), 'the write was refused').toBe('pending'); + expect(await marks('i_s8')).toEqual([false, true]); + expect(notified('approval.status_mirror_refused'), 'the refusal is told').toEqual([['org_admin']]); + expect(notified('approval.flow_not_continued'), 'no outcome, no notice').toEqual([]); + + refuse = false; + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_s8')).toBe('approved'); + expect(await marks('i_s8')).toEqual([false, false]); + expect(notified('approval.flow_not_continued'), 'with the outcome').toEqual([['org_admin']]); + }); + + it('[N9] where nothing was held back, a placed approval leaves a line in the log; nothing is written, told or cancelled', async () => { + await start('two_step', 'crm_ticket', 't_n9'); + await settle(withoutResume(() => decide('t_n9', 'approve', 'approver'))); + const [first] = await requestsOn('t_n9'); + await age('t_n9'); + infos.length = 0; + notices.length = 0; + const writes = recordWrites('crm_ticket'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ ended: 1 }); + expect(await marks('t_n9')).toEqual([false]); + expect(writes).toEqual([]); + expect(notices).toEqual([]); + expect(await statusOf(first.flow_run_id), 'the pause is left').toBe('paused'); + expect(infos.filter((m) => m.includes('crm_ticket/t_n9')), 'what the reconciler concluded is in the log').toHaveLength(1); + }); + }); }); }); From 724d41e275bc54605f5bb40bef5327f47b7f5709 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 15:28:15 +0000 Subject: [PATCH 03/23] test(approvals): a note that lands while the runs are read, before the fix (ADR-0162 item 8) One more case of the rebuild on contract review 7257527251, red on the base tree: the judgement reads the request, then its runs; a passage of another process notes in between that the step after the last decision could not open. The base tree read the note before the runs, so it answers finished and writes `approved` (expected 'approved' to be 'recalled'). Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jSFBvAjuff7Brz9Rf9 --- ...roval-reconciler-37767.integration.test.ts | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts index e0f78e83a7e..75783c89647 100644 --- a/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts @@ -953,6 +953,39 @@ describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges expect(snapshot.__runsRead?.ended, 'and the reading is kept beside them').toContain(String(row.flow_run_id)); }); + it('[S6] a note that lands while the runs are being read is the judgement\'s: abandoned, not finished', async () => { + await start('two_step', 'crm_invoice', 'i_s6_late'); + await decide('i_s6_late', 'approve', 'approver'); + const original = automation.getRun.bind(automation); + let landed = false; + (automation as any).getRun = async (id: string, options?: { strict?: boolean }) => { + if (!landed && options?.strict) { + landed = true; + // The judgement has read the request and is reading its runs. + // The passage of another process notes that the step after the + // last decision could not open, as `noteLaterStepNotOpened` does. + const row = (await requestsOn('i_s6_late')).at(-1)!; + await ql.update('sys_approval_request', { + id: row.id, + node_config_json: JSON.stringify({ + ...JSON.parse(String(row.node_config_json)), + __laterStepNotOpened: { node: 'third', at: new Date().toISOString(), reason: 'no approver' }, + }), + }, { context: SYS }); + } + return original(id, options); + }; + notices.length = 0; + await decide('i_s6_late', 'approve', 'approver2'); + expect(landed, 'the door read the runs').toBe(true); + expect(await steps('i_s6_late')).toEqual([['first', 'approved'], ['second', 'approved']]); + expect(await field('crm_invoice', 'i_s6_late'), 'a later step could not open: the record is not closed').toBe('recalled'); + expect(await marks('i_s6_late')).toEqual([false, false]); + expect(notified('approval.abandoned')).toEqual([['owner']]); + const last = (await requestsOn('i_s6_late')).at(-1)!; + expect(await lastLine(last.id)).toMatch(/its step 'third' could not open \(no approver\)/); + }); + it('[S8] a refused outcome at a last step that was placed sends no notice that the flow did not go on; the pass on which the write lands sends it', async () => { await start('two_step', 'crm_invoice', 'i_s8'); await decide('i_s8', 'approve', 'approver'); From 8dd667ba5209e99fcf6d7a2e31c4d4119df33504 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 15:33:00 +0000 Subject: [PATCH 04/23] fix(approvals): the kept reading is safe to judge from (ADR-0162 item 8) The rebuild of the plugin half on contract review 7257527251. M4: a run is kept as ended, and not read again, only once it was read to an end and every child run its steps name is kept as ended too. A run read to its end over a child not read yet is kept as open and is a seed of the next walk. The walk reads the whole tree before it answers; only a run it cannot read and the 200-read cap end it early. S1: a run parked at a node of the set on a child run says what its child says. The walk reads the child, so the latest request's own run parked at its own node is reached at any depth, and the one rule decides. S7: a door that leaves a request open reads the runs and keeps what it read. A run with no row counts as passed where a run that was read went on past the step that names it: the step succeeded, and the run reached an end or logged a later step and is not parked at that step. A step that failed is never passed, also where the flow routed its failure. S6: the kept reading writes its own key onto the snapshot read again just before the write, and the write is conditional on the column still reading what the key was set on. The note that a later step could not open is read once the runs are read, not before. S8: the administrators are told that the flow did not go on only on the pass whose outcome write landed. N5, N6, N9: the age bound's docblock names the four states; the walk's docblock agrees with itself; a placed approval that held nothing back leaves a line in the log. N8: the cancel of an abandoned approval's parked run goes up through a map whose items are not records, to the run that carries the record. One guard case comes with this commit and is not a failing case of the base tree, which had no such rule to over-reach: a run still parked at the step that names a child did not go on past it. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jSFBvAjuff7Brz9Rf9 --- ...roval-reconciler-37767.integration.test.ts | 39 + .../plugin-approvals/src/approval-service.ts | 688 +++++++++++++----- 2 files changed, 548 insertions(+), 179 deletions(-) diff --git a/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts index 75783c89647..599b2389863 100644 --- a/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts @@ -921,6 +921,45 @@ describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); }); + it('[S7 point 2, its edge] a run still parked at the step that names a child did not go on past it, whatever it logged after', async () => { + await start('two_step', 'crm_invoice', 'i_s7_parked'); + await decide('i_s7_parked', 'approve', 'approver'); + await withoutDoor(() => decide('i_s7_parked', 'approve', 'approver2')); + const [, last] = await requestsOn('i_s7_parked'); + const rootId = String(last.record_run_id); + // A double of the run store for a shape the engine logs in an order + // a fixture cannot fix: after the last step the run is parked at a + // `subflow` no step follows, on a child with no row, and a step on + // another branch of the flow was logged after the visit that parked it. + const at = new Date().toISOString(); + const real = automation.getRun.bind(automation); + (automation as any).getRun = async (id: string, options?: { strict?: boolean }) => { + if (id === 'run_tail_child') return null; + if (id !== rootId) return real(id, options); + const run: any = await real(id, options); + return { + ...run, status: 'paused', completedAt: undefined, + steps: [...run.steps, + { nodeId: 'tail_sub', nodeType: 'subflow', status: 'success', startedAt: at, childRunIds: ['run_tail_child'] }, + { nodeId: 'tail_note', nodeType: 'script', status: 'success', startedAt: at }], + }; + }; + const parkedAt = automation.suspensionOf.bind(automation); + (automation as any).suspensionOf = async (id: string) => (id === rootId + ? { nodeId: 'tail_sub', flowName: 'two_step', correlation: 'subflow:run_tail_child' } + : parkedAt(id)); + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound: no run speaks for the child').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_s7_parked')).toBe('pending'); + expect(await marks('i_s7_parked')).toEqual([false, true]); + + await age('i_s7_parked'); + notices.length = 0; + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_s7_parked')).toBe('approved'); + expect(notified('approval.flow_not_continued'), 'the one rule, with its notice').toEqual([['org_admin']]); + }); + it('[S6] a note another writer leaves on the request between the reading and the kept write survives it', async () => { await start('parent_two_subs', 'crm_invoice', 'i_s6'); throwOn.add('boom'); diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 12e18c216f6..bae79018027 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -1921,26 +1921,45 @@ type RunStepRead = { /** * [ADR-0162 Execution item 8] How many runs one judgement of an approval - * reads, at most. Past it the door answers that it cannot tell, and the - * approval keeps its mark. + * reads, at most, beside those it kept as ended and does not read again. + * Past it the door answers that it cannot tell, and the approval keeps its + * mark. It is also how many runs each list of the kept reading holds + * ({@link RunsRead}). */ const MAX_RUNS_READ_PER_APPROVAL = 200; /** - * [ADR-0162 Execution item 8] How long an approval's mark stands before the - * reconciler reads a run that will not move again as stopped where it stood: - * a run that reports paused while its pause is gone, and a run parked at a - * `subflow` or a `map` whose child run has ended. One hour: far past any - * passage a live process completes (a passage is the work between a decision - * and the next step, run in the same call), and short enough that a record a - * dead process left held is released the same working session. + * [ADR-0162 Execution item 8] How long an approval's marks stand before the + * reconciler reads a run that will not move again as stopped. It is measured + * from the marks: every mark of the approval has stood this long. Within it + * nothing is written for any of the four states it governs, at the + * approval's last step as at any other (ruling 3 on #37767). Past it: + * + * - a run that reports paused while its pause is gone has stopped at the + * last step it logged; + * - a run parked at a `subflow` or a `map` whose child run has ended, has + * no row, or will not go on itself, has stopped at that node; + * - a run with no row that no run the plugin read speaks for, and + * - the latest request's own run still parked at the step its decision was + * recorded on, have each stopped at the step last decided (rulings A3 and + * B2 on #37767, one rule). + * + * One hour: far past any passage a live process completes (a passage is the + * work between a decision and the next step, run in the same call), and + * short enough that a record a dead process left held is released the same + * working session. */ export const RECONCILER_AGE_BOUND_MS = 60 * 60 * 1000; -/** [ADR-0162 Execution item 8] A child run a step names, and whether a `map` step started it. */ +/** + * [ADR-0162 Execution item 8] A child run a step names, whether a `map` step + * started it, and whether the run that names it went on past that step + * (`passed`, {@link childRunsOf}). + */ interface ChildRunRef { readonly id: string; readonly item: boolean; + readonly passed: boolean; } /** @@ -1948,16 +1967,33 @@ interface ChildRunRef { * (`childRunIds`), to read next: every child of a `subflow` step, and every * item run of a `map` step, which the walk reads to tell whether it carries * another record (an item that is a record carries an approval of its own). + * + * `passed` (the seat's reading 7257555103 of ruling A3): the run went on + * past the step that names the child. The step succeeded, and the run + * reached an end of its flow (`reachedAnEnd`) or logged a later step. The + * engine logs one step for each visit of a node, a visit that paused and + * was resumed included, and a run stands at the last step it logged (as + * {@link stopOf} reads it), so a later step says the visit is over and + * every child of it has ended. Two things are never passed: + * + * - the latest visit of the node a paused run is parked at (`parkedAt`), + * whatever was logged after it: a step on another branch of the flow can + * be logged after the visit that parked the run; + * - a step that failed, also where the flow routed its failure and went on + * (the maintainer's pin on that reading): what such a run did after the + * step says nothing of the child. */ -function childRunsOf(steps: readonly RunStepRead[]): ChildRunRef[] { +function childRunsOf(steps: readonly RunStepRead[], reachedAnEnd: boolean, parkedAt?: string): ChildRunRef[] { const out: ChildRunRef[] = []; - for (const s of steps) { - if (!Array.isArray(s?.childRunIds)) continue; + const parkedVisit = parkedAt === undefined ? -1 : steps.map((s) => s?.nodeId).lastIndexOf(parkedAt); + steps.forEach((s, i) => { + if (!Array.isArray(s?.childRunIds)) return; + const passed = s.status === 'success' && i !== parkedVisit && (reachedAnEnd || i < steps.length - 1); for (const id of s.childRunIds) { if (typeof id !== 'string' || !id) continue; - out.push({ id, item: s.nodeType === 'map' }); + out.push({ id, item: s.nodeType === 'map', passed }); } - } + }); return out; } @@ -1977,20 +2013,34 @@ function childOfCorrelation(correlation: string): string | undefined { */ const RUNS_READ_KEY = '__runsRead'; +/** How many times {@link ApprovalService.keepRunsRead} tries its conditional write. */ +const KEEP_RUNS_READ_ATTEMPTS = 3; + /** * [ADR-0162 Execution item 8, ruling A3 on #37767] What the plugin kept of * an approval's runs, in the thin form: * - * - `runs`: every run of the approval it read; - * - `ended`: those a later judgement does not read again: a run read in a - * terminal status, and an item run of a `map` that carries another record; - * - `between`: a failure between two steps it found in a run that ended, - * with its instant, which counts while no later request of the approval + * - `ended`: the runs a later judgement does not read again. A run enters + * it only once it was read to an end and every child run its steps name + * is in it too ({@link keptAsEnded}), so a run kept here never hides a + * run that was not read. An end is a terminal status; an item run of a + * `map` that carries another record; and a run with no row that a run + * the plugin read went on past ({@link childRunsOf}); + * - `open`: the runs read in a terminal status that are not in `ended` + * yet, because a child they name was not read to such an end. The next + * judgement starts from them as well, so they are read again while their + * row lasts; and one whose row is gone by then is not taken as passed, + * since nothing can name its children any more; + * - `between`: a failure between two steps found in a run that ended, with + * its instant, which counts while no later request of the approval * opened after it (an instant it could not read always counts). + * + * A run that has not ended is not kept: the engine does not trim it, and + * the walk reaches it again from the runs above it. */ interface RunsRead { - readonly runs: readonly string[]; readonly ended: readonly string[]; + readonly open: readonly string[]; readonly between?: { readonly why: string; readonly at: string | null }; } @@ -2001,14 +2051,14 @@ function instantOf(v: unknown): number { /** [ruling A3] What the requests of one approval kept of its runs, merged ({@link RUNS_READ_KEY}). */ function runsReadOf(approval: readonly any[]): RunsRead { - const runs = new Set(); const ended = new Set(); + const open = new Set(); let between: RunsRead['between']; for (const r of approval) { const kept = parseJson>(r?.node_config_json, {})[RUNS_READ_KEY] as Partial | undefined; if (!kept || typeof kept !== 'object') continue; - for (const id of Array.isArray(kept.runs) ? kept.runs : []) if (typeof id === 'string' && id) runs.add(id); for (const id of Array.isArray(kept.ended) ? kept.ended : []) if (typeof id === 'string' && id) ended.add(id); + for (const id of Array.isArray(kept.open) ? kept.open : []) if (typeof id === 'string' && id) open.add(id); const b = kept.between; if (b && typeof b === 'object' && typeof b.why === 'string') { const at = typeof b.at === 'string' ? b.at : null; @@ -2016,14 +2066,124 @@ function runsReadOf(approval: readonly any[]): RunsRead { if (!between || !(instantOf(at) <= instantOf(between.at))) between = { why: b.why, at }; } } - return { runs: [...runs], ended: [...ended], ...(between ? { between } : {}) }; + // A run one request kept as open and a later one as ended has ended. + return { ended: [...ended], open: [...open].filter((id) => !ended.has(id)), ...(between ? { between } : {}) }; } -/** Whether two kept readings say the same. */ +/** Whether two kept readings say the same, whatever the order of their lists. */ function sameRunsRead(a: RunsRead, b: RunsRead): boolean { - return JSON.stringify(a) === JSON.stringify(b); + const same = (x: readonly string[], y: readonly string[]) => x.length === y.length && [...x].sort().join('\n') === [...y].sort().join('\n'); + return same(a.ended, b.ended) && same(a.open, b.open) && JSON.stringify(a.between ?? null) === JSON.stringify(b.between ?? null); +} + +/** + * [ADR-0162 Execution item 8, M4 of contract review 7257527251] Of the runs + * one reading found at an end (`over`), those it may keep as ended. A run + * kept as ended is not read again, and so the child runs its steps name are + * never reached through it again: it is kept only where every child it + * names is kept as ended too, in this reading or an earlier one + * (`settled`). A child whose read threw, a child the reading did not get to + * (the cap), a child that has not ended and a child with no row that no run + * went on past each leave the runs above them to be read again. + */ +function keptAsEnded( + over: ReadonlySet, + childrenOf: ReadonlyMap, + settled: ReadonlySet, +): Set { + const keep = new Set(over); + for (let changed = true; changed;) { + changed = false; + for (const id of keep) { + const children = childrenOf.get(id); + if (!children || children.some((c) => !keep.has(c) && !settled.has(c))) { + keep.delete(id); + changed = true; + } + } + } + return keep; +} + +/** + * [ADR-0162 Execution item 8] What one reading of an approval's runs found, + * for {@link runsReadAfter}: the runs read in a terminal status + * (`terminal`), the item runs of another record (`foreign`), the runs with + * no row (`noRow`), the runs a run that was read went on past (`passed`), + * and the child runs each run that was read names (`childrenOf`). + */ +interface RunsFound { + readonly terminal: Set; + readonly foreign: Set; + readonly noRow: Set; + readonly passed: Set; + readonly childrenOf: Map; +} + +const noRunsFound = (): RunsFound => ({ + terminal: new Set(), foreign: new Set(), noRow: new Set(), passed: new Set(), childrenOf: new Map(), +}); + +/** + * [the seat's reading 7257555103 of ruling A3] The runs with no row that a + * run the plugin read speaks for: it went on past the step that names them, + * so they count as passed at that step. Not one the plugin kept as `open`: + * it read that run to its end over a child it could not read, and a row + * that is gone no longer names that child. + */ +function passedWithNoRow(prior: RunsRead, found: RunsFound): Set { + const open = new Set(prior.open); + return new Set([...found.noRow].filter((id) => found.passed.has(id) && !open.has(id))); +} + +/** + * [ADR-0162 Execution item 8, ruling A3 on #37767] The kept reading after + * one more reading: what was kept before (`prior`) with what this one found. + * `ended` only grows, by the runs {@link keptAsEnded} allows; `open` is the + * runs read in a terminal status, now or before, that are not ended. + * + * Each list holds at most {@link MAX_RUNS_READ_PER_APPROVAL} runs. A run + * left out of `ended` is read again, which costs a read and changes no + * answer. A run left out of `open` could later be taken as passed, so a + * reading whose `open` does not fit keeps the lists as they were. + */ +function runsReadAfter(prior: RunsRead, found: RunsFound, between: RunsRead['between']): RunsRead { + const settled = new Set(prior.ended); + const gone = passedWithNoRow(prior, found); + const childrenOf = new Map(found.childrenOf); + for (const id of [...found.foreign, ...gone]) childrenOf.set(id, []); + const now = keptAsEnded(new Set([...found.terminal, ...found.foreign, ...gone]), childrenOf, settled); + const open = [...new Set([...prior.open, ...found.terminal])].filter((id) => !settled.has(id) && !now.has(id)); + const withBetween = between ? { between } : {}; + if (open.length > MAX_RUNS_READ_PER_APPROVAL) return { ended: prior.ended, open: prior.open, ...withBetween }; + const ended = [...prior.ended, ...[...now].filter((id) => !settled.has(id))].slice(0, MAX_RUNS_READ_PER_APPROVAL); + return { ended, open, ...withBetween }; } +/** + * [ADR-0162 Execution item 8] What one run of an approval's tree answered + * when the door read it (`ApprovalService.readApprovalRun`): + * + * - `undetermined`: it cannot be read or placed now; + * - `no_row`: the engine holds no row for it; + * - `foreign`: an item run of a `map` that carries another record; + * - `in_progress`: parked at a node of the set, on nothing the walk reads; + * - `waits`: parked at a node of the set (`node`) on a child run (`on`), + * which says what this run says (`ApprovalService.waitingRun`); + * - `own_node`: the latest request's own run, parked at that request's node; + * - `read`: everything else. `over`: it is in a terminal status. `stopped`: + * it reports paused at a pause that is gone, past the age bound, so it + * will not go on. `endedWhy`: it ended, or stopped, between two steps. + */ +type ApprovalRunRead = + | { answer: 'undetermined'; why: string } + | { answer: 'no_row' } + | { answer: 'foreign' } + | { answer: 'in_progress'; children: ChildRunRef[] } + | { answer: 'waits'; on: string; item: boolean; node: string; children: ChildRunRef[] } + | { answer: 'own_node'; flow?: string; children: ChildRunRef[] } + | { answer: 'read'; over: boolean; stopped?: boolean; endedWhy?: string; endedAt?: string; children: ChildRunRef[] }; + /** * [ADR-0162 Execution item 8] What the door answered for an approval after it * resumed or cancelled one of its runs (`ApprovalService.judgeApprovalAfterDoor`). @@ -5415,11 +5575,15 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * every run of the approval, from the run that carries the record * (`record_run_id`) down the child runs its steps name, beside what the * approval kept of runs it read before ({@link readCarryingRun}; what this - * reading showed is kept in turn, {@link keepRunsRead}). It answers one of: + * reading showed is kept in turn, {@link keepRunsRead}). It reads and keeps + * at every door, also at one that leaves a request open, whose answer it + * does not need (the seat's reading 7257555103 of ruling A3). It answers + * one of: * * - **in progress**: a request of the approval is pending or returned on * the record, or a run is parked at a pause a step can follow (a node - * of the set the request carries). Nothing is written, and the mark + * of the set the request carries) and is not waiting, through its child + * runs, on the step last decided. Nothing is written, and the mark * stays. * - **finished**: every run completed, stopped on a node outside the set, * or is parked at a pause outside it, and no failure a run routed, nor a @@ -5436,12 +5600,16 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * Past the age bound (`opts.ageBoundMs`, the reconciler's), the last two * have stopped at the step last decided (rulings A3 and B2 on #37767): where * a step can follow it, the approval is abandoned and a run still parked - * there is cancelled ({@link cancelStoppedRun}); where none can, it is - * finished, and the administrators are told that its flow did not go on - * after its last step ({@link reportFlowNotContinued}). + * there is cancelled, with the runs that wait on it ({@link cancelStoppedRun}); + * where none can, it is finished, and once its outcome is on the record the + * administrators are told that its flow did not go on after its last step + * ({@link reportFlowNotContinued}; ruling 3 on #37767: the outcome and the + * notice in one stroke, so a refused write sends no notice, and the pass on + * which the write lands sends it). * * In an approval that holds nothing back, finished and abandoned both end - * the hold: the mark is cleared and nothing is written. Where the approval's + * the hold: the mark is cleared and nothing is written, cancelled or told; + * where a run was placed, a line in the log says so. Where the approval's * latest request was recalled, the writer that recalled it already wrote * what an abandoned approval leaves: the mark is cleared and nothing more is * written. Where no request of the approval carries the mark, it was judged @@ -5479,7 +5647,21 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // Open: a pending request, or a returned one in its revise window, which // is the approval's latest (a resubmitted round stays `returned`). const latest = approval[approval.length - 1] ?? row; - if (approval.some((r) => r.status === 'pending') || latest.status === 'returned') return 'in_progress'; + if (approval.some((r) => r.status === 'pending') || latest.status === 'returned') { + // [the seat's reading 7257555103 of ruling A3, point 1] "At each + // door" is literal: a door that leaves a request open still reads the + // runs it can reach and keeps what it read, so that a child run that + // ended in this passage is read before its row can be trimmed. The + // answer of the reading is not used: an open request is in progress. + try { + await this.keepRunsRead(latest, approval, (await this.readCarryingRun(latest, stamp, approval)).kept); + } catch (err: any) { + this.logger?.warn?.('[approvals] could not read an approval\'s runs at a door that left a request open; the next door reads them', { + request: requestId, error: err?.message ?? String(err), + }); + } + return 'in_progress'; + } const marked = approval.filter(isMarked); if (marked.length === 0) return 'judged'; if (latest.status !== 'approved' && latest.status !== 'rejected') { @@ -5532,6 +5714,15 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega lastStepStopped = reading.why; } why = reading.why; + if (!holds) { + // Nothing was held back, so nothing is written, cancelled or told: + // the log keeps what was concluded of a run that did not go on. + this.logger?.info?.( + `[approvals] after ${door}, the approval of ${row.object_name}/${row.record_id} is over, and held nothing back: ${reading.why} ` + + 'Its marks were cleared; nothing was written, cancelled or told.', + { request: requestId, latest: latest.id, run: reading.parkedRun ?? null }, + ); + } } if (answer === 'finished') { if (!holds) { @@ -5545,8 +5736,14 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega latest.object_name, latest.record_id, field!, String(latest.status), actor, latest.organization_id ?? null, undefined, { request: latest, step: latest.flow_node_id ?? latest.current_step ?? null }, ); - if (lastStepStopped !== undefined) await this.reportFlowNotContinued(latest, lastStepStopped); - if (!refusal) await this.clearMarks(marked); + // [ruling 3 on #37767] The outcome and the administrators' notice in + // one stroke. A refused write keeps the marks and sends no notice + // that the flow did not go on (the mirror reports its refusal); the + // pass on which the write lands sends it. + if (!refusal) { + if (lastStepStopped !== undefined) await this.reportFlowNotContinued(latest, lastStepStopped); + await this.clearMarks(marked); + } return 'finished'; } if (!holds) { @@ -5554,8 +5751,9 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega return 'ended'; } await this.abandonApproval(latest, marked, field!, why); - // [ruling B2] The run parked at the decided step is cancelled, so that - // nothing resumes it on a record that was put back. + // [ruling B2] The run parked at the decided step is cancelled, with the + // runs that wait on it, so that nothing resumes the approval on a + // record that was put back. if (parkedRun) await this.cancelStoppedRun(latest, parkedRun, why); return 'abandoned'; } catch (err: any) { @@ -5569,32 +5767,49 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega } /** - * [ADR-0162 D5, Execution item 8] Read every run of the approval, once no - * request of it is pending or returned on its record, and place where each - * stopped against `stamp`. The walk starts at the run that carries the - * record, the latest request's own run, and every run a request of the - * approval kept as read and not ended ({@link RUNS_READ_KEY}), and follows - * the child runs each delegating step records (`childRunIds` on the step - * log): every `subflow` child, and every `map` item run that does not carry - * another record (an item that is a record carries an approval of its own). - * A run kept as ended is not read again: what it showed is in `kept`. + * [ADR-0162 D5, Execution item 8] Read every run of the approval and place + * where each stopped against `stamp`. The walk starts at the run that + * carries the record, the latest request's own run, and every run the + * approval kept as read to its end over a child not read yet (`open`, + * {@link RunsRead}), and follows the child runs each delegating step + * records (`childRunIds` on the step log): every `subflow` child, and every + * `map` item run that does not carry another record (an item that is a + * record carries an approval of its own). A run kept as ended is not read + * again: what it showed is in the kept reading, and every run below it was + * read to its end before it was kept ({@link keptAsEnded}). + * + * It reads the whole tree before it answers, so that no run it could read + * is left out of what it keeps, and one run's answer does not hide + * another's. A run it cannot read ends the reading at once, since nothing + * can be concluded past it: * * - A run that cannot be read because the store did not answer, that * another process is advancing, or that reports paused with no pause to - * be found (within the age bound): `undetermined`. - * - A run parked at a node of the set: `in_progress`. So is the latest - * request's own run, parked at the latest request's own node, within the - * bound: its decision is recorded and the run may still be resumed. + * be found (within the age bound), and a tree of more runs than one + * judgement reads: `undetermined`. + * - Otherwise, a run parked at a node of the set that is not waiting on + * the step last decided: `in_progress`. A run parked there on a child + * run says what its child says ({@link ApprovalService.waitingRun}): the + * walk reads the child, down to the latest request's own run where that + * is what the runs above it wait on. * - Otherwise, a failure between two steps that no later request answered, * read now or kept, or a later step that could not open (the note on - * `latest`, {@link noteLaterStepNotOpened}): `abandoned`. - * - Otherwise, a run with no row, or the latest request's own run still - * parked at its own node: within the bound `undetermined`, past it - * `placed`: the run has stopped at the step last decided (ruling A3 and - * B2 on #37767, one rule), and {@link judgeApprovalAfterDoor} ends the - * approval by whether a step can follow that step. + * `latest`, read once the runs are read, {@link laterStepNotOpenedOn}): + * `abandoned`. + * - Otherwise, a run with no row that no run read speaks for, or the + * latest request's own run still parked at its own node: within the + * bound `undetermined`, past it `placed`: the run has stopped at the + * step last decided (rulings A3 and B2 on #37767, one rule), and + * {@link judgeApprovalAfterDoor} ends the approval by whether a step can + * follow that step. * - Otherwise `finished`. * + * A run with no row is spoken for where a run that was read went on past + * the step that names it (the seat's reading 7257555103 of ruling A3; + * {@link childRunsOf}, {@link passedWithNoRow}): it counts as passed at + * that step, and is kept as ended. A continuation along a failure route is + * not going on past the step. + * * A failure between two steps is a failure the flow routed, of a node of * the set at the top level of a run (N46 c′: a failure handled in a * `try_catch` region is the author's statement that it needs no later @@ -5607,10 +5822,12 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * {@link RECONCILER_AGE_BOUND_MS}, so a run that has not moved since will * not move again. Then a run that reports paused while its pause is gone is * read as stopped at its last step, and a run parked at a `subflow` or a - * `map` whose child run has ended, or has no row, as stopped at that node. + * `map` whose child run has ended, has no row or will not go on itself, as + * stopped at that node. * - * Every answer carries `kept`: what this reading adds to what the approval - * kept, which the door writes on the latest request. + * Every answer carries `kept`: the kept reading with what this reading + * found ({@link runsReadAfter}), which the door writes on the latest + * request. A reading that ended early keeps what it had read by then. */ private async readCarryingRun( latest: any, @@ -5631,8 +5848,6 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega return { answer: 'undetermined', why: 'no automation engine that reports a run is attached.', runId: rootId }; } - const config = parseJson>(latest.node_config_json, {}); - const notOpened = config[LATER_STEP_NOT_OPENED_KEY] as { node?: unknown; reason?: unknown } | undefined; const lastOpened = approval.reduce((acc, r) => { const at = instantOf(r?.created_at); return Number.isFinite(at) && at > acc ? at : acc; @@ -5640,57 +5855,70 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const ownRuns = new Set(approval.map((r) => (r?.flow_run_id != null ? String(r.flow_run_id) : '')).filter(Boolean)); const prior = runsReadOf(approval); const settled = new Set(prior.ended); - const runs = new Set(prior.runs); - const ended = new Set(prior.ended); + const found = noRunsFound(); let between = prior.between && !(instantOf(prior.between.at) < lastOpened) ? prior.between : undefined; - const kept = (): RunsRead => ({ - runs: [...runs].slice(0, MAX_RUNS_READ_PER_APPROVAL), - ended: [...ended].slice(0, MAX_RUNS_READ_PER_APPROVAL), - ...(between ? { between } : {}), - }); + const kept = (): RunsRead => runsReadAfter(prior, found, between); const ownRunId = latest.flow_run_id != null ? String(latest.flow_run_id) : ''; - const queue: ChildRunRef[] = [{ id: rootId, item: false }]; - if (ownRunId && ownRunId !== rootId) queue.push({ id: ownRunId, item: false }); - for (const id of prior.runs) if (!settled.has(id)) queue.push({ id, item: false }); - const seen = new Set(); - const missing: string[] = []; - let parkedAtOwnNode: { runId: string; flow?: string } | undefined; - let endedWhy: string | undefined; + const queue: ChildRunRef[] = [{ id: rootId, item: false, passed: false }]; + if (ownRunId && ownRunId !== rootId) queue.push({ id: ownRunId, item: false, passed: false }); + for (const id of prior.open) queue.push({ id, item: false, passed: false }); + /** What each run read in this walk answered, in the order read. */ + const read = new Map(); while (queue.length > 0) { const next = queue.shift()!; const runId = next.id; - if (seen.has(runId) || settled.has(runId)) continue; - if (seen.size >= MAX_RUNS_READ_PER_APPROVAL) { - return { answer: 'undetermined', why: `its runs number more than ${MAX_RUNS_READ_PER_APPROVAL}, past what one judgement reads.`, runId, kept: kept() }; + if (next.passed) found.passed.add(runId); + if (read.has(runId) || settled.has(runId)) continue; + if (read.size >= MAX_RUNS_READ_PER_APPROVAL) { + return { + answer: 'undetermined', runId, kept: kept(), + why: `its runs number more than the ${MAX_RUNS_READ_PER_APPROVAL} one judgement reads; the runs read to their end are kept, and the next judgement reads on.`, + }; } - seen.add(runId); const one = await this.readApprovalRun(runId, { stamp, lastOpened, aged, item: next.item && !ownRuns.has(runId), latest, }); + read.set(runId, one); if (one.answer === 'undetermined') return { answer: 'undetermined', why: one.why, runId, kept: kept() }; - if (one.answer === 'missing') { - missing.push(runId); + if (one.answer === 'no_row') { + found.noRow.add(runId); continue; } - runs.add(runId); if (one.answer === 'foreign') { - ended.add(runId); + found.foreign.add(runId); continue; } - if (one.answer === 'in_progress') return { answer: 'in_progress', kept: kept() }; - if (one.answer === 'own_node') { - parkedAtOwnNode = { runId, flow: one.flow }; - } else { - if (one.ended) ended.add(runId); - if (one.endedWhy !== undefined && endedWhy === undefined) { - endedWhy = one.endedWhy; - if (one.ended && !between) between = { why: one.endedWhy, at: one.endedAt ?? null }; - } + found.childrenOf.set(runId, one.children.map((c) => c.id)); + if (one.answer === 'read' && one.over) { + found.terminal.add(runId); + if (one.endedWhy !== undefined && !between) between = { why: one.endedWhy, at: one.endedAt ?? null }; } queue.push(...one.children); + // The child a parked run waits on is read as well, also where no step names it. + if (one.answer === 'waits') queue.push({ id: one.on, item: one.item, passed: false }); + } + + const missing = [...found.noRow].filter((id) => !passedWithNoRow(prior, found).has(id)); + let inProgress = false; + let endedWhy: string | undefined; + let parkedAtOwnNode: { runId: string; flow?: string } | undefined; + for (const [runId, one] of read) { + if (one.answer === 'in_progress') { + inProgress = true; + } else if (one.answer === 'own_node') { + parkedAtOwnNode = { runId, flow: one.flow }; + } else if (one.answer === 'read') { + endedWhy ??= one.endedWhy; + } else if (one.answer === 'waits') { + const says = this.waitingRun(runId, read, settled, aged); + if (says === 'moving') inProgress = true; + else if (says !== 'still') endedWhy ??= says.why; + } } - if (notOpened && typeof notOpened === 'object') { + if (inProgress) return { answer: 'in_progress', kept: kept() }; + const notOpened = await this.laterStepNotOpenedOn(latest); + if (notOpened) { return { answer: 'abandoned', why: `its step '${String(notOpened.node ?? '')}' could not open (${String(notOpened.reason ?? 'no reason recorded')}).`, @@ -5702,7 +5930,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega if (parkedAtOwnNode || missing.length > 0) { const what = parkedAtOwnNode ? `its run '${parkedAtOwnNode.runId}' is still parked at the step '${String(latest.flow_node_id ?? '')}' its decision was recorded on, so the run did not go on after it` - : `its run '${missing[0]}' has no row the automation engine can read, so where it stopped cannot be read`; + : `its run '${missing[0]}' has no row the automation engine can read, and no run that was read went on past it, so where it stopped cannot be read`; if (!aged) return { answer: 'undetermined', why: `${what}, and a process may still be moving it.`, runId: parkedAtOwnNode?.runId ?? missing[0], kept: kept() }; return { answer: 'placed', @@ -5714,11 +5942,75 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega return { answer: 'finished', kept: kept() }; } + /** + * [ADR-0162 Execution item 8, S6 of contract review 7257527251] The note + * that a later step of `latest`'s approval could not open + * ({@link noteLaterStepNotOpened}), read from the row now and not from the + * copy the judgement began with. A passage writes the note before its run + * ends or parks, so a judgement that reads it once the runs are read + * cannot answer from runs that are still over a note it has not seen. + */ + private async laterStepNotOpenedOn(latest: any): Promise<{ node?: unknown; reason?: unknown } | undefined> { + const rows = await this.engine.find('sys_approval_request', { + where: { id: latest.id }, fields: ['id', 'node_config_json'], limit: 1, context: SYSTEM_CTX, + }); + const row: any = (Array.isArray(rows) ? rows[0] : undefined) ?? latest; + const note = parseJson>(row.node_config_json, {})[LATER_STEP_NOT_OPENED_KEY]; + return note && typeof note === 'object' ? note as { node?: unknown; reason?: unknown } : undefined; + } + + /** + * [ADR-0162 D5, Execution item 8] What a run parked at a node of the set on + * a child run says of the approval, once the walk has read that child + * ({@link readCarryingRun}). A parked parent moves only when its child + * does, so it says what the child says: + * + * - `moving`: the child is in progress in its own right, is parked at a + * pause that is not of the set, carries another record, or was not read; + * or, within the age bound, the child has ended or has no row, and the + * engine may still be resuming the parent. The approval is in progress. + * - `still`: the child is the latest request's own run, parked at the step + * its decision was recorded on, or a run that waits on that run in turn. + * The parent says nothing of its own: the one rule places the approval + * by that step (B2 on #37767), at whatever depth the step sits. + * - `{ why }`: past the age bound, the child has ended, has no row, or + * reports paused at a pause that is gone, so nothing will resume the + * parent, between two steps. + */ + private waitingRun( + runId: string, + read: ReadonlyMap, + settled: ReadonlySet, + aged: boolean, + above: ReadonlySet = new Set(), + ): 'moving' | 'still' | { why: string } { + const parent = read.get(runId); + if (parent?.answer !== 'waits' || above.has(runId)) return 'moving'; + const child = read.get(parent.on); + const stopped = (how: string) => ({ + why: `its run '${runId}' is parked at '${parent.node}' on a child run that ${how}, so nothing will resume it, between two steps.`, + }); + const ended = () => (aged ? stopped('has ended') : 'moving' as const); + if (!child) return settled.has(parent.on) ? ended() : 'moving'; + switch (child.answer) { + case 'no_row': return ended(); + case 'own_node': return 'still'; + case 'waits': { + const says = this.waitingRun(parent.on, read, settled, aged, new Set([...above, runId])); + return typeof says === 'string' ? says : stopped('will not go on'); + } + case 'read': + if (child.over) return ended(); + return child.stopped ? stopped('will not go on') : 'moving'; + default: return 'moving'; + } + } + /** * [ADR-0162 D5, Execution item 8] One run of an approval's tree, for * {@link readCarryingRun}: whether it can be read and is still, whether it * is parked between two steps or at the latest request's own node, whether - * it ended (and so is not read again) and ended between two steps, and the + * it is over (a terminal status) and ended between two steps, and the * child runs to read next. `item`: the run is an item run of a `map` that * is not the run of a request of the approval; one that carries a record * other than the approval's is `foreign`, and is not followed. @@ -5726,14 +6018,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega private async readApprovalRun( runId: string, at: { stamp: readonly StampedNode[]; lastOpened: number; aged: boolean; item: boolean; latest: any }, - ): Promise< - | { answer: 'undetermined'; why: string } - | { answer: 'missing' } - | { answer: 'foreign' } - | { answer: 'in_progress' } - | { answer: 'own_node'; flow?: string; children: ChildRunRef[] } - | { answer: 'read'; ended: boolean; endedWhy?: string; endedAt?: string; children: ChildRunRef[] } - > { + ): Promise { const { stamp, lastOpened, aged, item, latest } = at; const automation = this.automation!; let run: { status?: string; flowName?: string; completedAt?: string; trigger?: { object?: string; recordId?: string }; steps?: unknown } | null; @@ -5742,7 +6027,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega } catch (err: any) { return { answer: 'undetermined', why: `the run '${runId}' could not be read (${err?.message ?? err}).` }; } - if (!run) return { answer: 'missing' }; + if (!run) return { answer: 'no_row' }; if (item) { const object = run.trigger?.object; const record = run.trigger?.recordId; @@ -5757,7 +6042,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega } const flow = typeof run.flowName === 'string' ? run.flowName : undefined; const steps = (Array.isArray(run.steps) ? run.steps : []) as RunStepRead[]; - const children = childRunsOf(steps); + let children = childRunsOf(steps, REACHED_AN_END.has(status)); // A failure the flow routed, at the top level of the run, on a node of // the set, after which no request of the approval opened. Read for a @@ -5782,31 +6067,35 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega if (!aged) return { answer: 'undetermined', why: `the run '${runId}' reports paused, and no pause of it can be found.` }; const stop = stopOf(steps, 'failed'); const routed = routedFailure(stop); - if (routed) return { answer: 'read', ended: false, endedWhy: routedWhy(routed), children }; + if (routed) return { answer: 'read', over: false, stopped: true, endedWhy: routedWhy(routed), children }; return { - answer: 'read', ended: false, children, + answer: 'read', over: false, stopped: true, children, ...(stop && standsBetweenSteps(stamp, flow, stop) ? { endedWhy: `its run '${runId}' reports paused at a pause that is gone, so it will not go on, between two steps.` } : {}), }; } + // The run did not go on past the node it is parked at. + children = childRunsOf(steps, false, parked.nodeId); // [ruling B2 on #37767] The latest request's own run, still parked at // the node its decision was recorded on: the run was not resumed. if (String(runId) === String(latest.flow_run_id ?? '') && parked.nodeId === String(latest.flow_node_id ?? '')) { return { answer: 'own_node', flow: parked.flowName ?? flow, children }; } if (standsBetweenSteps(stamp, parked.flowName ?? flow, parked.nodeId)) { - const child = typeof parked.correlation === 'string' ? childOfCorrelation(parked.correlation) : undefined; - if (!aged || !child || !(await this.childRunHasEnded(child))) return { answer: 'in_progress' }; - return { - answer: 'read', ended: false, children, - endedWhy: `its run '${runId}' is parked at '${parked.nodeId}' on a child run that has ended, so nothing will resume it, between two steps.`, - }; + // Parked between two steps. On a child run, it says what the child + // says, and the walk reads the child ({@link waitingRun}); on + // anything else, a step can still follow. + const correlation = typeof parked.correlation === 'string' ? parked.correlation : ''; + const child = childOfCorrelation(correlation); + return child + ? { answer: 'waits', on: child, item: correlation.startsWith('map:'), node: parked.nodeId, children } + : { answer: 'in_progress', children }; } // Parked outside the set (M3 of 7255916895): a routed failure before // the pause still ended the approval between two steps. const routed = routedFailure(undefined); - return { answer: 'read', ended: false, children, ...(routed ? { endedWhy: routedWhy(routed) } : {}) }; + return { answer: 'read', over: false, children, ...(routed ? { endedWhy: routedWhy(routed) } : {}) }; } if (!TERMINAL_RUN_STATUSES.has(status)) { return { answer: 'undetermined', why: `the run '${runId}' reports the status '${status}', which the plugin does not place.` }; @@ -5815,53 +6104,66 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const stop = stopOf(steps, status); const routed = routedFailure(stop); if (routed) { - return { answer: 'read', ended: true, endedWhy: routedWhy(routed), endedAt: typeof routed.startedAt === 'string' ? routed.startedAt : undefined, children }; + return { answer: 'read', over: true, endedWhy: routedWhy(routed), endedAt: typeof routed.startedAt === 'string' ? routed.startedAt : undefined, children }; } - if (REACHED_AN_END.has(status)) return { answer: 'read', ended: true, children }; + if (REACHED_AN_END.has(status)) return { answer: 'read', over: true, children }; // A run that ended before the approval's latest request opened did not // stop it: the approval went on. const answered = instantOf(run.completedAt) < lastOpened; const endedAt = typeof run.completedAt === 'string' ? run.completedAt : undefined; if (!stop) { - return { answer: 'read', ended: true, children, ...(answered ? {} : { endedWhy: `its run '${runId}' ended ${status}, at a node the plugin cannot place.`, endedAt }) }; + return { answer: 'read', over: true, children, ...(answered ? {} : { endedWhy: `its run '${runId}' ended ${status}, at a node the plugin cannot place.`, endedAt }) }; } if (!answered && standsBetweenSteps(stamp, flow, stop)) { - return { answer: 'read', ended: true, endedWhy: `its run '${runId}' ended ${status} at node '${stop}', between two steps.`, endedAt, children }; - } - return { answer: 'read', ended: true, children }; - } - - /** - * [ADR-0162 Execution item 8] Whether `runId`, a child a parked run waits - * on, has ended: read in a terminal status, or with no row (it will not - * answer the run that waits on it). A store that does not answer is not - * an answer. - */ - private async childRunHasEnded(runId: string): Promise { - if (typeof this.automation?.getRun !== 'function') return false; - try { - const run = await this.automation.getRun(runId, { strict: true }); - return !run || (typeof run.status === 'string' && TERMINAL_RUN_STATUSES.has(run.status)); - } catch { - return false; + return { answer: 'read', over: true, endedWhy: `its run '${runId}' ended ${status} at node '${stop}', between two steps.`, endedAt, children }; } + return { answer: 'read', over: true, children }; } /** * [ADR-0162 Execution item 8, ruling A3 on #37767] Keep `kept` on - * `latest`'s snapshot ({@link RUNS_READ_KEY}), where it adds to what the - * approval kept; `latest` is updated in place, so a later write of its - * snapshot in the same judgement carries it. Best-effort: a write that - * fails leaves the runs to be read again. + * `latest`'s snapshot ({@link RUNS_READ_KEY}), where it differs from what + * the approval kept; `latest` is updated in place, so a later write of its + * snapshot in the same judgement carries it. + * + * The reading is a cache of what the runs showed, and the snapshot also + * holds facts other writers leave between this judgement's read of the row + * and this write: the note that a later step could not open + * (`__laterStepNotOpened`) and the journal of a failed resume + * (`__strandedContinuation`). So it writes its own key only, onto the + * snapshot read again just before the write, and the write is conditional: + * it lands only while the column still reads what the key was set on. A + * write that finds the column changed reads it again, at most + * {@link KEEP_RUNS_READ_ATTEMPTS} times. It can therefore not write a + * stale snapshot over another writer's note, whenever that note lands. + * + * Best-effort: a reading that is not kept leaves the runs to be read again. */ private async keepRunsRead(latest: any, approval: readonly any[], kept: RunsRead | undefined): Promise { if (!kept || !latest?.id) return; if (sameRunsRead(runsReadOf(approval), kept)) return; - const snapshot = parseJson>(latest.node_config_json, {}); - const node_config_json = JSON.stringify({ ...snapshot, [RUNS_READ_KEY]: kept }); try { - await this.engine.update('sys_approval_request', { id: latest.id, node_config_json }, { context: SYSTEM_CTX }); - latest.node_config_json = node_config_json; + for (let attempt = 0; attempt < KEEP_RUNS_READ_ATTEMPTS; attempt++) { + const rows = await this.engine.find('sys_approval_request', { + where: { id: latest.id }, fields: ['id', 'node_config_json'], limit: 1, context: SYSTEM_CTX, + }); + const current: any = Array.isArray(rows) ? rows[0] : undefined; + if (!current) return; + const before: unknown = current.node_config_json; + const node_config_json = JSON.stringify({ ...parseJson>(before, {}), [RUNS_READ_KEY]: kept }); + // The predicate form: the engine answers how many rows it wrote. + const landed = await this.engine.update('sys_approval_request', { node_config_json }, { + where: { id: latest.id, node_config_json: typeof before === 'string' ? before : { $null: true } }, + multi: true, context: SYSTEM_CTX, + }); + if (Number(landed) > 0) { + latest.node_config_json = node_config_json; + return; + } + } + this.logger?.warn?.('[approvals] could not keep what was read of an approval\'s runs: its request\'s snapshot kept changing under the write; the next judgement reads them again', { + request: latest.id, + }); } catch (err: any) { this.logger?.warn?.('[approvals] could not keep what was read of an approval\'s runs; the next judgement reads them again', { request: latest.id, error: err?.message ?? String(err), @@ -5871,14 +6173,15 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega /** * [ADR-0162 Execution item 8, ruling A3 on #37767] What a request that is - * opening keeps of its approval's runs: every run the plugin can read - * from the run that carries the record and the request's own run, down the - * child runs their steps name, with those that ended (and the item runs of - * another record) kept as ended. Every failure before this opening is - * answered by it, so none is kept. A run being advanced is read from what - * it logged when it last paused, so the run opening the approval's first - * request, which has logged nothing yet, is read at the first door. - * `undefined` where there is nothing to read. Best-effort and never + * opening keeps of its approval's runs: what the plugin can read from the + * run that carries the record, the request's own run and the runs the + * approval kept as open, down the child runs their steps name, kept by the + * rule every reading keeps by ({@link runsReadAfter}): a run is kept as + * ended only once every child it names is. Every failure before this + * opening is answered by it, so none is kept. A run being advanced is read + * from what it logged when it last paused, so the run opening the + * approval's first request, which has logged nothing yet, is read at the + * first door. `undefined` where nothing is kept. Best-effort and never * throws: a run it cannot read is read at the next door. */ private async runsReadAtOpening(row: { @@ -5892,16 +6195,17 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega fields: ['id', 'flow_run_id', 'node_config_json'], limit: 500, context: SYSTEM_CTX, })) ?? []; const prior = runsReadOf(approval); + const settled = new Set(prior.ended); const ownRuns = new Set([...approval.map((r) => String(r?.flow_run_id ?? '')), String(row.flow_run_id ?? '')].filter(Boolean)); - const runs = new Set(prior.runs); - const ended = new Set(prior.ended); - const queue: ChildRunRef[] = [{ id: rootId, item: false }]; - if (row.flow_run_id && String(row.flow_run_id) !== rootId) queue.push({ id: String(row.flow_run_id), item: false }); - for (const id of prior.runs) if (!ended.has(id)) queue.push({ id, item: false }); + const found = noRunsFound(); + const queue: ChildRunRef[] = [{ id: rootId, item: false, passed: false }]; + if (row.flow_run_id && String(row.flow_run_id) !== rootId) queue.push({ id: String(row.flow_run_id), item: false, passed: false }); + for (const id of prior.open) queue.push({ id, item: false, passed: false }); const seen = new Set(); while (queue.length > 0 && seen.size < MAX_RUNS_READ_PER_APPROVAL) { - const { id, item } = queue.shift()!; - if (seen.has(id) || ended.has(id)) continue; + const { id, item, passed } = queue.shift()!; + if (passed) found.passed.add(id); + if (seen.has(id) || settled.has(id)) continue; seen.add(id); let run: { status?: string; trigger?: { object?: string; recordId?: string }; steps?: unknown } | null; try { @@ -5909,19 +6213,24 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega } catch { continue; } - if (!run) continue; - runs.add(id); + if (!run) { + found.noRow.add(id); + continue; + } const record = run.trigger?.recordId; if (item && !ownRuns.has(id) && record != null && record !== '' && (String(record) !== String(row.record_id) || (run.trigger?.object != null && String(run.trigger.object) !== String(row.object_name)))) { - ended.add(id); + found.foreign.add(id); continue; } - if (typeof run.status === 'string' && TERMINAL_RUN_STATUSES.has(run.status)) ended.add(id); - queue.push(...childRunsOf((Array.isArray(run.steps) ? run.steps : []) as RunStepRead[])); - } - if (runs.size === 0) return undefined; - return { runs: [...runs].slice(0, MAX_RUNS_READ_PER_APPROVAL), ended: [...ended].slice(0, MAX_RUNS_READ_PER_APPROVAL) }; + const status = typeof run.status === 'string' ? run.status : ''; + const children = childRunsOf((Array.isArray(run.steps) ? run.steps : []) as RunStepRead[], REACHED_AN_END.has(status)); + found.childrenOf.set(id, children.map((c) => c.id)); + if (TERMINAL_RUN_STATUSES.has(status)) found.terminal.add(id); + queue.push(...children); + } + const kept = runsReadAfter(prior, found, undefined); + return kept.ended.length === 0 && kept.open.length === 0 ? undefined : kept; } catch (err: any) { this.logger?.warn?.('[approvals] could not read an approval\'s runs as its request opened; the next door reads them', { error: err?.message ?? String(err), @@ -6067,11 +6376,20 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega /** * [ADR-0162 Execution item 8, ruling B2 on #37767] Cancel the run of an * approval that was abandoned while the run stood parked at the step its - * decision was recorded on, and the runs above it that wait on it through - * a `subflow` (cut below a `map`, whose batch stays a batch), deepest - * first: nothing resumes the approval on a record that was put back. A - * cancel that fails is logged; the approval stays abandoned, and the door - * that continues a restored run refuses it. + * decision was recorded on, and the runs above it that wait on it, up to + * the run that carries the record, deepest first: nothing resumes the + * approval on a record that was put back. + * + * The chain goes through a `map` as through a `subflow`. A `map` between + * the run that carries the record and the parked run has items that are + * not records, so its items are steps of this one approval: the batch is + * cancelled with its item, and is not woken to start the next item, which + * would open a step of the abandoned approval. (A batch whose items are + * records sits above the run that carries the record, and is not in the + * chain.) + * + * A cancel that fails is logged; the approval stays abandoned, and the + * door that continues a restored run refuses it. */ private async cancelStoppedRun(latest: any, runId: string, why: string): Promise { if (typeof this.automation?.cancelRun !== 'function') { @@ -6083,6 +6401,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const chain = await this.voidedRunChain( String(latest.id), runId, latest.record_run_id ? String(latest.record_run_id) : undefined, 'whose approval was abandoned when its run did not go on', + { throughMap: true }, ); const reason = `the approval of request ${String(latest.id)} was abandoned: ${why}`; for (const id of [...chain].reverse()) { @@ -6103,7 +6422,8 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * last step and its outcome written, while its flow was not seen to go on * after that step, so the flow's nodes after it may not have run. The run's * pause, where it has one, is left for an operator to continue or cancel. - * Sent once per request. + * Sent once per request, and only on the pass whose outcome write landed + * (ruling 3 on #37767). */ private async reportFlowNotContinued(latest: any, why: string): Promise { const object = String(latest.object_name); @@ -9462,12 +9782,16 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * below its lowest `map:` link. `[runId]` alone when there is nothing to * walk (no record run, silently), or when the walk cannot be completed * (told at `warn`). + * + * `throughMap` is {@link cancelStoppedRun}'s: the chain is not cut at a + * `map:` link, so the batch and the runs above it are in it. */ private async voidedRunChain( requestId: string, runId: string, recordRunId: string | undefined, whose = 'whose approval a record delete voided', + opts?: { throughMap?: boolean }, ): Promise { if (!recordRunId || recordRunId === runId) return [runId]; const alone = (why: string, error?: unknown): string[] => { @@ -9489,7 +9813,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const correlation: string = parked?.correlation ?? ''; if (correlation.startsWith('map:')) { // A batch stays a batch: the chain starts again below it. - chain.length = 0; + if (!opts?.throughMap) chain.length = 0; current = correlation.slice('map:'.length) || undefined; } else if (correlation.startsWith('subflow:')) { current = correlation.slice('subflow:'.length) || undefined; @@ -11637,12 +11961,18 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * will not move again (rulings A3 and B2 on #37767): a run that reports * paused while its pause is gone, a run parked at a `subflow` or a `map` * whose child run has ended or has no row, and, as one rule, a run with no - * row the engine can read and the latest request's own run still parked - * at the step its decision was recorded on, each of which has stopped at - * the step last decided. Where a step can follow it, the approval is - * abandoned (and a run still parked there is cancelled); where none can, - * the outcome is written and the administrators are told that the flow did - * not go on after its last step. + * row that no run read speaks for and the latest request's own run still + * parked at the step its decision was recorded on (at whatever depth below + * the run that carries the record), each of which has stopped at the step + * last decided. Where a step can follow it, the approval is abandoned (and + * a run still parked there is cancelled, with the runs that wait on it); + * where none can, the outcome is written and, once it has landed, the + * administrators are told that the flow did not go on after its last step. + * + * What each judgement reads of the runs is kept on the approval's latest + * request ({@link RunsRead}), so a pass reads on from where the last one + * stopped: a run is not read again only once it and every run below it + * were read to an end. * * A refused outcome or put-back leaves the marks, so the next pass tries it * again; the mirror's notice to the administrators is keyed per request and From dc5895d73dd259cbe43dd3f43df52a327ad7b77a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 15:33:00 +0000 Subject: [PATCH 05/23] fix(approvals): the notice that a flow did not go on says what to do where no run is left N10 of contract review 7257527251. The body ended "continue or cancel it", which a run with no row offers no way to do. It now says both: where the run is still paused, continue or cancel it; where no run is left, check that the steps after the decision were done. All 11 locale packs. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jSFBvAjuff7Brz9Rf9 --- .../src/translations/messages.ts | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/packages/plugins/plugin-approvals/src/translations/messages.ts b/packages/plugins/plugin-approvals/src/translations/messages.ts index 88f3faebc99..96267dbe650 100644 --- a/packages/plugins/plugin-approvals/src/translations/messages.ts +++ b/packages/plugins/plugin-approvals/src/translations/messages.ts @@ -156,7 +156,7 @@ const enSentences = { approvalAbandonedTitle: 'Approval did not finish', approvalAbandonedBody: 'The approval of your {{object}} {{record}} stopped between two of its steps, so it did not finish and the record was put back to an open status. Submit it again when it is ready.', approvalFlowNotContinuedTitle: 'Approval flow did not go on', - approvalFlowNotContinuedBody: 'The approval of {{object}} {{record}} was decided at its last step and the decision was written, but its flow was not seen to go on after that step, so the steps that follow it may not have run. Check the approval\'s flow run, and continue or cancel it.', + approvalFlowNotContinuedBody: 'The approval of {{object}} {{record}} was decided at its last step and the decision was written, but its flow was not seen to go on after that step, so the steps that follow it may not have run. Check the approval\'s flow run: where it is still paused, continue or cancel it; where no run is left, check that the steps after the decision were done.', approvalReturnedTitle: 'Sent back for revision', approvalReturnedBody: 'Your {{object}} {{record}} needs rework before it can be approved.', approvalRequestInfoTitle: 'More information requested', @@ -308,7 +308,7 @@ export const zhCNMessages: ApprovalMessages = { approvalAbandonedTitle: '审批未能完成', approvalAbandonedBody: '您的{{object}} {{record}} 的审批在两个步骤之间停止,未能完成,记录已恢复为未关闭的状态。准备好后请重新提交。', approvalFlowNotContinuedTitle: '审批流程未继续', - approvalFlowNotContinuedBody: '{{object}} {{record}} 的审批已在最后一步作出决定,决定也已写入,但未见其流程在该步之后继续,之后的步骤可能没有执行。请检查该审批的流程运行,并继续或取消它。', + approvalFlowNotContinuedBody: '{{object}} {{record}} 的审批已在最后一步作出决定,决定也已写入,但未见其流程在该步之后继续,之后的步骤可能没有执行。请检查该审批的流程运行:若仍处于暂停,请继续或取消它;若已无运行记录,请核对该决定之后的步骤是否已完成。', approvalReturnedTitle: '已退回修改', approvalReturnedBody: '您的{{object}} {{record}} 需要修改后才能获批。', approvalRequestInfoTitle: '需要补充信息', @@ -397,7 +397,7 @@ export const jaJPMessages: ApprovalMessages = { approvalAbandonedTitle: '承認が完了しませんでした', approvalAbandonedBody: 'あなたの{{object}} {{record}} の承認は 2 つのステップの間で停止したため完了せず、レコードは閉じていないステータスに戻されました。準備ができたら再度申請してください。', approvalFlowNotContinuedTitle: '承認フローが続行されませんでした', - approvalFlowNotContinuedBody: '{{object}} {{record}} の承認は最後のステップで決定され、その決定は書き込まれましたが、フローがそのステップの後に続行されたことを確認できないため、後続のステップが実行されていない可能性があります。承認のフロー実行を確認し、続行またはキャンセルしてください。', + approvalFlowNotContinuedBody: '{{object}} {{record}} の承認は最後のステップで決定され、その決定は書き込まれましたが、フローがそのステップの後に続行されたことを確認できないため、後続のステップが実行されていない可能性があります。承認のフロー実行を確認してください。まだ一時停止中であれば続行またはキャンセルし、実行が残っていなければ、決定の後のステップが行われたかを確認してください。', approvalReturnedTitle: '修正のため差し戻されました', approvalReturnedBody: 'あなたの{{object}} {{record}} は、承認を受ける前に修正が必要です。', approvalRequestInfoTitle: '追加情報が求められています', @@ -486,7 +486,7 @@ export const esESMessages: ApprovalMessages = { approvalAbandonedTitle: 'La aprobación no terminó', approvalAbandonedBody: 'La aprobación de su {{object}} {{record}} se detuvo entre dos de sus pasos, así que no terminó y el registro volvió a un estado abierto. Envíelo de nuevo cuando esté listo.', approvalFlowNotContinuedTitle: 'El flujo de la aprobación no continuó', - approvalFlowNotContinuedBody: 'La aprobación de {{object}} {{record}} se decidió en su último paso y la decisión se escribió, pero no se vio que su flujo continuara después de ese paso, así que es posible que los pasos siguientes no se hayan ejecutado. Revise la ejecución del flujo de la aprobación y continúela o cancélela.', + approvalFlowNotContinuedBody: 'La aprobación de {{object}} {{record}} se decidió en su último paso y la decisión se escribió, pero no se vio que su flujo continuara después de ese paso, así que es posible que los pasos siguientes no se hayan ejecutado. Revise la ejecución del flujo de la aprobación: si sigue en pausa, continúela o cancélela; si ya no queda ninguna ejecución, compruebe que se hicieron los pasos posteriores a la decisión.', approvalReturnedTitle: 'Devuelto para revisión', approvalReturnedBody: 'Su {{object}} {{record}} necesita cambios antes de poder aprobarse.', approvalRequestInfoTitle: 'Se solicita más información', @@ -575,7 +575,7 @@ export const zhHantMessages: ApprovalMessages = { approvalAbandonedTitle: '核准未能完成', approvalAbandonedBody: '你的{{object}} {{record}} 的核准在兩個步驟之間停止,未能完成,記錄已恢復為未關閉的狀態。準備好後請重新送出。', approvalFlowNotContinuedTitle: '核准流程未繼續', - approvalFlowNotContinuedBody: '{{object}} {{record}} 的核准已在最後一步作出決定,決定也已寫入,但未見其流程在該步之後繼續,之後的步驟可能沒有執行。請檢查該核准的流程執行,並繼續或取消它。', + approvalFlowNotContinuedBody: '{{object}} {{record}} 的核准已在最後一步作出決定,決定也已寫入,但未見其流程在該步之後繼續,之後的步驟可能沒有執行。請檢查該核准的流程執行:若仍處於暫停,請繼續或取消它;若已無執行記錄,請核對該決定之後的步驟是否已完成。', approvalReturnedTitle: '已退回修改', approvalReturnedBody: '你的{{object}} {{record}} 需要修改後才能獲得核准。', approvalRequestInfoTitle: '需要補充資訊', @@ -664,7 +664,7 @@ export const arMessages: ApprovalMessages = { approvalAbandonedTitle: 'لم تكتمل الموافقة', approvalAbandonedBody: 'توقفت الموافقة على {{object}} {{record}} بين خطوتين من خطواتها، فلم تكتمل وأُعيد السجل إلى حالة مفتوحة. أعد إرساله عندما يكون جاهزًا.', approvalFlowNotContinuedTitle: 'لم يستمر مسار الموافقة', - approvalFlowNotContinuedBody: 'تم البت في الموافقة على {{object}} {{record}} في خطوتها الأخيرة وكُتب القرار، لكن لم يُرَ مسارها يستمر بعد تلك الخطوة، لذا ربما لم تُنفَّذ الخطوات التي تليها. راجع تشغيل مسار الموافقة، ثم تابعه أو ألغِه.', + approvalFlowNotContinuedBody: 'تم البت في الموافقة على {{object}} {{record}} في خطوتها الأخيرة وكُتب القرار، لكن لم يُرَ مسارها يستمر بعد تلك الخطوة، لذا ربما لم تُنفَّذ الخطوات التي تليها. راجع تشغيل مسار الموافقة: إن كان لا يزال متوقفًا مؤقتًا فتابعه أو ألغِه، وإن لم يبقَ له تشغيل فتحقّق من أن الخطوات التي تلي القرار قد نُفّذت.', approvalReturnedTitle: 'أُعيد للمراجعة', approvalReturnedBody: 'يحتاج طلبك بشأن {{object}} {{record}} إلى تعديل قبل أن تمكن الموافقة عليه.', approvalRequestInfoTitle: 'مطلوب مزيد من المعلومات', @@ -753,7 +753,7 @@ export const frMessages: ApprovalMessages = { approvalAbandonedTitle: 'L’approbation n’a pas abouti', approvalAbandonedBody: 'L’approbation de votre {{object}} {{record}} s’est arrêtée entre deux de ses étapes : elle n’a pas abouti et l’enregistrement est revenu à un statut ouvert. Soumettez-le à nouveau lorsqu’il est prêt.', approvalFlowNotContinuedTitle: 'Le flux de l’approbation n’a pas continué', - approvalFlowNotContinuedBody: 'L’approbation de {{object}} {{record}} a été décidée à sa dernière étape et la décision a été écrite, mais son flux n’a pas été vu se poursuivre après cette étape : les étapes suivantes n’ont peut-être pas été exécutées. Vérifiez l’exécution du flux de l’approbation, puis poursuivez-la ou annulez-la.', + approvalFlowNotContinuedBody: 'L’approbation de {{object}} {{record}} a été décidée à sa dernière étape et la décision a été écrite, mais son flux n’a pas été vu se poursuivre après cette étape : les étapes suivantes n’ont peut-être pas été exécutées. Vérifiez l’exécution du flux de l’approbation : si elle est encore en pause, poursuivez-la ou annulez-la ; s’il n’en reste aucune, vérifiez que les étapes qui suivent la décision ont été faites.', approvalReturnedTitle: 'Renvoyé pour révision', approvalReturnedBody: 'Votre demande sur {{object}} {{record}} doit être retravaillée avant de pouvoir être approuvée.', approvalRequestInfoTitle: 'Informations complémentaires demandées', @@ -842,7 +842,7 @@ export const ptBRMessages: ApprovalMessages = { approvalAbandonedTitle: 'A aprovação não foi concluída', approvalAbandonedBody: 'A aprovação de {{object}} {{record}} parou entre duas de suas etapas, por isso não foi concluída e o registro voltou a um status aberto. Envie-o novamente quando estiver pronto.', approvalFlowNotContinuedTitle: 'O fluxo da aprovação não continuou', - approvalFlowNotContinuedBody: 'A aprovação de {{object}} {{record}} foi decidida em sua última etapa e a decisão foi gravada, mas não se viu o fluxo continuar depois dessa etapa, então as etapas seguintes podem não ter sido executadas. Verifique a execução do fluxo da aprovação e continue-a ou cancele-a.', + approvalFlowNotContinuedBody: 'A aprovação de {{object}} {{record}} foi decidida em sua última etapa e a decisão foi gravada, mas não se viu o fluxo continuar depois dessa etapa, então as etapas seguintes podem não ter sido executadas. Verifique a execução do fluxo da aprovação: se ainda estiver pausada, continue-a ou cancele-a; se não restar nenhuma execução, confira se as etapas após a decisão foram feitas.', approvalReturnedTitle: 'Devolvido para revisão', approvalReturnedBody: 'Sua solicitação sobre {{object}} {{record}} precisa de ajustes antes de poder ser aprovada.', approvalRequestInfoTitle: 'Mais informações solicitadas', @@ -931,7 +931,7 @@ export const ruMessages: ApprovalMessages = { approvalAbandonedTitle: 'Согласование не завершено', approvalAbandonedBody: 'Согласование {{object}} {{record}} остановилось между двумя шагами, поэтому не завершилось, и запись возвращена в открытый статус. Отправьте её снова, когда она будет готова.', approvalFlowNotContinuedTitle: 'Процесс согласования не продолжился', - approvalFlowNotContinuedBody: 'Согласование {{object}} {{record}} было решено на последнем шаге, и решение записано, но не видно, чтобы процесс продолжился после этого шага, поэтому следующие шаги могли не выполниться. Проверьте запуск процесса согласования и продолжите или отмените его.', + approvalFlowNotContinuedBody: 'Согласование {{object}} {{record}} было решено на последнем шаге, и решение записано, но не видно, чтобы процесс продолжился после этого шага, поэтому следующие шаги могли не выполниться. Проверьте запуск процесса согласования: если он ещё приостановлен, продолжите или отмените его; если запуска уже нет, проверьте, что шаги после решения выполнены.', approvalReturnedTitle: 'Возвращено на доработку', approvalReturnedBody: 'Ваш запрос по {{object}} {{record}} нужно доработать, прежде чем его можно будет одобрить.', approvalRequestInfoTitle: 'Запрошены дополнительные сведения', @@ -1020,7 +1020,7 @@ export const deMessages: ApprovalMessages = { approvalAbandonedTitle: 'Genehmigung nicht abgeschlossen', approvalAbandonedBody: 'Die Genehmigung zu {{object}} {{record}} hat zwischen zwei ihrer Schritte angehalten. Sie wurde nicht abgeschlossen, und der Datensatz wurde auf einen offenen Status zurückgesetzt. Reichen Sie ihn erneut ein, wenn er bereit ist.', approvalFlowNotContinuedTitle: 'Der Ablauf der Genehmigung wurde nicht fortgesetzt', - approvalFlowNotContinuedBody: 'Die Genehmigung zu {{object}} {{record}} wurde in ihrem letzten Schritt entschieden und die Entscheidung geschrieben, aber ihr Ablauf wurde nach diesem Schritt nicht fortgesetzt gesehen, sodass die folgenden Schritte möglicherweise nicht ausgeführt wurden. Prüfen Sie den Ablauf der Genehmigung und setzen Sie ihn fort oder brechen Sie ihn ab.', + approvalFlowNotContinuedBody: 'Die Genehmigung zu {{object}} {{record}} wurde in ihrem letzten Schritt entschieden und die Entscheidung geschrieben, aber ihr Ablauf wurde nach diesem Schritt nicht fortgesetzt gesehen, sodass die folgenden Schritte möglicherweise nicht ausgeführt wurden. Prüfen Sie den Ablauf der Genehmigung: Ist er noch pausiert, setzen Sie ihn fort oder brechen Sie ihn ab; ist kein Lauf mehr vorhanden, prüfen Sie, ob die Schritte nach der Entscheidung erledigt wurden.', approvalReturnedTitle: 'Zur Überarbeitung zurückgesendet', approvalReturnedBody: 'Ihre Anfrage zu {{object}} {{record}} muss überarbeitet werden, bevor sie genehmigt werden kann.', approvalRequestInfoTitle: 'Weitere Informationen angefordert', @@ -1109,7 +1109,7 @@ export const koMessages: ApprovalMessages = { approvalAbandonedTitle: '승인이 완료되지 않았습니다', approvalAbandonedBody: '{{object}} {{record}}의 승인이 두 단계 사이에서 멈춰 완료되지 않았고, 레코드는 열린 상태로 되돌아갔습니다. 준비가 되면 다시 제출하세요.', approvalFlowNotContinuedTitle: '승인 흐름이 계속되지 않았습니다', - approvalFlowNotContinuedBody: '{{object}} {{record}}의 승인은 마지막 단계에서 결정되었고 결정도 기록되었지만, 그 단계 이후 흐름이 계속되는 것이 확인되지 않아 이후 단계가 실행되지 않았을 수 있습니다. 승인의 흐름 실행을 확인하고 계속하거나 취소하세요.', + approvalFlowNotContinuedBody: '{{object}} {{record}}의 승인은 마지막 단계에서 결정되었고 결정도 기록되었지만, 그 단계 이후 흐름이 계속되는 것이 확인되지 않아 이후 단계가 실행되지 않았을 수 있습니다. 승인의 흐름 실행을 확인하세요. 아직 일시 중지되어 있으면 계속하거나 취소하고, 남은 실행이 없으면 결정 이후의 단계가 수행되었는지 확인하세요.', approvalReturnedTitle: '수정 요청됨', approvalReturnedBody: '{{object}} {{record}}을(를) 승인받으려면 먼저 수정해야 합니다.', approvalRequestInfoTitle: '추가 정보 요청', From 033c2f6899b819c961cfd00bcf588c18ec9d035e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 15:39:25 +0000 Subject: [PATCH 06/23] docs(approvals): the changeset and the guide say what the rebuilt reconciler does The sentences contract review 7257527251 and its L1 record found ahead of the tree are rewritten to this head: what a tree of more than 200 runs answers, what a trimmed history means for a run that was and was not read, which doors read, and when a run that ended is not read again. The changeset also names `@objectstack/service-messaging`, whose exported topic list gains `approval.flow_not_continued` (S9). Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jSFBvAjuff7Brz9Rf9 --- .changeset/37767-reconciler.md | 13 ++++--- content/docs/automation/approvals.mdx | 50 ++++++++++++++++++--------- 2 files changed, 42 insertions(+), 21 deletions(-) diff --git a/.changeset/37767-reconciler.md b/.changeset/37767-reconciler.md index bbc11de84ec..32e2ce5fddd 100644 --- a/.changeset/37767-reconciler.md +++ b/.changeset/37767-reconciler.md @@ -1,5 +1,6 @@ --- '@objectstack/plugin-approvals': patch +'@objectstack/service-messaging': patch --- feat(approvals): the reconciler, and the door reads every run of an approval (ADR-0162 Execution item 8) @@ -7,14 +8,16 @@ feat(approvals): the reconciler, and the door reads every run of an approval (AD Clause-②: yes (widening) Metadata-protocol: none -Widened: `ApprovalService` gains `reconcileMarkedApprovals(options?)`, which the plugin runs on the sweep clock beside the escalation, dead-run and stranded-request sweeps; the `getRun` member of the automation surface the plugin declares types the step log's `childRunIds`, the run's `trigger` and `completedAt`, and an optional `{ strict }` read; the plugin's message catalog gains `approvalFlowNotContinuedTitle` and `approvalFlowNotContinuedBody` in all 11 locale packs, sent to the organization's administrators on the topic `approval.flow_not_continued`. +Widened: `ApprovalService` gains `reconcileMarkedApprovals(options?)`, which the plugin runs on the sweep clock beside the escalation, dead-run and stranded-request sweeps; the `getRun` member of the automation surface the plugin declares types the step log's `childRunIds`, the run's `trigger` and `completedAt`, and an optional `{ strict }` read; the plugin's message catalog gains `approvalFlowNotContinuedTitle` and `approvalFlowNotContinuedBody` in all 11 locale packs, sent to the organization's administrators on the topic `approval.flow_not_continued`; `PLATFORM_NOTIFICATION_TOPICS` of `@objectstack/service-messaging`, the topics a notification preference may name, gains that topic. Only for an approval the check stamped when it opened (one with a step that can act on an object that declares `closedStates`): -- **The door reads every run of the approval.** Where it read the run that carries the record and the latest request's own run, it now walks the tree from the run that carries the record, following the child runs each delegating step records: every `subflow` child, and every `map` item run that does not carry another record (an item that is a record carries an approval of its own). One run decides for the whole approval: one that another process is advancing, or that the store could not answer for, makes it cannot tell; one parked at a node a step can follow, in progress; one that ended between two steps, abandoned. So a sibling child whose failure the flow routed, a middle run two levels down that failed, an item run that failed before its step, and a run between two others that is being advanced are no longer read as finished. A failure routed to a pause no step follows is read as abandoned, as on the base. A stop is answered where a request of the approval opened after it. A tree of more than 200 runs is cannot tell. -- **The plugin keeps what it read.** At each door, and as each request opens, the approval's latest request keeps, in its config snapshot, the runs the plugin read, which of them ended (and so are not read again), and a failure between two steps it found in a run that ended. A history the automation engine trims afterwards is not needed again, so an approval whose early child run was trimmed, or whose refused outcome is tried again after its run's history went, is judged as it would have been. -- **A run that stopped, placed by the step last decided.** A run the engine has no row for (its history is gone, or a process stopped while advancing it), and the latest request's own run still parked at the step its decision was recorded on (a process stopped before the run was resumed), are cannot tell for an hour from the approval's marks (the age bound). Past it, they have stopped at the step last decided. Where a later step can follow that step, the approval is abandoned: the record is put back, the submitter is told and submits again, the decisions already made stay on their requests, and the run still parked there is cancelled. At the last step, the outcome is written, the administrators are told that the flow did not go on after that step, and the run's pause is left for an operator. -- **The reconciler.** Each pass reads two windows of at most 200 marked requests (`unjudged_since`): the oldest marks, and the next page of a walk over every marked request by id, so that marks which stay cannot keep the newer ones from being read. It judges each approval among them once, as the door would have: it writes the outcome in the name of the request's recorded decider, abandons the approval, or, where nothing was held back, clears the mark and writes nothing. It ends what no door saw: a run that was cancelled, a parent run cancelled while its child's request was pending, and the stopped runs above. Past the age bound it also reads as stopped where it stood a run that reports paused while its pause is gone, and a run parked at a `subflow` or a `map` whose child run has ended or has no row. +- **The door reads every run of the approval.** Where it read the run that carries the record and the latest request's own run, it now walks the tree from the run that carries the record, following the child runs each delegating step records: every `subflow` child, and every `map` item run that does not carry another record (an item that is a record carries an approval of its own). It reads the whole tree before it answers, and one run decides for the whole approval: one that another process is advancing, or that the store could not answer for, makes it cannot tell; otherwise one parked at a node a step can follow, in progress; otherwise one that ended between two steps, abandoned. A run parked at such a node on a child run says what its child says, so the walk reads the child, at any depth. So a sibling child whose failure the flow routed, a middle run two levels down that failed, an item run that failed before its step, and a run between two others that is being advanced are no longer read as finished. A failure routed to a pause no step follows is read as abandoned, as on the base. A stop is answered where a request of the approval opened after it. One judgement reads at most 200 runs beside those it kept as ended: past them it is cannot tell, keeps what it read, and the next judgement reads on. The kept list holds 200 runs, so a tree too large to be finished that way stays cannot tell and keeps its mark. +- **The plugin keeps what it read.** At every door, one that leaves the next request pending included, and as each request opens, the approval's latest request keeps, in its config snapshot (`__runsRead`): the runs that are not read again (`ended`), the runs read to their end over a child run that was not (`open`), and a failure between two steps found in a run that ended. A run is kept as ended only once it was read to an end and every child run its steps name is kept as ended too. So a child whose read failed, a child with no row, and the runs past the 200 one judgement reads are read on the next pass, which starts from the open runs as well, and no pass answers finished over a run it skipped. A run the plugin read before the automation engine trimmed its history is not needed again, so an approval whose refused outcome is tried again after its run's history went is judged as it would have been. +- **A run with no row, under a run that went on past it, is passed.** A run the engine has no row for counts as passed, and is kept as ended, where a run the plugin read went on past the step that names it: that step succeeded, and the run reached an end of its flow, or logged a later step and is not parked at that step. So an early child run trimmed before the plugin read it does not hold the approval back. A step that failed is never passed, also where the flow routed the failure and went on. A run the plugin had read to its end over an unread child, and whose own row is gone since, is not passed either: nothing names that child any more. +- **The kept reading is its own key.** It is written onto the snapshot read again just before the write, and only while the column still reads the same, at most three times. It cannot write a stale snapshot over a note another writer left there (`__laterStepNotOpened`, `__strandedContinuation`). The judgement reads the note that a later step could not open once it has read the runs, so a note that lands while they are read is judged with. +- **A run that stopped, placed by the step last decided.** A run the engine has no row for and that no run the plugin read speaks for (its history is gone, or a process stopped while advancing it), and the latest request's own run still parked at the step its decision was recorded on (a process stopped before the run was resumed), in the run that carries the record or in a child run any number of levels below it, are cannot tell for an hour from the approval's marks (the age bound). Past it, they have stopped at the step last decided. Where a later step can follow that step, the approval is abandoned: the record is put back, the submitter is told and submits again, the decisions already made stay on their requests, and the run still parked there is cancelled, with the runs that wait on it up to the run that carries the record, through a `map` whose items are not records as through a `subflow`. At the last step, the outcome is written and, once that write has landed, the administrators are told that the flow did not go on after that step; the run's pause is left for an operator. A refused write sends no such notice, and the pass on which the write lands sends it. The notice now says what to do in both cases: continue or cancel a run that is still paused, and where no run is left, check that the steps after the decision were done. +- **The reconciler.** Each pass reads two windows of at most 200 marked requests (`unjudged_since`): the oldest marks, and the next page of a walk over every marked request by id, so that marks which stay cannot keep the newer ones from being read. It judges each approval among them once, as the door would have: it writes the outcome in the name of the request's recorded decider, abandons the approval, or, where nothing was held back, clears the mark and writes nothing (where it concluded that a run had stopped, a line in the log says so). It ends what no door saw: a run that was cancelled, a parent run cancelled while its child's request was pending, and the stopped runs above. Past the age bound it also reads as stopped where it stood a run that reports paused while its pause is gone, and a run parked at a `subflow` or a `map` whose child run has ended or has no row. - **A refused write is tried again.** A refused outcome or put-back leaves the marks, and the next pass tries it again. The timeline line and the administrators' notice (keyed per request and status) are left once for one refusal; the same holds for the line an abandoned approval leaves. - **A deleted record.** Where the approval's record was deleted, the reconciler clears the marks of its requests and writes nothing: no retry and no notice. - **The stranded-request report** (`inspectStrandedRequests`) leaves a decided request the check stamped to the door and the reconciler, and still reports a returned one. diff --git a/content/docs/automation/approvals.mdx b/content/docs/automation/approvals.mdx index f9a157b1c7a..9b904051be7 100644 --- a/content/docs/automation/approvals.mdx +++ b/content/docs/automation/approvals.mdx @@ -1647,7 +1647,8 @@ through the steps that started them, every `subflow` child under it, and every an approval of its own). It answers one of: - **In progress.** A request is pending or returned on the record, or a run is - parked at a node between two steps. Nothing is written. + parked at a node between two steps. A run parked there on a child run counts + as what its child run is. Nothing is written. - **Ended between two steps.** A run stopped on a node a step could still follow (it failed or was cancelled there), a failure the flow routed at the top level of a run ended it, to an end or to a pause no step follows, or a later step @@ -1661,23 +1662,39 @@ an approval of its own). It answers one of: who decided it. The platform keeps what it read on the approval's own requests, at each of these -actions and as each request opens: which runs it read, which of them ended, and a -failure between two steps it found in one. A run that ended is not read again, -so a flow run history the platform trims later, as it trims every flow's history, -does not hold the approval. +actions, one that leaves the next request pending included, and as each request +opens: the runs it read to their end, and a failure between two steps it found +in one. A run is not read again once it, and every run its steps started, were +read to their end. Until then it is read again at the next action or sweep, so +a run the platform could not read once is not passed over later. One reading +takes at most 200 runs beside those it does not read again; a larger tree +cannot tell on that reading and is read on at the next, and one too large to +finish that way stays cannot tell. + +The platform trims every flow's run history in time. A run it read before that +is not needed again. A run it never read counts as passed where the history of +a run it did read shows that the flow went on past the step that started it: +that step succeeded, and the flow reached an end or went on to a later step. +Such a run does not hold the approval. A step that failed does not count, also +where the flow routed the failure and went on. Two more states cannot tell at first: a run with no history left to read, which -the platform never read to its end (a process stopped while it was advancing -it), and a decided request whose run is still parked at that request's own step -(a process stopped before the run was resumed). An hour after the approval's -marks were set, either has stopped at the step last decided. Where a later step -could follow that step, the approval is abandoned, above, and a run still parked -there is cancelled, so nothing resumes it; the decisions already made stay on +the platform never read and which no run it read went on past (a process +stopped while it was advancing it), and a decided request whose run is still +parked at that request's own step (a process stopped before the run was +resumed), in the run that carries the record or in a `subflow` or `map` run +below it. An hour after the approval's marks were set, either has stopped at +the step last decided. Where a later step could follow that step, the approval +is abandoned, above, and a run still parked there is cancelled, with the runs +that wait on it, so nothing resumes it; the decisions already made stay on their requests, and the submitter submits again. Where the step was the last, -its decision is written, the organization's administrators are told that the -flow did not go on after that step (the notice `approval.flow_not_continued`), -and the run's pause is left, so that an operator can continue the flow's -remaining nodes or cancel the run. +its decision is written and, once it is on the record, the organization's +administrators are told that the flow did not go on after that step (the notice +`approval.flow_not_continued`). The run's pause is left: where the run is still +paused, an operator can continue the flow's remaining nodes or cancel the run; +where no run is left, check that the steps after the decision were done. A +write that a rule or a hook refuses sends no such notice; the notice goes out +with the write that lands. Every decision on an approval any step of which can act on an object that declares `closedStates` leaves a mark on its request (`unjudged_since`), also @@ -1691,7 +1708,8 @@ progress do not keep the newer ones from being judged. Once the mark has stood for an hour, it also reads as stopped where it stood a run that reports paused while its pause is gone, and a run parked at a `subflow` or a `map` whose child run has ended or has no history left. -Where nothing was held back it clears the mark and writes nothing. A write that +Where nothing was held back it clears the mark and writes nothing; where it +concluded that a run had stopped, a line in the server log says so. A write that a rule or a hook refuses is reported as above, once, and tried again on each sweep while the mark stands. Where the record was deleted, the reconciler clears the mark and writes nothing. From e0eae8b99b474cc3cf93737a325b193bf27f51d8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 15:42:48 +0000 Subject: [PATCH 07/23] test(approvals): a run in progress beside a sibling that failed (ADR-0162 item 8) The fourth shape M4 of contract review 7257527251 names. Red on the base tree's service (2dc92706cf): its walk returned at the run in progress, kept the run above as ended, and the next pass answered finished over the sibling it never read (expected { finished: 1 } to deeply equal { abandoned: 1 }). Green on this head, where a run is kept as ended only with every child its steps name. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jSFBvAjuff7Brz9Rf9 --- ...roval-reconciler-37767.integration.test.ts | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts index 599b2389863..a62db931b82 100644 --- a/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts @@ -793,6 +793,45 @@ describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges expect(await lastLine(last.id)).toMatch(/its node 'first' failed between two steps/); }); + it('[M4] a run in progress beside a sibling that failed: in progress, and once it has ended the sibling still counts', async () => { + await start('two_step', 'crm_invoice', 'i_m4_wait'); + await decide('i_m4_wait', 'approve', 'approver'); + await withoutDoor(() => decide('i_m4_wait', 'approve', 'approver2')); + const [, last] = await requestsOn('i_m4_wait'); + const rootId = String(last.record_run_id); + // A double of the run store, as in the case of the 200 runs: the run + // that carries the record names two child runs. The first is parked + // between two steps (matched by its node id, as a run of an unknown + // flow is); the second ended with a failure the flow routed there. + const at = new Date().toISOString(); + const child = { flowName: 'fan_child', startedAt: at, trigger: { object: 'crm_invoice', recordId: 'i_m4_wait' } }; + let waiting = true; + const real = automation.getRun.bind(automation); + (automation as any).getRun = async (id: string, options?: { strict?: boolean }) => { + if (id === rootId) { + const run: any = await real(id, options); + return { ...run, steps: [...run.steps, { nodeId: 'fan', nodeType: 'subflow', status: 'success', startedAt: at, childRunIds: ['run_wait', 'run_done'] }] }; + } + if (id === 'run_wait') return waiting ? { id, ...child, status: 'paused', steps: [] } : { id, ...child, status: 'completed', completedAt: at, steps: [] }; + if (id === 'run_done') { + return { id, ...child, status: 'completed', completedAt: at, steps: [{ nodeId: 'first', nodeType: 'mark', status: 'failure', startedAt: at }] }; + } + return real(id, options); + }; + const parkedAt = automation.suspensionOf.bind(automation); + (automation as any).suspensionOf = async (id: string) => (id === 'run_wait' + ? (waiting ? { nodeId: 'first', flowName: 'fan_child' } : undefined) + : parkedAt(id)); + + expect((await svc.reconcileMarkedApprovals()).judged, 'a run is parked between two steps').toEqual({ in_progress: 1 }); + expect(await field('crm_invoice', 'i_m4_wait')).toBe('pending'); + + waiting = false; + expect((await svc.reconcileMarkedApprovals()).judged, 'it ended: the sibling that failed is not skipped').toEqual({ abandoned: 1 }); + expect(await field('crm_invoice', 'i_m4_wait')).toBe('recalled'); + expect(await lastLine(last.id)).toMatch(/its node 'first' failed between two steps/); + }); + it('[M4] a run read to its end over a child not read yet, whose own row is gone by the next pass, is not taken as passed', async () => { await start('root_of_two_subs', 'crm_invoice', 'i_m4_owed'); throwOn.add('boom'); From 5ab38fb1c78e3f2a692a30cf6b4f3179884b83a0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 16:10:00 +0000 Subject: [PATCH 08/23] test(approvals): a truncated map step and a step log the row cut, before the fix (ADR-0162 item 8) Seat ruling 7258590209 on M5 of review record 7258563513 (the engine half): a step names at most 200 child runs and carries `childRunIdsTruncated` when its execution started more, and the plugin reads such a step as cannot tell. Three cases, red on this head and on the base tree (each answers finished where cannot tell is owed): - a `map` step that carries the mark: held to the bound, then placed by the step last decided; its log speaks for no run it names; - a step log the history row cut short, and one it stored as null: the run's summary still counts the steps it logged. The mark is not on the local stand-in of the engine half yet, so the cases drive it through a double of the run store. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jSFBvAjuff7Brz9Rf9 --- ...roval-reconciler-37767.integration.test.ts | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts index a62db931b82..a309c75c613 100644 --- a/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts @@ -999,6 +999,80 @@ describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges expect(notified('approval.flow_not_continued'), 'the one rule, with its notice').toEqual([['org_admin']]); }); + /** The summary the engine folds from a whole step log: one execution for each step. */ + const folded = (steps: any[]) => ({ + selected: 0, acted: 0, skipped: 0, + nodes: steps.map((s) => ({ nodeId: s.nodeId, nodeType: s.nodeType ?? 'script', status: 'success', runs: 1, failures: 0, skipped: 0 })), + }); + + it('[M5] a map step that started more item runs than it names: cannot tell, held to the bound and then placed; its log speaks for no run it names', async () => { + await start('two_step', 'crm_invoice', 'i_m5_trunc'); + await decide('i_m5_trunc', 'approve', 'approver'); + await withoutDoor(() => decide('i_m5_trunc', 'approve', 'approver2')); + const [, last] = await requestsOn('i_m5_trunc'); + const rootId = String(last.record_run_id); + // A double of the run store: after the last step the run went through + // a `map` whose step carries the engine's mark that it started more + // item runs than it names (`childRunIdsTruncated`, ruling 7258590209), + // and on to its end. One of the two item runs it names has no row. + const at = new Date().toISOString(); + const real = automation.getRun.bind(automation); + (automation as any).getRun = async (id: string, options?: { strict?: boolean }) => { + if (id === 'run_item_gone') return null; + if (id === 'run_item_0') { + return { id, flowName: 'fan_child', status: 'completed', startedAt: at, completedAt: at, trigger: { object: 'crm_invoice', recordId: 'i_m5_trunc' }, steps: [], summary: folded([]) }; + } + if (id !== rootId) return real(id, options); + const run: any = await real(id, options); + const steps = [...run.steps, + { nodeId: 'fan', nodeType: 'map', status: 'success', startedAt: at, childRunIds: ['run_item_0', 'run_item_gone'], childRunIdsTruncated: true }, + { nodeId: 'tail', nodeType: 'script', status: 'success', startedAt: at }]; + return { ...run, steps, summary: folded(steps) }; + }; + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound: the item runs the step does not name cannot be read').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_m5_trunc')).toBe('pending'); + expect(await marks('i_m5_trunc')).toEqual([false, true]); + const read = kept((await requestsOn('i_m5_trunc')).at(-1)); + expect(read.ended, 'a truncated step does not speak for an item run with no row').not.toContain('run_item_gone'); + expect(read.ended, 'and its run is not done with').not.toContain(rootId); + expect(read.open).toContain(rootId); + + await age('i_m5_trunc'); + notices.length = 0; + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_m5_trunc')).toBe('approved'); + expect(notified('approval.flow_not_continued'), 'placed by the step last decided, with its notice').toEqual([['org_admin']]); + }); + + it.each([ + ['cut short', 'cut', (steps: any[]) => steps.slice(1)], + ['stored as null', 'null', () => [] as any[]], + ])('[M5] a step log the history row %s: cannot tell, held to the bound and then placed', async (_how, tag, stored) => { + const id = `i_m5_${tag}`; + await start('two_step', 'crm_invoice', id); + await decide(id, 'approve', 'approver'); + await withoutDoor(() => decide(id, 'approve', 'approver2')); + const [, last] = await requestsOn(id); + const rootId = String(last.record_run_id); + // The run's summary still counts every step it logged; the row keeps fewer. + const real = automation.getRun.bind(automation); + (automation as any).getRun = async (runId: string, options?: { strict?: boolean }) => { + const run: any = await real(runId, options); + return runId === rootId && run ? { ...run, steps: stored(run.steps), summary: folded(run.steps) } : run; + }; + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', id)).toBe('pending'); + expect(await marks(id)).toEqual([false, true]); + + await age(id); + notices.length = 0; + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', id)).toBe('approved'); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + }); + it('[S6] a note another writer leaves on the request between the reading and the kept write survives it', async () => { await start('parent_two_subs', 'crm_invoice', 'i_s6'); throwOn.add('boom'); From 1a09d5763fc4098630547434705c78b0c57f0440 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 16:13:46 +0000 Subject: [PATCH 09/23] fix(approvals): a step log that does not name every child run is cannot tell (ADR-0162 item 8) Seat ruling 7258590209 on M5 of review record 7258563513. The walk reads as cut, and never as finished: - a step that carries `childRunIdsTruncated`: its execution started more child runs than the 200 the engine names on a step; - the step log of a run in a terminal status whose history row keeps fewer steps than the run logged. The row bounds the log by bytes, to a tail of it or to none; the run's summary is folded before that and counts every step, so the two are compared. A summary that is absent or dropped its detail gives nothing to compare, and reads as cut. A run whose log is cut is cannot tell within the age bound and, past it, placed by the step last decided, as a run with no row is (ruling B2). It is never kept as ended, its children are still read, and it speaks for none of them: no run it names counts as passed. `childRunIdsTruncated` and `summary` are typed as optional on the plugin's own `ApprovalResumeSurface.getRun`. The run-store doubles of the earlier cases carry the summary of the step logs they answer. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jSFBvAjuff7Brz9Rf9 --- ...roval-reconciler-37767.integration.test.ts | 22 +-- .../plugin-approvals/src/approval-service.ts | 169 ++++++++++++++---- 2 files changed, 150 insertions(+), 41 deletions(-) diff --git a/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts index a309c75c613..f1490d12faf 100644 --- a/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts @@ -706,6 +706,11 @@ describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges }); const statusOf = async (runId: unknown) => (await automation.getRun(String(runId)))?.status; const lastLine = async (requestId: unknown) => String((await timeline(String(requestId))).at(-1)![2]); + /** The summary the engine folds from a whole step log: one execution for each step. */ + const folded = (steps: any[]) => ({ + selected: 0, acted: 0, skipped: 0, + nodes: steps.map((s) => ({ nodeId: s.nodeId, nodeType: s.nodeType ?? 'script', status: 'success', runs: 1, failures: 0, skipped: 0 })), + }); /** Refuse the mirror's write of `approved` on the invoice while `on()` holds. */ const refuseApproved = (on: () => boolean) => { const original = ql.update.bind(ql); @@ -777,10 +782,10 @@ describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges } const i = fan.indexOf(id); if (i < 0) return real(id, options); + const steps = i === fan.length - 1 ? [{ nodeId: 'first', nodeType: 'mark', status: 'failure', startedAt: at }] : []; return { id, flowName: 'fan_child', status: 'completed', startedAt: at, completedAt: at, - trigger: { object: 'crm_invoice', recordId: 'i_m4_cap' }, - steps: i === fan.length - 1 ? [{ nodeId: 'first', nodeType: 'mark', status: 'failure', startedAt: at }] : [], + trigger: { object: 'crm_invoice', recordId: 'i_m4_cap' }, steps, summary: folded(steps), }; }; @@ -812,9 +817,12 @@ describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges const run: any = await real(id, options); return { ...run, steps: [...run.steps, { nodeId: 'fan', nodeType: 'subflow', status: 'success', startedAt: at, childRunIds: ['run_wait', 'run_done'] }] }; } - if (id === 'run_wait') return waiting ? { id, ...child, status: 'paused', steps: [] } : { id, ...child, status: 'completed', completedAt: at, steps: [] }; + if (id === 'run_wait') { + return waiting ? { id, ...child, status: 'paused', steps: [] } : { id, ...child, status: 'completed', completedAt: at, steps: [], summary: folded([]) }; + } if (id === 'run_done') { - return { id, ...child, status: 'completed', completedAt: at, steps: [{ nodeId: 'first', nodeType: 'mark', status: 'failure', startedAt: at }] }; + const steps = [{ nodeId: 'first', nodeType: 'mark', status: 'failure', startedAt: at }]; + return { id, ...child, status: 'completed', completedAt: at, steps, summary: folded(steps) }; } return real(id, options); }; @@ -999,12 +1007,6 @@ describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges expect(notified('approval.flow_not_continued'), 'the one rule, with its notice').toEqual([['org_admin']]); }); - /** The summary the engine folds from a whole step log: one execution for each step. */ - const folded = (steps: any[]) => ({ - selected: 0, acted: 0, skipped: 0, - nodes: steps.map((s) => ({ nodeId: s.nodeId, nodeType: s.nodeType ?? 'script', status: 'success', runs: 1, failures: 0, skipped: 0 })), - }); - it('[M5] a map step that started more item runs than it names: cannot tell, held to the bound and then placed; its log speaks for no run it names', async () => { await start('two_step', 'crm_invoice', 'i_m5_trunc'); await decide('i_m5_trunc', 'approve', 'approver'); diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index bae79018027..beee182b775 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -383,7 +383,22 @@ export interface ApprovalResumeSurface { startedAt?: string; completedAt?: string; trigger?: { object?: string; recordId?: string }; - steps?: ReadonlyArray<{ nodeId?: string; nodeType?: string; status?: string; parentNodeId?: string; startedAt?: string; childRunIds?: readonly string[] }>; + steps?: ReadonlyArray<{ + nodeId?: string; nodeType?: string; status?: string; parentNodeId?: string; startedAt?: string; + childRunIds?: readonly string[]; + /** + * [seat ruling 7258590209 on #37767] The engine names at most 200 child + * runs on a step, and sets this where the step's execution started + * more. The door reads such a step as cannot tell ({@link stepLogCut}). + */ + childRunIdsTruncated?: boolean; + }>; + /** + * The run's summary (`ExecutionLog.summary`), folded from every step the + * run logged before its history row bounds the step log: how the door + * tells a step log its row cut short ({@link stepLogCut}). + */ + summary?: { nodes?: ReadonlyArray<{ runs?: number; skipped?: number }>; detailOmitted?: boolean }; } | null>; /** * Whether a suspension still exists for `runId` — the pre-flight that keeps @@ -1917,6 +1932,7 @@ function stopOf(log: ReadonlyArray<{ nodeId?: unknown; parentNodeId?: unknown }> /** [ADR-0162 Execution item 8] One step of a run's log, as the door reads it. */ type RunStepRead = { nodeId?: unknown; nodeType?: unknown; status?: unknown; parentNodeId?: unknown; startedAt?: unknown; childRunIds?: unknown; + childRunIdsTruncated?: unknown; }; /** @@ -1932,14 +1948,16 @@ const MAX_RUNS_READ_PER_APPROVAL = 200; * [ADR-0162 Execution item 8] How long an approval's marks stand before the * reconciler reads a run that will not move again as stopped. It is measured * from the marks: every mark of the approval has stood this long. Within it - * nothing is written for any of the four states it governs, at the + * nothing is written for any of the five states it governs, at the * approval's last step as at any other (ruling 3 on #37767). Past it: * * - a run that reports paused while its pause is gone has stopped at the * last step it logged; * - a run parked at a `subflow` or a `map` whose child run has ended, has * no row, or will not go on itself, has stopped at that node; - * - a run with no row that no run the plugin read speaks for, and + * - a run with no row that no run the plugin read speaks for, + * - a run whose step log does not name every child run it started + * ({@link stepLogCut}; seat ruling 7258590209), and * - the latest request's own run still parked at the step its decision was * recorded on, have each stopped at the step last decided (rulings A3 and * B2 on #37767, one rule). @@ -1951,6 +1969,53 @@ const MAX_RUNS_READ_PER_APPROVAL = 200; */ export const RECONCILER_AGE_BOUND_MS = 60 * 60 * 1000; +/** + * How many steps the engine keeps of a terminal run's log before the history + * row bounds it by bytes (its `MAX_PERSISTED_HISTORY_STEPS`). Only read by + * {@link stepLogCut}: were the engine to keep fewer, more logs would read as + * cut, which is the safe side. + */ +const HISTORY_STEPS_KEPT = 200; + +/** + * [ADR-0162 Execution item 8; seat ruling 7258590209 on M5 of review record + * 7258563513] Why a run's step log does not name every child run its steps + * started, or `undefined` where it does. Such a log cannot be judged from: + * the runs it leaves out are not read, and it does not speak for the runs + * it does name. + * + * - A step carries `childRunIdsTruncated`: its execution started more + * child runs than the 200 the engine names on a step. + * - The history row of a run in a terminal status keeps fewer steps than + * the run logged. The row bounds the log by bytes: over the bound it + * keeps a tail of it, or stores none. The run's summary is folded before + * that, and counts one execution or one skip for every step logged, so + * the two are compared. A log of more steps than the engine keeps + * ({@link HISTORY_STEPS_KEPT}) is compared with that number: the engine's + * own compaction of a long log is not a cut of the row. A summary that + * is absent, or that dropped its per-node detail, gives nothing to + * compare, and the log is read as cut. + * + * A run that has not ended is read from its pause, whose step log is not + * bounded, so only the mark applies to it. + */ +function stepLogCut( + run: { summary?: { nodes?: ReadonlyArray<{ runs?: unknown; skipped?: unknown }>; detailOmitted?: unknown } | null }, + steps: readonly RunStepRead[], + terminal: boolean, +): string | undefined { + const marked = steps.find((s) => s?.childRunIdsTruncated === true); + if (marked) return `its step '${String(marked.nodeId)}' started more child runs than it names`; + if (!terminal) return undefined; + const nodes = run.summary?.detailOmitted ? undefined : run.summary?.nodes; + if (!Array.isArray(nodes)) return 'its summary does not say how many steps it logged'; + let logged = 0; + for (const n of nodes) logged += (Number(n?.runs) || 0) + (Number(n?.skipped) || 0); + return steps.length < Math.min(logged, HISTORY_STEPS_KEPT) + ? `its history keeps ${steps.length} of the ${logged} steps it logged` + : undefined; +} + /** * [ADR-0162 Execution item 8] A child run a step names, whether a `map` step * started it, and whether the run that names it went on past that step @@ -1982,13 +2047,16 @@ interface ChildRunRef { * - a step that failed, also where the flow routed its failure and went on * (the maintainer's pin on that reading): what such a run did after the * step says nothing of the child. + * + * And a log that is cut ({@link stepLogCut}, `speaks` false) passes none: + * it does not speak for the runs it names. */ -function childRunsOf(steps: readonly RunStepRead[], reachedAnEnd: boolean, parkedAt?: string): ChildRunRef[] { +function childRunsOf(steps: readonly RunStepRead[], reachedAnEnd: boolean, parkedAt?: string, speaks = true): ChildRunRef[] { const out: ChildRunRef[] = []; const parkedVisit = parkedAt === undefined ? -1 : steps.map((s) => s?.nodeId).lastIndexOf(parkedAt); steps.forEach((s, i) => { if (!Array.isArray(s?.childRunIds)) return; - const passed = s.status === 'success' && i !== parkedVisit && (reachedAnEnd || i < steps.length - 1); + const passed = speaks && s.status === 'success' && i !== parkedVisit && (reachedAnEnd || i < steps.length - 1); for (const id of s.childRunIds) { if (typeof id !== 'string' || !id) continue; out.push({ id, item: s.nodeType === 'map', passed }); @@ -2174,15 +2242,18 @@ function runsReadAfter(prior: RunsRead, found: RunsFound, between: RunsRead['bet * - `read`: everything else. `over`: it is in a terminal status. `stopped`: * it reports paused at a pause that is gone, past the age bound, so it * will not go on. `endedWhy`: it ended, or stopped, between two steps. + * + * `cut`, on any of the last four: why its step log does not name every + * child run it started ({@link stepLogCut}). */ type ApprovalRunRead = | { answer: 'undetermined'; why: string } | { answer: 'no_row' } | { answer: 'foreign' } - | { answer: 'in_progress'; children: ChildRunRef[] } - | { answer: 'waits'; on: string; item: boolean; node: string; children: ChildRunRef[] } - | { answer: 'own_node'; flow?: string; children: ChildRunRef[] } - | { answer: 'read'; over: boolean; stopped?: boolean; endedWhy?: string; endedAt?: string; children: ChildRunRef[] }; + | { answer: 'in_progress'; children: ChildRunRef[]; cut?: string } + | { answer: 'waits'; on: string; item: boolean; node: string; children: ChildRunRef[]; cut?: string } + | { answer: 'own_node'; flow?: string; children: ChildRunRef[]; cut?: string } + | { answer: 'read'; over: boolean; stopped?: boolean; endedWhy?: string; endedAt?: string; children: ChildRunRef[]; cut?: string }; /** * [ADR-0162 Execution item 8] What the door answered for an approval after it @@ -5593,11 +5664,12 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * in the name of whoever decided it ({@link attributedMirrorContext}). * - **abandoned**: a run ended between two steps ({@link abandonApproval}). * - **cannot tell**: another process is advancing a run, a run or the - * table cannot be read, or, within the age bound, a run has no row or - * the latest request's own run is still parked at its own node. Nothing - * is written, and the mark stays for the reconciler. + * table cannot be read, or, within the age bound, a run has no row, a + * run's step log is cut, or the latest request's own run is still parked + * at its own node. Nothing is written, and the mark stays for the + * reconciler. * - * Past the age bound (`opts.ageBoundMs`, the reconciler's), the last two + * Past the age bound (`opts.ageBoundMs`, the reconciler's), the last three * have stopped at the step last decided (rulings A3 and B2 on #37767): where * a step can follow it, the approval is abandoned and a run still parked * there is cancelled, with the runs that wait on it ({@link cancelStoppedRun}); @@ -5796,9 +5868,10 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * read now or kept, or a later step that could not open (the note on * `latest`, read once the runs are read, {@link laterStepNotOpenedOn}): * `abandoned`. - * - Otherwise, a run with no row that no run read speaks for, or the - * latest request's own run still parked at its own node: within the - * bound `undetermined`, past it `placed`: the run has stopped at the + * - Otherwise, a run with no row that no run read speaks for, a run whose + * step log is cut ({@link stepLogCut}: the runs it leaves out cannot be + * read), or the latest request's own run still parked at its own node: + * within the bound `undetermined`, past it `placed`: the run has stopped at the * step last decided (rulings A3 and B2 on #37767, one rule), and * {@link judgeApprovalAfterDoor} ends the approval by whether a step can * follow that step. @@ -5808,7 +5881,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * the step that names it (the seat's reading 7257555103 of ruling A3; * {@link childRunsOf}, {@link passedWithNoRow}): it counts as passed at * that step, and is kept as ended. A continuation along a failure route is - * not going on past the step. + * not going on past the step, and a log that is cut speaks for no run. * * A failure between two steps is a failure the flow routed, of a node of * the set at the top level of a run (N46 c′: a failure handled in a @@ -5865,6 +5938,8 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega for (const id of prior.open) queue.push({ id, item: false, passed: false }); /** What each run read in this walk answered, in the order read. */ const read = new Map(); + /** The first run read whose step log is cut ({@link stepLogCut}). */ + let cutLog: { runId: string; why: string } | undefined; while (queue.length > 0) { const next = queue.shift()!; const runId = next.id; @@ -5889,7 +5964,10 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega found.foreign.add(runId); continue; } - found.childrenOf.set(runId, one.children.map((c) => c.id)); + // A run whose log is cut names its children in part: they are read, + // and it is never kept as ended ({@link keptAsEnded} wants its children). + if (one.cut === undefined) found.childrenOf.set(runId, one.children.map((c) => c.id)); + else cutLog ??= { runId, why: one.cut }; if (one.answer === 'read' && one.over) { found.terminal.add(runId); if (one.endedWhy !== undefined && !between) between = { why: one.endedWhy, at: one.endedAt ?? null }; @@ -5927,11 +6005,18 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega } const failed = endedWhy ?? between?.why; if (failed) return { answer: 'abandoned', why: failed, kept: kept() }; - if (parkedAtOwnNode || missing.length > 0) { + if (parkedAtOwnNode || cutLog || missing.length > 0) { const what = parkedAtOwnNode ? `its run '${parkedAtOwnNode.runId}' is still parked at the step '${String(latest.flow_node_id ?? '')}' its decision was recorded on, so the run did not go on after it` - : `its run '${missing[0]}' has no row the automation engine can read, and no run that was read went on past it, so where it stopped cannot be read`; - if (!aged) return { answer: 'undetermined', why: `${what}, and a process may still be moving it.`, runId: parkedAtOwnNode?.runId ?? missing[0], kept: kept() }; + : cutLog + ? `the step log of its run '${cutLog.runId}' does not name every child run it started (${cutLog.why}), so the runs below it cannot all be read` + : `its run '${missing[0]}' has no row the automation engine can read, and no run that was read went on past it, so where it stopped cannot be read`; + if (!aged) { + return { + answer: 'undetermined', runId: parkedAtOwnNode?.runId ?? cutLog?.runId ?? missing[0], kept: kept(), + why: parkedAtOwnNode || !cutLog ? `${what}, and a process may still be moving it.` : `${what}; within the age bound nothing is concluded from it.`, + }; + } return { answer: 'placed', why: `${what}; past the age bound it has stopped at that step.`, @@ -6018,10 +6103,24 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega private async readApprovalRun( runId: string, at: { stamp: readonly StampedNode[]; lastOpened: number; aged: boolean; item: boolean; latest: any }, + ): Promise { + const log: { cut?: string } = {}; + const one = await this.placeApprovalRun(runId, at, log); + return log.cut !== undefined && 'children' in one ? { ...one, cut: log.cut } : one; + } + + /** The body of {@link readApprovalRun}; `log.cut` is set where the run's step log is cut ({@link stepLogCut}). */ + private async placeApprovalRun( + runId: string, + at: { stamp: readonly StampedNode[]; lastOpened: number; aged: boolean; item: boolean; latest: any }, + log: { cut?: string }, ): Promise { const { stamp, lastOpened, aged, item, latest } = at; const automation = this.automation!; - let run: { status?: string; flowName?: string; completedAt?: string; trigger?: { object?: string; recordId?: string }; steps?: unknown } | null; + let run: { + status?: string; flowName?: string; completedAt?: string; trigger?: { object?: string; recordId?: string }; steps?: unknown; + summary?: { nodes?: ReadonlyArray<{ runs?: number; skipped?: number }>; detailOmitted?: boolean }; + } | null; try { run = await automation.getRun!(runId, { strict: true }); } catch (err: any) { @@ -6042,7 +6141,9 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega } const flow = typeof run.flowName === 'string' ? run.flowName : undefined; const steps = (Array.isArray(run.steps) ? run.steps : []) as RunStepRead[]; - let children = childRunsOf(steps, REACHED_AN_END.has(status)); + log.cut = stepLogCut(run, steps, TERMINAL_RUN_STATUSES.has(status)); + const speaks = log.cut === undefined; + let children = childRunsOf(steps, REACHED_AN_END.has(status), undefined, speaks); // A failure the flow routed, at the top level of the run, on a node of // the set, after which no request of the approval opened. Read for a @@ -6076,7 +6177,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega }; } // The run did not go on past the node it is parked at. - children = childRunsOf(steps, false, parked.nodeId); + children = childRunsOf(steps, false, parked.nodeId, speaks); // [ruling B2 on #37767] The latest request's own run, still parked at // the node its decision was recorded on: the run was not resumed. if (String(runId) === String(latest.flow_run_id ?? '') && parked.nodeId === String(latest.flow_node_id ?? '')) { @@ -6207,7 +6308,9 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega if (passed) found.passed.add(id); if (seen.has(id) || settled.has(id)) continue; seen.add(id); - let run: { status?: string; trigger?: { object?: string; recordId?: string }; steps?: unknown } | null; + let run: { status?: string; trigger?: { object?: string; recordId?: string }; steps?: unknown; + summary?: { nodes?: ReadonlyArray<{ runs?: number; skipped?: number }>; detailOmitted?: boolean }; + } | null; try { run = await this.automation.getRun(id, { strict: true }); } catch { @@ -6224,8 +6327,11 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega continue; } const status = typeof run.status === 'string' ? run.status : ''; - const children = childRunsOf((Array.isArray(run.steps) ? run.steps : []) as RunStepRead[], REACHED_AN_END.has(status)); - found.childrenOf.set(id, children.map((c) => c.id)); + const steps = (Array.isArray(run.steps) ? run.steps : []) as RunStepRead[]; + // A cut log names its children in part and speaks for none: its run is not kept as ended. + const whole = stepLogCut(run, steps, TERMINAL_RUN_STATUSES.has(status)) === undefined; + const children = childRunsOf(steps, REACHED_AN_END.has(status), undefined, whole); + if (whole) found.childrenOf.set(id, children.map((c) => c.id)); if (TERMINAL_RUN_STATUSES.has(status)) found.terminal.add(id); queue.push(...children); } @@ -11961,10 +12067,11 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * will not move again (rulings A3 and B2 on #37767): a run that reports * paused while its pause is gone, a run parked at a `subflow` or a `map` * whose child run has ended or has no row, and, as one rule, a run with no - * row that no run read speaks for and the latest request's own run still - * parked at the step its decision was recorded on (at whatever depth below - * the run that carries the record), each of which has stopped at the step - * last decided. Where a step can follow it, the approval is abandoned (and + * row that no run read speaks for, a run whose step log is cut + * ({@link stepLogCut}) and the latest request's own run still parked at + * the step its decision was recorded on (at whatever depth below the run + * that carries the record), each of which has stopped at the step last + * decided. Where a step can follow it, the approval is abandoned (and * a run still parked there is cancelled, with the runs that wait on it); * where none can, the outcome is written and, once it has landed, the * administrators are told that the flow did not go on after its last step. From c59318455ffffd91e6a9a951d032eb0924154537 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 16:15:26 +0000 Subject: [PATCH 10/23] docs(approvals): a step log that does not name every child run, in the changeset and the guide Seat ruling 7258590209: the changeset names the two logs read as cut, what they answer within and past the age bound, and the two members the plugin's `getRun` typing gains; the guide lists the state beside the two it already held to the hour. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jSFBvAjuff7Brz9Rf9 --- .changeset/37767-reconciler.md | 5 +++-- content/docs/automation/approvals.mdx | 14 ++++++++------ 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/.changeset/37767-reconciler.md b/.changeset/37767-reconciler.md index 32e2ce5fddd..5fd71434090 100644 --- a/.changeset/37767-reconciler.md +++ b/.changeset/37767-reconciler.md @@ -8,15 +8,16 @@ feat(approvals): the reconciler, and the door reads every run of an approval (AD Clause-②: yes (widening) Metadata-protocol: none -Widened: `ApprovalService` gains `reconcileMarkedApprovals(options?)`, which the plugin runs on the sweep clock beside the escalation, dead-run and stranded-request sweeps; the `getRun` member of the automation surface the plugin declares types the step log's `childRunIds`, the run's `trigger` and `completedAt`, and an optional `{ strict }` read; the plugin's message catalog gains `approvalFlowNotContinuedTitle` and `approvalFlowNotContinuedBody` in all 11 locale packs, sent to the organization's administrators on the topic `approval.flow_not_continued`; `PLATFORM_NOTIFICATION_TOPICS` of `@objectstack/service-messaging`, the topics a notification preference may name, gains that topic. +Widened: `ApprovalService` gains `reconcileMarkedApprovals(options?)`, which the plugin runs on the sweep clock beside the escalation, dead-run and stranded-request sweeps; the `getRun` member of the automation surface the plugin declares types the step log's `childRunIds` and `childRunIdsTruncated`, the run's `trigger`, `completedAt` and `summary`, and an optional `{ strict }` read; the plugin's message catalog gains `approvalFlowNotContinuedTitle` and `approvalFlowNotContinuedBody` in all 11 locale packs, sent to the organization's administrators on the topic `approval.flow_not_continued`; `PLATFORM_NOTIFICATION_TOPICS` of `@objectstack/service-messaging`, the topics a notification preference may name, gains that topic. Only for an approval the check stamped when it opened (one with a step that can act on an object that declares `closedStates`): - **The door reads every run of the approval.** Where it read the run that carries the record and the latest request's own run, it now walks the tree from the run that carries the record, following the child runs each delegating step records: every `subflow` child, and every `map` item run that does not carry another record (an item that is a record carries an approval of its own). It reads the whole tree before it answers, and one run decides for the whole approval: one that another process is advancing, or that the store could not answer for, makes it cannot tell; otherwise one parked at a node a step can follow, in progress; otherwise one that ended between two steps, abandoned. A run parked at such a node on a child run says what its child says, so the walk reads the child, at any depth. So a sibling child whose failure the flow routed, a middle run two levels down that failed, an item run that failed before its step, and a run between two others that is being advanced are no longer read as finished. A failure routed to a pause no step follows is read as abandoned, as on the base. A stop is answered where a request of the approval opened after it. One judgement reads at most 200 runs beside those it kept as ended: past them it is cannot tell, keeps what it read, and the next judgement reads on. The kept list holds 200 runs, so a tree too large to be finished that way stays cannot tell and keeps its mark. - **The plugin keeps what it read.** At every door, one that leaves the next request pending included, and as each request opens, the approval's latest request keeps, in its config snapshot (`__runsRead`): the runs that are not read again (`ended`), the runs read to their end over a child run that was not (`open`), and a failure between two steps found in a run that ended. A run is kept as ended only once it was read to an end and every child run its steps name is kept as ended too. So a child whose read failed, a child with no row, and the runs past the 200 one judgement reads are read on the next pass, which starts from the open runs as well, and no pass answers finished over a run it skipped. A run the plugin read before the automation engine trimmed its history is not needed again, so an approval whose refused outcome is tried again after its run's history went is judged as it would have been. - **A run with no row, under a run that went on past it, is passed.** A run the engine has no row for counts as passed, and is kept as ended, where a run the plugin read went on past the step that names it: that step succeeded, and the run reached an end of its flow, or logged a later step and is not parked at that step. So an early child run trimmed before the plugin read it does not hold the approval back. A step that failed is never passed, also where the flow routed the failure and went on. A run the plugin had read to its end over an unread child, and whose own row is gone since, is not passed either: nothing names that child any more. +- **A step log that does not name every child run is cannot tell.** Two logs are read as cut, and never as finished: one with a step that carries the engine's mark `childRunIdsTruncated` (its execution started more child runs than the 200 a step names), and the log of a run that ended whose history row keeps fewer steps than the run logged (the row bounds the log by bytes, to a tail of it or to none, while the run's summary still counts every step). Within the age bound nothing is written; past it the approval is placed by the step last decided, as for a run with no row, below. A run whose log is cut is not kept as ended, the child runs it does name are still read, and it speaks for none of them: no run it names counts as passed. A summary that is absent or dropped its per-node detail gives nothing to compare, and reads as cut. A log of more than 200 steps, which the engine compacts to 200 before the row, is read by the steps it keeps, as before. - **The kept reading is its own key.** It is written onto the snapshot read again just before the write, and only while the column still reads the same, at most three times. It cannot write a stale snapshot over a note another writer left there (`__laterStepNotOpened`, `__strandedContinuation`). The judgement reads the note that a later step could not open once it has read the runs, so a note that lands while they are read is judged with. -- **A run that stopped, placed by the step last decided.** A run the engine has no row for and that no run the plugin read speaks for (its history is gone, or a process stopped while advancing it), and the latest request's own run still parked at the step its decision was recorded on (a process stopped before the run was resumed), in the run that carries the record or in a child run any number of levels below it, are cannot tell for an hour from the approval's marks (the age bound). Past it, they have stopped at the step last decided. Where a later step can follow that step, the approval is abandoned: the record is put back, the submitter is told and submits again, the decisions already made stay on their requests, and the run still parked there is cancelled, with the runs that wait on it up to the run that carries the record, through a `map` whose items are not records as through a `subflow`. At the last step, the outcome is written and, once that write has landed, the administrators are told that the flow did not go on after that step; the run's pause is left for an operator. A refused write sends no such notice, and the pass on which the write lands sends it. The notice now says what to do in both cases: continue or cancel a run that is still paused, and where no run is left, check that the steps after the decision were done. +- **A run that stopped, placed by the step last decided.** A run the engine has no row for and that no run the plugin read speaks for (its history is gone, or a process stopped while advancing it), a run whose step log is cut, above, and the latest request's own run still parked at the step its decision was recorded on (a process stopped before the run was resumed), in the run that carries the record or in a child run any number of levels below it, are cannot tell for an hour from the approval's marks (the age bound). Past it, they have stopped at the step last decided. Where a later step can follow that step, the approval is abandoned: the record is put back, the submitter is told and submits again, the decisions already made stay on their requests, and the run still parked there is cancelled, with the runs that wait on it up to the run that carries the record, through a `map` whose items are not records as through a `subflow`. At the last step, the outcome is written and, once that write has landed, the administrators are told that the flow did not go on after that step; the run's pause is left for an operator. A refused write sends no such notice, and the pass on which the write lands sends it. The notice now says what to do in both cases: continue or cancel a run that is still paused, and where no run is left, check that the steps after the decision were done. - **The reconciler.** Each pass reads two windows of at most 200 marked requests (`unjudged_since`): the oldest marks, and the next page of a walk over every marked request by id, so that marks which stay cannot keep the newer ones from being read. It judges each approval among them once, as the door would have: it writes the outcome in the name of the request's recorded decider, abandons the approval, or, where nothing was held back, clears the mark and writes nothing (where it concluded that a run had stopped, a line in the log says so). It ends what no door saw: a run that was cancelled, a parent run cancelled while its child's request was pending, and the stopped runs above. Past the age bound it also reads as stopped where it stood a run that reports paused while its pause is gone, and a run parked at a `subflow` or a `map` whose child run has ended or has no row. - **A refused write is tried again.** A refused outcome or put-back leaves the marks, and the next pass tries it again. The timeline line and the administrators' notice (keyed per request and status) are left once for one refusal; the same holds for the line an abandoned approval leaves. - **A deleted record.** Where the approval's record was deleted, the reconciler clears the marks of its requests and writes nothing: no retry and no notice. diff --git a/content/docs/automation/approvals.mdx b/content/docs/automation/approvals.mdx index 9b904051be7..cfea5ff229b 100644 --- a/content/docs/automation/approvals.mdx +++ b/content/docs/automation/approvals.mdx @@ -1678,12 +1678,14 @@ that step succeeded, and the flow reached an end or went on to a later step. Such a run does not hold the approval. A step that failed does not count, also where the flow routed the failure and went on. -Two more states cannot tell at first: a run with no history left to read, which -the platform never read and which no run it read went on past (a process -stopped while it was advancing it), and a decided request whose run is still -parked at that request's own step (a process stopped before the run was -resumed), in the run that carries the record or in a `subflow` or `map` run -below it. An hour after the approval's marks were set, either has stopped at +Three more states cannot tell at first: a run with no history left to read, +which the platform never read and which no run it read went on past (a process +stopped while it was advancing it); a run whose history does not list every run +its steps started (a `map` step that started more than 200 item runs, or a step +history that was cut to fit when it was stored); and a decided request whose +run is still parked at that request's own step (a process stopped before the +run was resumed), in the run that carries the record or in a `subflow` or `map` +run below it. An hour after the approval's marks were set, each has stopped at the step last decided. Where a later step could follow that step, the approval is abandoned, above, and a run still parked there is cancelled, with the runs that wait on it, so nothing resumes it; the decisions already made stay on From 0be4d5d59c708f1830b550ced86c9c01c227fddd Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 02:53:22 +0000 Subject: [PATCH 11/23] test(approvals): the cases the rework on review 7266979193 owes, failing first (ADR-0162 item 8) Five cases on the reconciler, each red on this commit and green on the next one: - [S11] a map of 200 items that are not records, each calling a subflow: no judgement can keep a run, and past the bound the approval is placed. Here it answers cannot tell on every pass. - [S11] two map steps of 200 record items after the decision: the judgements read on while each keeps more runs, and the one that can keep no more places the approval. Here the third pass still answers cannot tell. - [S11] a parked run whose child the judgement did not get to: placed past the bound. Here it answers cannot tell. - [S12] a run parked at a map whose items are records, on an item run that has ended: past the bound the approval is over. Here it answers in progress. - [S12] an item run that has not ended is not kept as ended. Here the door keeps it as ended while it still waits for its approval. Red record on this commit: Tests 5 failed | 44 passed (49). Claude-Session: https://claude.ai/code/session_01JQwxbaoxpe1tyHuqnsAUFB Co-authored-by: Claude --- ...roval-reconciler-37767.integration.test.ts | 177 ++++++++++++++++++ 1 file changed, 177 insertions(+) diff --git a/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts index f1490d12faf..32447cec62e 100644 --- a/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts @@ -147,6 +147,12 @@ const FLOWS = [ // A map whose two items are not records: each item's step is a step of the parent's record. flow('first_then_two_items', [step('first', 'approver'), { id: 'each', type: 'map', label: 'Each', config: { flowName: 'child_boom_then_step', collection: [1, 2] } }], [edge('start', 'first'), edge('first', 'each', 'approve'), edge('first', 'end', 'reject'), edge('each', 'end')]), + // ── The fixtures of the rework on contract review 7266979193 ── + // A map whose items are records, between two steps: each item's step is an approval of the item's own record. + flow('first_then_records', [step('first', 'approver'), + { id: 'each', type: 'map', label: 'Each', config: { flowName: 'child_one_step', collection: [{ id: 'm_line_1' }, { id: 'm_line_2' }], itemObject: 'crm_memo' } }, + step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'each', 'approve'), edge('first', 'end', 'reject'), edge('each', 'second'), ...decided('second', 'end')]), ]; describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges what no door did', () => { @@ -1177,6 +1183,177 @@ describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges expect(await statusOf(first.flow_run_id), 'the pause is left').toBe('paused'); expect(infos.filter((m) => m.includes('crm_ticket/t_n9')), 'what the reconciler concluded is in the log').toHaveLength(1); }); + + describe('the rework on contract review 7266979193: a tree one judgement cannot read has an end, and a map of records is placed', () => { + const at = new Date().toISOString(); + /** A run of a double that reached its end, on the record `record`. */ + const ended = (id: string, record: string, steps: any[] = []) => ({ + id, flowName: 'fan_child', status: 'completed', startedAt: at, completedAt: at, + trigger: { object: 'crm_invoice', recordId: record }, steps, summary: folded(steps), + }); + /** A `map` step that names the item runs `ids`. */ + const fan = (node: string, ids: string[]) => ({ nodeId: node, nodeType: 'map', status: 'success', startedAt: at, childRunIds: ids }); + const ids = (prefix: string) => Array.from({ length: 200 }, (_, i) => `${prefix}_${i}`); + /** + * A double of the run store over the real one, for trees the engine + * does not build cheaply: the run that carries the record logs + * `rootSteps` after its own (and reads as `root` says), and `runs` + * answers for the runs those steps name. + */ + const tree = (rootId: string, rootSteps: any[], runs: (id: string) => unknown, root: Record = {}) => { + const real = automation.getRun.bind(automation); + (automation as any).getRun = async (id: string, options?: { strict?: boolean }) => { + if (id === rootId) { + const run: any = await real(id, options); + return { ...run, ...root, steps: [...run.steps, ...rootSteps] }; + } + const run = runs(id); + return run === undefined ? real(id, options) : run; + }; + }; + /** An item run that is not a record's, and called a `subflow`; and the run that `subflow` started. */ + const itemsThatDelegate = (record: string) => (id: string) => { + const [, kind, i] = /^run_(item|below)_(\d+)$/.exec(id) ?? []; + if (kind === 'item') return ended(id, record, [{ nodeId: 'sub', nodeType: 'subflow', status: 'success', startedAt: at, childRunIds: [`run_below_${i}`] }]); + return kind === 'below' ? ended(id, record) : undefined; + }; + const keptOn = async (id: string) => kept((await requestsOn(id)).at(-1)); + /** The item run the batch of `first_then_records` waits on. */ + const itemOf = async (batch: string) => String((await automation.suspensionOf(batch))?.correlation ?? '').replace(/^map:/, ''); + const seedLines = async () => { for (const id of ['m_line_1', 'm_line_2']) await seed('crm_memo', id); }; + + it('[S11] a map of 200 items that are not records, each calling a subflow: no judgement can keep a run, so the approval is held within the bound and placed past it', async () => { + await start('two_step', 'crm_invoice', 'i_s11_deep'); + await decide('i_s11_deep', 'approve', 'approver'); + await withoutDoor(() => decide('i_s11_deep', 'approve', 'approver2')); + const [, last] = await requestsOn('i_s11_deep'); + // After the last step the run went through a `map` of 200 items + // that are not records, and on to its end; each item run called a + // `subflow`. One judgement reads the run and 199 item runs, and no + // run an item started: no run is read to its end with every run + // below it, so nothing is kept as ended, on any pass. + tree(String(last.record_run_id), [fan('fan', ids('run_item'))], itemsThatDelegate('i_s11_deep')); + notices.length = 0; + + for (const pass of ['the first pass', 'the pass after it']) { + expect((await svc.reconcileMarkedApprovals()).judged, `${pass}, within the bound`).toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_s11_deep'), pass).toBe('pending'); + expect(await marks('i_s11_deep'), pass).toEqual([false, true]); + } + expect((await keptOn('i_s11_deep')).ended, 'no run was read to its end with every run below it').toEqual([]); + + await age('i_s11_deep'); + expect((await svc.reconcileMarkedApprovals()).judged, 'past the bound: a tree the walk cannot finish is placed').toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_s11_deep'), 'the last step: its decision stands').toBe('approved'); + expect(await marks('i_s11_deep')).toEqual([false, false]); + expect(notified('approval.flow_not_continued'), 'placed by the step last decided, with its notice').toEqual([['org_admin']]); + expect((await svc.reconcileMarkedApprovals()).scanned, 'nothing left to judge').toBe(0); + }); + + it('[S11] two map steps of 200 record items after the decision: past the bound the judgements read on while each keeps more runs, and the one that can keep no more places the approval', async () => { + await start('two_step', 'crm_invoice', 'i_s11_wide'); + await decide('i_s11_wide', 'approve', 'approver'); + await withoutDoor(() => decide('i_s11_wide', 'approve', 'approver2')); + const [, last] = await requestsOn('i_s11_wide'); + // After the last step the run went through two `map` steps of 200 + // items each, every item a record of its own, and on to its end: + // 401 runs, where one judgement reads 200 and the kept list holds 200. + tree(String(last.record_run_id), [fan('fan_a', ids('run_a')), fan('fan_b', ids('run_b'))], + (id) => (/^run_[ab]_\d+$/.test(id) ? ended(id, `line_of_${id}`) : undefined)); + // No door judged, and the first judgement comes past the bound. + await age('i_s11_wide'); + notices.length = 0; + + expect((await svc.reconcileMarkedApprovals()).judged, 'it keeps 199 item runs, so the next judgement reads on').toEqual({ undetermined: 1 }); + expect((await keptOn('i_s11_wide')).ended).toHaveLength(199); + expect((await svc.reconcileMarkedApprovals()).judged, 'it keeps one more, and the kept list is full').toEqual({ undetermined: 1 }); + expect((await keptOn('i_s11_wide')).ended).toHaveLength(200); + expect(await field('crm_invoice', 'i_s11_wide')).toBe('pending'); + expect(notified('approval.flow_not_continued')).toEqual([]); + + expect((await svc.reconcileMarkedApprovals()).judged, 'it can keep no more: the tree cannot be finished, and is placed').toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_s11_wide')).toBe('approved'); + expect(await marks('i_s11_wide')).toEqual([false, false]); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + }); + + it('[S11] a parked run whose child the judgement did not get to says nothing: the tree is placed all the same', async () => { + await start('two_step', 'crm_invoice', 'i_s11_parked'); + await decide('i_s11_parked', 'approve', 'approver'); + await withoutDoor(() => decide('i_s11_parked', 'approve', 'approver2')); + const [, last] = await requestsOn('i_s11_parked'); + const rootId = String(last.record_run_id); + // The tree of the first case, still in flight: after its last step + // the run is parked at the `map` (a node no step follows) on item + // 198, and that item run is parked between two steps (matched by + // its node id, as a run of an unknown flow is) on a child run. One + // judgement reads the run and items 0 to 198, and not that child. + const delegating = itemsThatDelegate('i_s11_parked'); + tree(rootId, [fan('fan', ids('run_item'))], (id) => (id === 'run_item_198' + ? { id, flowName: 'fan_child', status: 'paused', startedAt: at, trigger: { object: 'crm_invoice', recordId: 'i_s11_parked' }, steps: [] } + : delegating(id)), { status: 'paused', completedAt: undefined }); + const parkedAt = automation.suspensionOf.bind(automation); + (automation as any).suspensionOf = async (id: string) => { + if (id === rootId) return { nodeId: 'fan', flowName: 'two_step', correlation: 'map:run_item_198' }; + return id === 'run_item_198' ? { nodeId: 'first', flowName: 'fan_child', correlation: 'subflow:run_waited_on' } : parkedAt(id); + }; + notices.length = 0; + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound').toEqual({ undetermined: 1 }); + expect(await marks('i_s11_parked')).toEqual([false, true]); + + await age('i_s11_parked'); + expect((await svc.reconcileMarkedApprovals()).judged, 'past the bound: placed, not in progress for good').toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_s11_parked')).toBe('approved'); + expect(await marks('i_s11_parked')).toEqual([false, false]); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + }); + + it('[S12] a run parked at a map whose items are records, on an item run that has ended: past the bound nothing will resume it, and the approval is over', async () => { + await seedLines(); + await start('first_then_records', 'crm_ticket', 't_s12'); + // The first step is decided, and the batch starts its first item, + // whose step is an approval of the item's own record. No door + // judges: the process stops there. + await withoutDoor(() => decide('t_s12', 'approve', 'approver')); + const [first] = await requestsOn('t_s12'); + const batch = String(first.record_run_id); + const item = await itemOf(batch); + expect((await automation.getRun(item) as any)?.trigger, 'the item run carries a record of its own').toMatchObject({ object: 'crm_memo', recordId: 'm_line_1' }); + // The item run ends, and nothing resumes the batch. + await automation.cancelRun(item); + expect([await statusOf(item), await statusOf(batch)]).toEqual(['cancelled', 'paused']); + expect(await marks('t_s12')).toEqual([true]); + + await age('t_s12'); + expect((await svc.reconcileMarkedApprovals()).judged, 'the batch is parked between two steps on a run that has ended').toEqual({ ended: 1 }); + expect(await marks('t_s12'), 'the ticket closes on another field, so nothing was held back: the hold ends').toEqual([false]); + expect(await steps('t_s12'), 'the decision stays on its request').toEqual([['first', 'approved']]); + expect((await svc.reconcileMarkedApprovals()).scanned, 'nothing left to judge').toBe(0); + }); + + it('[S12] an item run that has not ended is not kept as ended: the batch waits on it past the bound, and goes on when the item is decided', async () => { + await seedLines(); + await start('first_then_records', 'crm_ticket', 't_s12_live'); + await decide('t_s12_live', 'approve', 'approver'); + const [first] = await requestsOn('t_s12_live'); + const item = await itemOf(String(first.record_run_id)); + expect(await statusOf(item), 'the item waits for its own approval').toBe('paused'); + // The door read the item run: it carries another record, and it has not ended. + expect(kept(first)?.ended ?? [], 'not kept as ended').not.toContain(item); + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound').toEqual({ in_progress: 1 }); + + await age('t_s12_live'); + expect((await svc.reconcileMarkedApprovals()).judged, 'past the bound, the item is still being approved').toEqual({ in_progress: 1 }); + expect(await marks('t_s12_live')).toEqual([true]); + + // Each item's own approval is decided: the batch goes on to the next item, and after the last to the second step. + await decide('m_line_1', 'approve', 'approver'); + await decide('m_line_2', 'approve', 'approver'); + expect(await steps('t_s12_live')).toEqual([['first', 'approved'], ['second', 'pending']]); + expect(kept((await requestsOn('t_s12_live')).at(-1))?.ended, 'an item run that ended is kept').toContain(item); + }); + }); }); }); }); From bed455197d37e77680ba5666c6312e342544b2d4 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 02:59:07 +0000 Subject: [PATCH 12/23] fix(approvals): a tree one judgement cannot read has an end, and a map of records is placed (ADR-0162 item 8) S11 of contract review 7266979193. The 200-run cap answered cannot tell before it looked at the age bound, so a tree no judgement could finish kept its mark for good. Now, within the bound the next judgement reads on, as before. Past it a judgement reads on only where it kept a run the approval had not kept and that reading is on the request; the kept list only grows and holds 200 runs, so those judgements are numbered. The one that keeps none answers from the runs it did read, and where they say nothing the approval is placed by the step last decided, like a run the plugin never read. A parked run whose child the reading did not get to says nothing in such a tree, and the child a parked run waits on is read next, before the runs beside it use up the reading. S12. An item run of a map that carries another record answered before its status was read, so a batch parked on one that had ended was in progress at any age, and a door that read one still waiting kept it as ended. The answer now says whether the item run is in a terminal status: past the bound such a child says what any ended child says, and an item run is kept as ended only once it has ended. Reconciler file on this commit: Tests 49 passed (49). Claude-Session: https://claude.ai/code/session_01JQwxbaoxpe1tyHuqnsAUFB Co-authored-by: Claude --- .../plugin-approvals/src/approval-service.ts | 197 ++++++++++++------ 1 file changed, 139 insertions(+), 58 deletions(-) diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index beee182b775..3ee3759f27c 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -1937,10 +1937,18 @@ type RunStepRead = { /** * [ADR-0162 Execution item 8] How many runs one judgement of an approval - * reads, at most, beside those it kept as ended and does not read again. - * Past it the door answers that it cannot tell, and the approval keeps its - * mark. It is also how many runs each list of the kept reading holds + * reads, at most, beside those it kept as ended and does not read again. It + * is also how many runs each list of the kept reading holds * ({@link RunsRead}). + * + * A tree of more runs is read over several judgements, each reading on from + * what the approval kept. Within the age bound such a judgement answers that + * it cannot tell, and the approval keeps its mark. Past the bound it answers + * so only while it keeps a run the approval had not kept; the judgement that + * keeps none cannot finish the tree, and the approval is placed by the step + * last decided ({@link RECONCILER_AGE_BOUND_MS}; S11 of contract review + * 7266979193). The kept list only grows and holds this many runs, so the + * judgements that read on are numbered. */ const MAX_RUNS_READ_PER_APPROVAL = 200; @@ -1948,16 +1956,23 @@ const MAX_RUNS_READ_PER_APPROVAL = 200; * [ADR-0162 Execution item 8] How long an approval's marks stand before the * reconciler reads a run that will not move again as stopped. It is measured * from the marks: every mark of the approval has stood this long. Within it - * nothing is written for any of the five states it governs, at the + * nothing is written for any of the six states it governs, at the * approval's last step as at any other (ruling 3 on #37767). Past it: * * - a run that reports paused while its pause is gone has stopped at the * last step it logged; * - a run parked at a `subflow` or a `map` whose child run has ended, has - * no row, or will not go on itself, has stopped at that node; + * no row, or will not go on itself, has stopped at that node. An item + * run of a `map` that carries another record is such a child once it is + * in a terminal status (S12 of contract review 7266979193); * - a run with no row that no run the plugin read speaks for, * - a run whose step log does not name every child run it started - * ({@link stepLogCut}; seat ruling 7258590209), and + * ({@link stepLogCut}; seat ruling 7258590209), + * - a tree of more runs than one judgement reads, once a judgement keeps + * no run the approval had not kept ({@link MAX_RUNS_READ_PER_APPROVAL}; + * S11 of that review: the runs it does not get to are runs the plugin + * never read, and the cost is the one ruling 7258590209 accepted for a + * truncated step), and * - the latest request's own run still parked at the step its decision was * recorded on, have each stopped at the step last decided (rulings A3 and * B2 on #37767, one rule). @@ -2091,9 +2106,10 @@ const KEEP_RUNS_READ_ATTEMPTS = 3; * - `ended`: the runs a later judgement does not read again. A run enters * it only once it was read to an end and every child run its steps name * is in it too ({@link keptAsEnded}), so a run kept here never hides a - * run that was not read. An end is a terminal status; an item run of a - * `map` that carries another record; and a run with no row that a run - * the plugin read went on past ({@link childRunsOf}); + * run that was not read. An end is a terminal status, also for an item + * run of a `map` that carries another record, whose steps are not read; + * and a run with no row that a run the plugin read went on past + * ({@link childRunsOf}); * - `open`: the runs read in a terminal status that are not in `ended` * yet, because a child they name was not read to such an end. The next * judgement starts from them as well, so they are read again while their @@ -2176,9 +2192,10 @@ function keptAsEnded( /** * [ADR-0162 Execution item 8] What one reading of an approval's runs found, * for {@link runsReadAfter}: the runs read in a terminal status - * (`terminal`), the item runs of another record (`foreign`), the runs with - * no row (`noRow`), the runs a run that was read went on past (`passed`), - * and the child runs each run that was read names (`childrenOf`). + * (`terminal`), the item runs of another record that are in a terminal + * status (`foreign`), the runs with no row (`noRow`), the runs a run that + * was read went on past (`passed`), and the child runs each run that was + * read names (`childrenOf`). */ interface RunsFound { readonly terminal: Set; @@ -2234,7 +2251,10 @@ function runsReadAfter(prior: RunsRead, found: RunsFound, between: RunsRead['bet * * - `undetermined`: it cannot be read or placed now; * - `no_row`: the engine holds no row for it; - * - `foreign`: an item run of a `map` that carries another record; + * - `foreign`: an item run of a `map` that carries another record. Its + * steps are an approval of that record and are not read; `over`: it is + * in a terminal status, so the batch parked on it has nothing left to + * wait for; * - `in_progress`: parked at a node of the set, on nothing the walk reads; * - `waits`: parked at a node of the set (`node`) on a child run (`on`), * which says what this run says (`ApprovalService.waitingRun`); @@ -2249,7 +2269,7 @@ function runsReadAfter(prior: RunsRead, found: RunsFound, between: RunsRead['bet type ApprovalRunRead = | { answer: 'undetermined'; why: string } | { answer: 'no_row' } - | { answer: 'foreign' } + | { answer: 'foreign'; over: boolean } | { answer: 'in_progress'; children: ChildRunRef[]; cut?: string } | { answer: 'waits'; on: string; item: boolean; node: string; children: ChildRunRef[]; cut?: string } | { answer: 'own_node'; flow?: string; children: ChildRunRef[]; cut?: string } @@ -5665,12 +5685,15 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * - **abandoned**: a run ended between two steps ({@link abandonApproval}). * - **cannot tell**: another process is advancing a run, a run or the * table cannot be read, or, within the age bound, a run has no row, a - * run's step log is cut, or the latest request's own run is still parked - * at its own node. Nothing is written, and the mark stays for the + * run's step log is cut, the approval's runs number more than one + * judgement reads, or the latest request's own run is still parked at + * its own node. Nothing is written, and the mark stays for the * reconciler. * - * Past the age bound (`opts.ageBoundMs`, the reconciler's), the last three - * have stopped at the step last decided (rulings A3 and B2 on #37767): where + * Past the age bound (`opts.ageBoundMs`, the reconciler's), the last four + * have stopped at the step last decided (rulings A3 and B2 on #37767; a + * tree of more runs than one judgement reads, once a judgement keeps no + * run the approval had not kept, S11 of contract review 7266979193): where * a step can follow it, the approval is abandoned and a run still parked * there is cancelled, with the runs that wait on it ({@link cancelStoppedRun}); * where none can, it is finished, and once its outcome is on the record the @@ -5857,8 +5880,14 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * * - A run that cannot be read because the store did not answer, that * another process is advancing, or that reports paused with no pause to - * be found (within the age bound), and a tree of more runs than one - * judgement reads: `undetermined`. + * be found (within the age bound): `undetermined`. + * - A tree of more runs than one judgement reads + * ({@link MAX_RUNS_READ_PER_APPROVAL}): `undetermined` within the age + * bound, and past it while this reading keeps a run the approval had + * not kept and that reading is on the request, so that the next + * judgement reads on from it. The reading that keeps none cannot + * finish the tree: it answers from the runs it did read, and where + * they say nothing it is `placed`, as below. * - Otherwise, a run parked at a node of the set that is not waiting on * the step last decided: `in_progress`. A run parked there on a child * run says what its child says ({@link ApprovalService.waitingRun}): the @@ -5870,9 +5899,10 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * `abandoned`. * - Otherwise, a run with no row that no run read speaks for, a run whose * step log is cut ({@link stepLogCut}: the runs it leaves out cannot be - * read), or the latest request's own run still parked at its own node: - * within the bound `undetermined`, past it `placed`: the run has stopped at the - * step last decided (rulings A3 and B2 on #37767, one rule), and + * read), a tree this reading could not finish, or the latest request's + * own run still parked at its own node: within the bound + * `undetermined`, past it `placed`: the run has stopped at the step + * last decided (rulings A3 and B2 on #37767, one rule), and * {@link judgeApprovalAfterDoor} ends the approval by whether a step can * follow that step. * - Otherwise `finished`. @@ -5895,8 +5925,9 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * {@link RECONCILER_AGE_BOUND_MS}, so a run that has not moved since will * not move again. Then a run that reports paused while its pause is gone is * read as stopped at its last step, and a run parked at a `subflow` or a - * `map` whose child run has ended, has no row or will not go on itself, as - * stopped at that node. + * `map` whose child run has ended (an item run that carries another + * record included), has no row or will not go on itself, as stopped at + * that node. * * Every answer carries `kept`: the kept reading with what this reading * found ({@link runsReadAfter}), which the door writes on the latest @@ -5940,16 +5971,18 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const read = new Map(); /** The first run read whose step log is cut ({@link stepLogCut}). */ let cutLog: { runId: string; why: string } | undefined; + /** The first run this reading did not get to: the tree holds more runs than one judgement reads. */ + let unread: string | undefined; while (queue.length > 0) { const next = queue.shift()!; const runId = next.id; if (next.passed) found.passed.add(runId); if (read.has(runId) || settled.has(runId)) continue; if (read.size >= MAX_RUNS_READ_PER_APPROVAL) { - return { - answer: 'undetermined', runId, kept: kept(), - why: `its runs number more than the ${MAX_RUNS_READ_PER_APPROVAL} one judgement reads; the runs read to their end are kept, and the next judgement reads on.`, - }; + // No further run is read. The queue is still emptied, so that every + // run a run that was read went on past counts as passed. + unread ??= runId; + continue; } const one = await this.readApprovalRun(runId, { stamp, lastOpened, aged, item: next.item && !ownRuns.has(runId), latest, @@ -5961,7 +5994,9 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega continue; } if (one.answer === 'foreign') { - found.foreign.add(runId); + // Kept as ended once it has ended. One that has not is not kept: the + // batch above it is read again, and reads it again. + if (one.over) found.foreign.add(runId); continue; } // A run whose log is cut names its children in part: they are read, @@ -5973,8 +6008,29 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega if (one.endedWhy !== undefined && !between) between = { why: one.endedWhy, at: one.endedAt ?? null }; } queue.push(...one.children); - // The child a parked run waits on is read as well, also where no step names it. - if (one.answer === 'waits') queue.push({ id: one.on, item: one.item, passed: false }); + // The child a parked run waits on is read as well, also where no step + // names it; and it is read next, so that what a parked run waits on is + // read before the runs beside it use up the reading. + if (one.answer === 'waits') queue.unshift({ id: one.on, item: one.item, passed: false }); + } + + // [S11 of contract review 7266979193] A tree of more runs than one + // judgement reads has an end. Within the age bound the next judgement + // reads on. Past it, it reads on only where this reading kept a run the + // approval had not kept, and that reading is on the request: the kept + // list only grows and holds at most MAX_RUNS_READ_PER_APPROVAL runs, so + // the judgements that read on are numbered. The reading that keeps none + // cannot finish the tree, and answers below from the runs it did read. + if (unread !== undefined) { + const reading = kept(); + const readsOn = !aged + || (reading.ended.length > prior.ended.length && await this.keepRunsRead(latest, approval, reading)); + if (readsOn) { + return { + answer: 'undetermined', runId: unread, kept: reading, + why: `its runs number more than the ${MAX_RUNS_READ_PER_APPROVAL} one judgement reads; the runs read to their end are kept, and the next judgement reads on.`, + }; + } } const missing = [...found.noRow].filter((id) => !passedWithNoRow(prior, found).has(id)); @@ -5990,8 +6046,10 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega endedWhy ??= one.endedWhy; } else if (one.answer === 'waits') { const says = this.waitingRun(runId, read, settled, aged); - if (says === 'moving') inProgress = true; - else if (says !== 'still') endedWhy ??= says.why; + // A child the reading did not get to says nothing of the run parked + // on it: in a tree that cannot be finished, it is not in progress. + if (says === 'moving' || (says === 'unread' && unread === undefined)) inProgress = true; + else if (typeof says !== 'string') endedWhy ??= says.why; } } if (inProgress) return { answer: 'in_progress', kept: kept() }; @@ -6005,12 +6063,14 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega } const failed = endedWhy ?? between?.why; if (failed) return { answer: 'abandoned', why: failed, kept: kept() }; - if (parkedAtOwnNode || cutLog || missing.length > 0) { + if (parkedAtOwnNode || cutLog || unread !== undefined || missing.length > 0) { const what = parkedAtOwnNode ? `its run '${parkedAtOwnNode.runId}' is still parked at the step '${String(latest.flow_node_id ?? '')}' its decision was recorded on, so the run did not go on after it` : cutLog ? `the step log of its run '${cutLog.runId}' does not name every child run it started (${cutLog.why}), so the runs below it cannot all be read` - : `its run '${missing[0]}' has no row the automation engine can read, and no run that was read went on past it, so where it stopped cannot be read`; + : unread !== undefined + ? `its runs number more than the ${MAX_RUNS_READ_PER_APPROVAL} one judgement reads, and this judgement kept no further run as read to its end, so its runs (the run '${unread}' among them) cannot all be read` + : `its run '${missing[0]}' has no row the automation engine can read, and no run that was read went on past it, so where it stopped cannot be read`; if (!aged) { return { answer: 'undetermined', runId: parkedAtOwnNode?.runId ?? cutLog?.runId ?? missing[0], kept: kept(), @@ -6051,16 +6111,22 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * does, so it says what the child says: * * - `moving`: the child is in progress in its own right, is parked at a - * pause that is not of the set, carries another record, or was not read; - * or, within the age bound, the child has ended or has no row, and the - * engine may still be resuming the parent. The approval is in progress. + * pause that is not of the set, or carries another record and has not + * ended; or, within the age bound, the child has ended or has no row, + * and the engine may still be resuming the parent. The approval is in + * progress. + * - `unread`: the reading did not get to the child, so the parent says + * nothing. The caller reads it as moving, except in a tree of more runs + * than one judgement reads ({@link readCarryingRun}). * - `still`: the child is the latest request's own run, parked at the step * its decision was recorded on, or a run that waits on that run in turn. * The parent says nothing of its own: the one rule places the approval * by that step (B2 on #37767), at whatever depth the step sits. * - `{ why }`: past the age bound, the child has ended, has no row, or * reports paused at a pause that is gone, so nothing will resume the - * parent, between two steps. + * parent, between two steps. An item run of a `map` that carries + * another record has ended once it is in a terminal status (S12 of + * contract review 7266979193). */ private waitingRun( runId: string, @@ -6068,7 +6134,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega settled: ReadonlySet, aged: boolean, above: ReadonlySet = new Set(), - ): 'moving' | 'still' | { why: string } { + ): 'moving' | 'still' | 'unread' | { why: string } { const parent = read.get(runId); if (parent?.answer !== 'waits' || above.has(runId)) return 'moving'; const child = read.get(parent.on); @@ -6076,9 +6142,10 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega why: `its run '${runId}' is parked at '${parent.node}' on a child run that ${how}, so nothing will resume it, between two steps.`, }); const ended = () => (aged ? stopped('has ended') : 'moving' as const); - if (!child) return settled.has(parent.on) ? ended() : 'moving'; + if (!child) return settled.has(parent.on) ? ended() : 'unread'; switch (child.answer) { case 'no_row': return ended(); + case 'foreign': return child.over ? ended() : 'moving'; case 'own_node': return 'still'; case 'waits': { const says = this.waitingRun(parent.on, read, settled, aged, new Set([...above, runId])); @@ -6098,7 +6165,8 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * it is over (a terminal status) and ended between two steps, and the * child runs to read next. `item`: the run is an item run of a `map` that * is not the run of a request of the approval; one that carries a record - * other than the approval's is `foreign`, and is not followed. + * other than the approval's is `foreign`: it is not followed, and only + * whether it has ended is read. */ private async readApprovalRun( runId: string, @@ -6131,7 +6199,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const object = run.trigger?.object; const record = run.trigger?.recordId; if (record != null && record !== '' && (String(record) !== String(latest.record_id) || (object != null && String(object) !== String(latest.object_name)))) { - return { answer: 'foreign' }; + return { answer: 'foreign', over: typeof run.status === 'string' && TERMINAL_RUN_STATUSES.has(run.status) }; } } const status = typeof run.status === 'string' ? run.status : ''; @@ -6239,17 +6307,20 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * stale snapshot over another writer's note, whenever that note lands. * * Best-effort: a reading that is not kept leaves the runs to be read again. + * It answers whether `kept` is on the approval's rows now, which a + * judgement that relies on the next one reading on from it asks + * ({@link readCarryingRun}). */ - private async keepRunsRead(latest: any, approval: readonly any[], kept: RunsRead | undefined): Promise { - if (!kept || !latest?.id) return; - if (sameRunsRead(runsReadOf(approval), kept)) return; + private async keepRunsRead(latest: any, approval: readonly any[], kept: RunsRead | undefined): Promise { + if (!kept || !latest?.id) return false; + if (sameRunsRead(runsReadOf(approval), kept)) return true; try { for (let attempt = 0; attempt < KEEP_RUNS_READ_ATTEMPTS; attempt++) { const rows = await this.engine.find('sys_approval_request', { where: { id: latest.id }, fields: ['id', 'node_config_json'], limit: 1, context: SYSTEM_CTX, }); const current: any = Array.isArray(rows) ? rows[0] : undefined; - if (!current) return; + if (!current) return false; const before: unknown = current.node_config_json; const node_config_json = JSON.stringify({ ...parseJson>(before, {}), [RUNS_READ_KEY]: kept }); // The predicate form: the engine answers how many rows it wrote. @@ -6259,7 +6330,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega }); if (Number(landed) > 0) { latest.node_config_json = node_config_json; - return; + return true; } } this.logger?.warn?.('[approvals] could not keep what was read of an approval\'s runs: its request\'s snapshot kept changing under the write; the next judgement reads them again', { @@ -6270,6 +6341,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega request: latest.id, error: err?.message ?? String(err), }); } + return false; } /** @@ -6321,12 +6393,13 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega continue; } const record = run.trigger?.recordId; + const status = typeof run.status === 'string' ? run.status : ''; if (item && !ownRuns.has(id) && record != null && record !== '' && (String(record) !== String(row.record_id) || (run.trigger?.object != null && String(run.trigger.object) !== String(row.object_name)))) { - found.foreign.add(id); + // An item run of another record is kept as ended once it has ended. + if (TERMINAL_RUN_STATUSES.has(status)) found.foreign.add(id); continue; } - const status = typeof run.status === 'string' ? run.status : ''; const steps = (Array.isArray(run.steps) ? run.steps : []) as RunStepRead[]; // A cut log names its children in part and speaks for none: its run is not kept as ended. const whole = stepLogCut(run, steps, TERMINAL_RUN_STATUSES.has(status)) === undefined; @@ -12066,12 +12139,15 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * stood past {@link RECONCILER_AGE_BOUND_MS}, it also places a run that * will not move again (rulings A3 and B2 on #37767): a run that reports * paused while its pause is gone, a run parked at a `subflow` or a `map` - * whose child run has ended or has no row, and, as one rule, a run with no - * row that no run read speaks for, a run whose step log is cut - * ({@link stepLogCut}) and the latest request's own run still parked at - * the step its decision was recorded on (at whatever depth below the run - * that carries the record), each of which has stopped at the step last - * decided. Where a step can follow it, the approval is abandoned (and + * whose child run has ended or has no row (an item run of a `map` that + * carries another record included, once it is in a terminal status), and, + * as one rule, a run with no row that no run read speaks for, a run whose + * step log is cut ({@link stepLogCut}), a tree of more runs than one + * judgement reads once a judgement keeps no run the approval had not kept + * ({@link MAX_RUNS_READ_PER_APPROVAL}), and the latest request's own run + * still parked at the step its decision was recorded on (at whatever depth + * below the run that carries the record), each of which has stopped at the + * step last decided. Where a step can follow it, the approval is abandoned (and * a run still parked there is cancelled, with the runs that wait on it); * where none can, the outcome is written and, once it has landed, the * administrators are told that the flow did not go on after its last step. @@ -12085,7 +12161,12 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * again; the mirror's notice to the administrators is keyed per request and * status, so it is sent once. For a record that was deleted, the marks of * its approval are cleared and nothing is written: no retry and no notice. - * An approval it cannot tell about keeps its marks for the next pass. + * An approval it cannot tell about keeps its marks for the next pass. Of + * the states it holds within the age bound, none is without an end: each + * is placed past it. What stays cannot tell at any age is a run that + * cannot be read (a store that does not answer, a run that reports a + * status the plugin does not place or that another process is advancing): + * it is read again on the next pass. * * Best-effort: one approval's failure costs only that approval. */ From de5e66594e7fd6fd5f92d9c1b8999b5eb5603ebb Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 03:03:10 +0000 Subject: [PATCH 13/23] test(approvals): the pins N20 to N22 of review 7266979193 owe; the N20 case fails first (ADR-0162 item 8) - [N20] the step last decided is placed in its own flow. Red on this commit: a node of a child flow that carries the id of the parent's last step answers for it, and the approval is abandoned where it is finished. The next commit fixes it. - [N21] the number of steps the plugin takes the engine to keep of a long log is the engine's own, and on a real run the engine names on one step as many child runs as one judgement reads. The two numbers are exported from the module (not the package) for these pins. - [N22] the runs kept as open seed the next reading; a marked step that carries no list (the shape of a row whose links were shed); and the marked step against the real engine, a map of 201 items. These three hold on arrival: they pin what the tree already does. Reconciler file on this commit: Tests 1 failed | 53 passed (54). Claude-Session: https://claude.ai/code/session_01JQwxbaoxpe1tyHuqnsAUFB Co-authored-by: Claude --- ...roval-reconciler-37767.integration.test.ts | 112 +++++++++++++++++- .../plugin-approvals/src/approval-service.ts | 13 +- 2 files changed, 120 insertions(+), 5 deletions(-) diff --git a/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts index 32447cec62e..f3e31e6aabc 100644 --- a/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts @@ -24,8 +24,8 @@ import { APPROVAL_REVISE_NODE_TYPE } from '@objectstack/spec/automation'; 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, RECONCILER_AGE_BOUND_MS } from './approval-service.js'; +import { AutomationServicePlugin, MAX_PERSISTED_HISTORY_STEPS, type AutomationEngine } from '@objectstack/service-automation'; +import { ApprovalService, HISTORY_STEPS_KEPT, MAX_RUNS_READ_PER_APPROVAL, RECONCILER_AGE_BOUND_MS } from './approval-service.js'; import { registerApprovalNode } from './approval-node.js'; import { SysApprovalRequest } from './sys-approval-request.object.js'; import { SysApprovalAction } from './sys-approval-action.object.js'; @@ -153,6 +153,14 @@ const FLOWS = [ { id: 'each', type: 'map', label: 'Each', config: { flowName: 'child_one_step', collection: [{ id: 'm_line_1' }, { id: 'm_line_2' }], itemObject: 'crm_memo' } }, step('second', 'approver2')], [edge('start', 'first'), edge('first', 'each', 'approve'), edge('first', 'end', 'reject'), edge('each', 'second'), ...decided('second', 'end')]), + // The only step, then a map of one item more than the engine names on a step; the items are not records. + flow('only_then_fan', [step('only', 'approver'), + { id: 'fan', type: 'map', label: 'Fan', config: { flowName: 'child_noop', collection: Array.from({ length: 201 }, (_, i) => i) } }], + [edge('start', 'only'), edge('only', 'fan', 'approve'), edge('only', 'end', 'reject'), edge('fan', 'end')]), + // A child between the two steps, one of whose nodes carries the id of the parent's last step. + flow('child_named_final', [mark('final')], [edge('start', 'final'), edge('final', 'end')]), + flow('gate_sub_final', [step('gate', 'approver'), { id: 'sub', type: 'subflow', label: 'Sub', config: { flowName: 'child_named_final' } }, step('final', 'approver2')], + [edge('start', 'gate'), edge('gate', 'sub', 'approve'), edge('gate', 'end', 'reject'), edge('sub', 'final'), ...decided('final', 'end')]), ]; describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges what no door did', () => { @@ -1353,6 +1361,106 @@ describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges expect(await steps('t_s12_live')).toEqual([['first', 'approved'], ['second', 'pending']]); expect(kept((await requestsOn('t_s12_live')).at(-1))?.ended, 'an item run that ended is kept').toContain(item); }); + + it('[N20] the step last decided is placed in its own flow: a node of another flow of the set that carries its id does not answer for it', async () => { + await start('gate_sub_final', 'crm_invoice', 'i_n20'); + await decide('i_n20', 'approve', 'approver'); + await withoutDoor(() => decide('i_n20', 'approve', 'approver2')); + const [, last] = await requestsOn('i_n20'); + expect(await statusOf(last.record_run_id), 'the run went on to its end').toBe('completed'); + // The set names the child's node `final`, which stands between the + // two steps, and not the parent's step of that id, which is the last. + const stamp = JSON.parse(String(last.between_steps_json)); + expect(stamp).toContainEqual({ flow: 'child_named_final', node: 'final' }); + expect(stamp).not.toContainEqual({ flow: 'gate_sub_final', node: 'final' }); + expect(last.process_name, 'the request records the flow its step stands in').toBe('flow:gate_sub_final'); + + // No door judged, and the run that carries the record has no row any more. + trimmed.add(String(last.record_run_id)); + await age('i_n20'); + notices.length = 0; + expect((await svc.reconcileMarkedApprovals()).judged, 'placed by its last step: no step can follow it').toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_n20')).toBe('approved'); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + }); + + it('[N21] the number of steps the plugin takes the engine to keep of a long log is the engine\'s', () => { + expect(HISTORY_STEPS_KEPT).toBe(MAX_PERSISTED_HISTORY_STEPS); + }); + + it('[N22] the runs kept as open seed the next reading: a failure below one is found though the run above it has no row left', async () => { + await start('root_of_two_subs', 'crm_invoice', 'i_n22_seed'); + throwOn.add('boom'); + downFlows.add('child_boom_then_step'); + await decide('i_n22_seed', 'approve', 'approver'); + const [first] = await requestsOn('i_n22_seed'); + const root: any = await automation.getRun(String(first.record_run_id)); + const middle = String(root.steps.find((s: any) => s.nodeId === 'mid').childRunIds[0]); + expect(await field('crm_invoice', 'i_n22_seed'), 'the door cannot tell').toBe('pending'); + expect([...kept(first).open].sort(), 'the root and the middle run ended over a child that was not read').toEqual([String(first.record_run_id), middle].sort()); + + // The store answers again, and the root's row is gone: only the + // kept reading still leads to the middle run and the child below it. + downFlows.clear(); + trimmedFlows.add('root_of_two_subs'); + expect((await svc.reconcileMarkedApprovals()).judged, 'the middle run is read from the kept reading').toEqual({ abandoned: 1 }); + expect(await field('crm_invoice', 'i_n22_seed')).toBe('recalled'); + expect(await marks('i_n22_seed')).toEqual([false]); + }); + + it('[M5, N22] a marked step that carries no list, as a history row whose links were shed: cannot tell, held to the bound and then placed', async () => { + await start('two_step', 'crm_invoice', 'i_m5_shed'); + await decide('i_m5_shed', 'approve', 'approver'); + await withoutDoor(() => decide('i_m5_shed', 'approve', 'approver2')); + const [, last] = await requestsOn('i_m5_shed'); + const rootId = String(last.record_run_id); + // A double of the run store: after the last step the run went + // through a `map` whose step carries the engine's mark and no list. + const real = automation.getRun.bind(automation); + (automation as any).getRun = async (id: string, options?: { strict?: boolean }) => { + const run: any = await real(id, options); + if (id !== rootId || !run) return run; + const all = [...run.steps, { nodeId: 'fan', nodeType: 'map', status: 'success', startedAt: at, childRunIdsTruncated: true }]; + return { ...run, steps: all, summary: folded(all) }; + }; + notices.length = 0; + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_m5_shed')).toBe('pending'); + expect((await keptOn('i_m5_shed')).ended, 'its run is not done with').not.toContain(rootId); + + await age('i_m5_shed'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_m5_shed')).toBe('approved'); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + }); + + it('[M5, N21, N22] on the real engine, a map of 201 items: its step names as many item runs as one judgement reads and is marked, so the approval is held and then placed', async () => { + await start('only_then_fan', 'crm_invoice', 'i_m5_real'); + await decide('i_m5_real', 'approve', 'approver'); + const [only] = await requestsOn('i_m5_real'); + const rootId = String(only.record_run_id); + const root: any = await automation.getRun(rootId); + expect(root.status, 'the run went through the map to its end').toBe('completed'); + const fanStep = root.steps.find((s: any) => s.nodeId === 'fan'); + expect(fanStep.childRunIds, 'the engine names on one step as many child runs as one judgement reads').toHaveLength(MAX_RUNS_READ_PER_APPROVAL); + expect(fanStep.childRunIdsTruncated, 'and marks the step that started more').toBe(true); + expect(await field('crm_invoice', 'i_m5_real'), 'the door cannot tell').toBe('pending'); + expect(await marks('i_m5_real')).toEqual([true]); + notices.length = 0; + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound').toEqual({ undetermined: 1 }); + const read = await keptOn('i_m5_real'); + expect(read.ended, 'every item run the step names was read to its end').toEqual(expect.arrayContaining(fanStep.childRunIds)); + expect(read.ended, 'the run that carries the record is not done with: the item run its step does not name was never read').not.toContain(rootId); + expect(await field('crm_invoice', 'i_m5_real')).toBe('pending'); + + await age('i_m5_real'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_m5_real'), 'the last step: its decision stands').toBe('approved'); + expect(await marks('i_m5_real')).toEqual([false]); + expect(notified('approval.flow_not_continued'), 'placed by the step last decided, with its notice').toEqual([['org_admin']]); + }); }); }); }); diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 3ee3759f27c..36790b4c7b5 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -1949,8 +1949,12 @@ type RunStepRead = { * last decided ({@link RECONCILER_AGE_BOUND_MS}; S11 of contract review * 7266979193). The kept list only grows and holds this many runs, so the * judgements that read on are numbered. + * + * It is also how many child runs the engine names on one step before it + * marks the step (`childRunIdsTruncated`); the suite ties the two on a real + * run (N21 of that review), for which it is exported from this module. */ -const MAX_RUNS_READ_PER_APPROVAL = 200; +export const MAX_RUNS_READ_PER_APPROVAL = 200; /** * [ADR-0162 Execution item 8] How long an approval's marks stand before the @@ -1988,9 +1992,12 @@ export const RECONCILER_AGE_BOUND_MS = 60 * 60 * 1000; * How many steps the engine keeps of a terminal run's log before the history * row bounds it by bytes (its `MAX_PERSISTED_HISTORY_STEPS`). Only read by * {@link stepLogCut}: were the engine to keep fewer, more logs would read as - * cut, which is the safe side. + * cut, which is the safe side. Were it to keep more, a row cut to a length + * between the two numbers would compare as whole, so the suite pins this + * number to the engine's (N21 of contract review 7266979193), for which it + * is exported from this module. */ -const HISTORY_STEPS_KEPT = 200; +export const HISTORY_STEPS_KEPT = 200; /** * [ADR-0162 Execution item 8; seat ruling 7258590209 on M5 of review record From 898c05aeaa9debd30b0e3aaf327b203e99bfe04a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 03:03:36 +0000 Subject: [PATCH 14/23] fix(approvals): the step last decided is placed in the flow its request records (ADR-0162 item 8) N20 of contract review 7266979193. A placement by a run with no row, a cut log or a tree too large to read asked whether a step can follow the step last decided with no flow, so the step was matched by its node id across every flow of the set, and a node of another flow that carried its id answered for it: a last step read as one a later step follows, and the approval was abandoned where it was finished. The flow is now the parked run's where a run is still parked at the step, otherwise the one the request records (`process_name`). A flow the set does not name is still matched by id alone, as before. Reconciler file on this commit: Tests 54 passed (54). Claude-Session: https://claude.ai/code/session_01JQwxbaoxpe1tyHuqnsAUFB Co-authored-by: Claude --- packages/plugins/plugin-approvals/src/approval-service.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 36790b4c7b5..6230cd99bc6 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -5809,7 +5809,12 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega let why = reading.answer === 'abandoned' || reading.answer === 'placed' ? reading.why : ''; if (reading.answer === 'placed') { const stepNode = String(latest.flow_node_id ?? latest.current_step ?? ''); - if (stepNode && standsBetweenSteps(stamp, reading.flow, stepNode)) { + // The flow the step stands in: the parked run's where a run is still + // parked at it, otherwise the one its request records, so that a + // node of another flow of the set that carries the step's id does + // not answer for it (N20 of contract review 7266979193). + const stepFlow = reading.flow ?? flowNameOfProcess(latest.process_name); + if (stepNode && standsBetweenSteps(stamp, stepFlow, stepNode)) { answer = 'abandoned'; parkedRun = reading.parkedRun; } else { From 292dc62c23b50c0731453d912bb24be8eafda8b2 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 03:07:11 +0000 Subject: [PATCH 15/23] docs(approvals): the changeset, the guide and the notice say what the tree does (ADR-0162 item 8) S13 of contract review 7266979193, and the interim on its question q1. - A tree of more runs than one judgement reads no longer "stays cannot tell": the changeset and the guide say when it is read on and when it is placed. - "A step log that does not name every child run is cannot tell" and "no pass answers finished over a run it skipped" said more than the tree. The first is now the two logs that are read as cut; the second says what happens to a run a stored step names. A log the engine compacted past 200 steps has its own entry, in the changeset and in the guide: which steps the row keeps, that the child runs a dropped step started are not read from the stored row, and that such an approval can be written as finished with no notice. - N18: the cancel of a parked run is not tried again once the put-back has landed, and both texts say so. - N19: the notice body's second arm covers a run that has ended, in all 11 locale packs, and its first sentence no longer says the flow was not seen to go on where it could not be read in full. - A map over records is named where the fourth state is stated. Claude-Session: https://claude.ai/code/session_01JQwxbaoxpe1tyHuqnsAUFB Co-authored-by: Claude --- .changeset/37767-reconciler.md | 11 ++-- content/docs/automation/approvals.mdx | 61 +++++++++++++------ .../plugin-approvals/src/approval-service.ts | 15 +++-- .../src/translations/messages.ts | 22 +++---- 4 files changed, 70 insertions(+), 39 deletions(-) diff --git a/.changeset/37767-reconciler.md b/.changeset/37767-reconciler.md index 5fd71434090..fb6fb34084c 100644 --- a/.changeset/37767-reconciler.md +++ b/.changeset/37767-reconciler.md @@ -12,13 +12,14 @@ Widened: `ApprovalService` gains `reconcileMarkedApprovals(options?)`, which the Only for an approval the check stamped when it opened (one with a step that can act on an object that declares `closedStates`): -- **The door reads every run of the approval.** Where it read the run that carries the record and the latest request's own run, it now walks the tree from the run that carries the record, following the child runs each delegating step records: every `subflow` child, and every `map` item run that does not carry another record (an item that is a record carries an approval of its own). It reads the whole tree before it answers, and one run decides for the whole approval: one that another process is advancing, or that the store could not answer for, makes it cannot tell; otherwise one parked at a node a step can follow, in progress; otherwise one that ended between two steps, abandoned. A run parked at such a node on a child run says what its child says, so the walk reads the child, at any depth. So a sibling child whose failure the flow routed, a middle run two levels down that failed, an item run that failed before its step, and a run between two others that is being advanced are no longer read as finished. A failure routed to a pause no step follows is read as abandoned, as on the base. A stop is answered where a request of the approval opened after it. One judgement reads at most 200 runs beside those it kept as ended: past them it is cannot tell, keeps what it read, and the next judgement reads on. The kept list holds 200 runs, so a tree too large to be finished that way stays cannot tell and keeps its mark. -- **The plugin keeps what it read.** At every door, one that leaves the next request pending included, and as each request opens, the approval's latest request keeps, in its config snapshot (`__runsRead`): the runs that are not read again (`ended`), the runs read to their end over a child run that was not (`open`), and a failure between two steps found in a run that ended. A run is kept as ended only once it was read to an end and every child run its steps name is kept as ended too. So a child whose read failed, a child with no row, and the runs past the 200 one judgement reads are read on the next pass, which starts from the open runs as well, and no pass answers finished over a run it skipped. A run the plugin read before the automation engine trimmed its history is not needed again, so an approval whose refused outcome is tried again after its run's history went is judged as it would have been. +- **The door reads every run of the approval.** Where it read the run that carries the record and the latest request's own run, it now walks the tree from the run that carries the record, following the child runs each delegating step records: every `subflow` child, and every `map` item run that does not carry another record (an item that is a record carries an approval of its own). It reads the whole tree before it answers, and one run decides for the whole approval: one that another process is advancing, or that the store could not answer for, makes it cannot tell; otherwise one parked at a node a step can follow, in progress; otherwise one that ended between two steps, abandoned. A run parked at such a node on a child run says what its child says, so the walk reads the child, at any depth. So a sibling child whose failure the flow routed, a middle run two levels down that failed, an item run that failed before its step, and a run between two others that is being advanced are no longer read as finished. A failure routed to a pause no step follows is read as abandoned, as on the base. A stop is answered where a request of the approval opened after it. One judgement reads at most 200 runs beside those it kept as ended: past them it is cannot tell, keeps what it read, and the next judgement reads on. That has an end: once the approval's marks have stood for the hour of the age bound, a judgement reads on only while it keeps a run the approval had not kept (the kept list holds 200 runs), and the judgement that keeps none places the approval by the step last decided, below. A run parked on a child run that such a judgement did not get to says nothing of its own, and the child a parked run waits on is read next, before the runs beside it. +- **The plugin keeps what it read.** At every door, one that leaves the next request pending included, and as each request opens, the approval's latest request keeps, in its config snapshot (`__runsRead`): the runs that are not read again (`ended`), the runs read to their end over a child run that was not (`open`), and a failure between two steps found in a run that ended. A run is kept as ended only once it was read to an end and every child run its steps name is kept as ended too. So a child whose read failed, a child with no row, and the runs past the 200 one judgement reads are read on the next pass, which starts from the open runs as well. A run that a stored step names and that a pass did not read is never left out without a word: it is read on a later pass, it counts as passed by the rule below, or the approval is cannot tell and then placed. A run that no stored step names any more is not covered by that: see the compacted log, below. A run the plugin read before the automation engine trimmed its history is not needed again, so an approval whose refused outcome is tried again after its run's history went is judged as it would have been. - **A run with no row, under a run that went on past it, is passed.** A run the engine has no row for counts as passed, and is kept as ended, where a run the plugin read went on past the step that names it: that step succeeded, and the run reached an end of its flow, or logged a later step and is not parked at that step. So an early child run trimmed before the plugin read it does not hold the approval back. A step that failed is never passed, also where the flow routed the failure and went on. A run the plugin had read to its end over an unread child, and whose own row is gone since, is not passed either: nothing names that child any more. -- **A step log that does not name every child run is cannot tell.** Two logs are read as cut, and never as finished: one with a step that carries the engine's mark `childRunIdsTruncated` (its execution started more child runs than the 200 a step names), and the log of a run that ended whose history row keeps fewer steps than the run logged (the row bounds the log by bytes, to a tail of it or to none, while the run's summary still counts every step). Within the age bound nothing is written; past it the approval is placed by the step last decided, as for a run with no row, below. A run whose log is cut is not kept as ended, the child runs it does name are still read, and it speaks for none of them: no run it names counts as passed. A summary that is absent or dropped its per-node detail gives nothing to compare, and reads as cut. A log of more than 200 steps, which the engine compacts to 200 before the row, is read by the steps it keeps, as before. +- **A step log the engine marked, or the history row cut, is cannot tell.** Two logs are read as cut, and are not judged from as they stand: one with a step that carries the engine's mark `childRunIdsTruncated` (its execution started more child runs than the 200 a step names, or the history row shed the step's list to fit its size), and the log of a run that ended whose history row keeps fewer steps than the run logged (the row bounds the log by bytes, to a tail of it or to none, while the run's summary still counts every step). Within the age bound nothing is written; past it the approval is placed by the step last decided, as for a run with no row, below. A run whose log is cut is not kept as ended, the child runs it does name are still read, and it speaks for none of them: no run it names counts as passed. A summary that is absent or dropped its per-node detail gives nothing to compare, and reads as cut. +- **Not read as cut: a log the engine compacted.** A run that logged more than 200 steps is stored with 200 of them: every top-level step and every failed step, then the most recent of the rest (the most recent 200 of the top-level and failed steps, where those alone pass 200). It is judged from the steps the row keeps, as before this change. What an operator gets in that case: a `subflow` or `map` step the compaction dropped (one that succeeded inside a `loop`, `parallel` or `try_catch` region, or an early step of a very long run) no longer names the child runs it started, so a judgement made from the stored row does not read them. A failure the flow routed inside such a child run, between two steps, is not seen, and the approval can be written as finished, with no notice and no line in the log. A process that still holds the run in memory reads its whole log, so this is a judgement made once that process is gone. No approval is judged worse than before this change, whose door read no child run. Whether such a log should be read as cut instead is not decided yet; this entry states what is built. - **The kept reading is its own key.** It is written onto the snapshot read again just before the write, and only while the column still reads the same, at most three times. It cannot write a stale snapshot over a note another writer left there (`__laterStepNotOpened`, `__strandedContinuation`). The judgement reads the note that a later step could not open once it has read the runs, so a note that lands while they are read is judged with. -- **A run that stopped, placed by the step last decided.** A run the engine has no row for and that no run the plugin read speaks for (its history is gone, or a process stopped while advancing it), a run whose step log is cut, above, and the latest request's own run still parked at the step its decision was recorded on (a process stopped before the run was resumed), in the run that carries the record or in a child run any number of levels below it, are cannot tell for an hour from the approval's marks (the age bound). Past it, they have stopped at the step last decided. Where a later step can follow that step, the approval is abandoned: the record is put back, the submitter is told and submits again, the decisions already made stay on their requests, and the run still parked there is cancelled, with the runs that wait on it up to the run that carries the record, through a `map` whose items are not records as through a `subflow`. At the last step, the outcome is written and, once that write has landed, the administrators are told that the flow did not go on after that step; the run's pause is left for an operator. A refused write sends no such notice, and the pass on which the write lands sends it. The notice now says what to do in both cases: continue or cancel a run that is still paused, and where no run is left, check that the steps after the decision were done. -- **The reconciler.** Each pass reads two windows of at most 200 marked requests (`unjudged_since`): the oldest marks, and the next page of a walk over every marked request by id, so that marks which stay cannot keep the newer ones from being read. It judges each approval among them once, as the door would have: it writes the outcome in the name of the request's recorded decider, abandons the approval, or, where nothing was held back, clears the mark and writes nothing (where it concluded that a run had stopped, a line in the log says so). It ends what no door saw: a run that was cancelled, a parent run cancelled while its child's request was pending, and the stopped runs above. Past the age bound it also reads as stopped where it stood a run that reports paused while its pause is gone, and a run parked at a `subflow` or a `map` whose child run has ended or has no row. +- **A run that stopped, placed by the step last decided.** A run the engine has no row for and that no run the plugin read speaks for (its history is gone, or a process stopped while advancing it), a run whose step log is cut, above, a tree of more runs than the judgements can read in full, above, and the latest request's own run still parked at the step its decision was recorded on (a process stopped before the run was resumed), in the run that carries the record or in a child run any number of levels below it, are cannot tell for an hour from the approval's marks (the age bound). Past it, they have stopped at the step last decided. Whether a later step can follow that step is asked in the flow its request records, so a node of another flow that carries the step's id does not answer for it. Where one can, the approval is abandoned: the record is put back, the submitter is told and submits again, the decisions already made stay on their requests, and a run still parked there is cancelled, with the runs that wait on it up to the run that carries the record, through a `map` whose items are not records as through a `subflow`. The cancel follows the put-back, and is not tried again once the put-back has landed: where it fails, or the process stops between the two, the run stays parked, the approval stays abandoned, and the door that continues a restored run refuses it. At the last step, the outcome is written and, once that write has landed, the administrators are told that the flow did not go on after that step; the run's pause is left for an operator. A refused write sends no such notice, and the pass on which the write lands sends it. The notice says what to do in each case: continue or cancel a run that is still paused, and where the run has ended or no run is left, check that the steps after the decision were done. An approval placed for a cut log or a tree too large to read can be one whose flow did go on, which the plugin could not read in full: at its last step the administrators get the notice for a flow that ran, and where a later step can follow, the submitter submits again. +- **The reconciler.** Each pass reads two windows of at most 200 marked requests (`unjudged_since`): the oldest marks, and the next page of a walk over every marked request by id, so that marks which stay cannot keep the newer ones from being read. It judges each approval among them once, as the door would have: it writes the outcome in the name of the request's recorded decider, abandons the approval, or, where nothing was held back, clears the mark and writes nothing (where it concluded that a run had stopped, a line in the log says so). It ends what no door saw: a run that was cancelled, a parent run cancelled while its child's request was pending, and the stopped runs above. Past the age bound it also reads as stopped where it stood a run that reports paused while its pause is gone, and a run parked at a `subflow` or a `map` whose child run has ended or has no row. The item run of a `map` whose items are records is such a child once it is in a terminal status: its steps are an approval of the item's own record and are not read, only whether it has ended, and it is kept as ended only once it has. - **A refused write is tried again.** A refused outcome or put-back leaves the marks, and the next pass tries it again. The timeline line and the administrators' notice (keyed per request and status) are left once for one refusal; the same holds for the line an abandoned approval leaves. - **A deleted record.** Where the approval's record was deleted, the reconciler clears the marks of its requests and writes nothing: no retry and no notice. - **The stranded-request report** (`inspectStrandedRequests`) leaves a decided request the check stamped to the door and the reconciler, and still reports a returned one. diff --git a/content/docs/automation/approvals.mdx b/content/docs/automation/approvals.mdx index cfea5ff229b..9b3e7899954 100644 --- a/content/docs/automation/approvals.mdx +++ b/content/docs/automation/approvals.mdx @@ -1666,10 +1666,13 @@ actions, one that leaves the next request pending included, and as each request opens: the runs it read to their end, and a failure between two steps it found in one. A run is not read again once it, and every run its steps started, were read to their end. Until then it is read again at the next action or sweep, so -a run the platform could not read once is not passed over later. One reading -takes at most 200 runs beside those it does not read again; a larger tree -cannot tell on that reading and is read on at the next, and one too large to -finish that way stays cannot tell. +a run that a stored step lists, and that the platform could not read once, is +not passed over later. One reading takes at most 200 runs beside those it does +not read again; a larger tree cannot tell on that reading and is read on at the +next. That has an end: once the approval's marks have stood for an hour, the +platform reads on only while a reading adds to the runs it does not read again +(it keeps at most 200 of them), and the reading that adds none places the +approval by the step last decided, below. The platform trims every flow's run history in time. A run it read before that is not needed again. A run it never read counts as passed where the history of @@ -1678,25 +1681,45 @@ that step succeeded, and the flow reached an end or went on to a later step. Such a run does not hold the approval. A step that failed does not count, also where the flow routed the failure and went on. -Three more states cannot tell at first: a run with no history left to read, +Four more states cannot tell at first: a run with no history left to read, which the platform never read and which no run it read went on past (a process stopped while it was advancing it); a run whose history does not list every run its steps started (a `map` step that started more than 200 item runs, or a step -history that was cut to fit when it was stored); and a decided request whose -run is still parked at that request's own step (a process stopped before the -run was resumed), in the run that carries the record or in a `subflow` or `map` -run below it. An hour after the approval's marks were set, each has stopped at -the step last decided. Where a later step could follow that step, the approval -is abandoned, above, and a run still parked there is cancelled, with the runs -that wait on it, so nothing resumes it; the decisions already made stay on -their requests, and the submitter submits again. Where the step was the last, -its decision is written and, once it is on the record, the organization's +history that lost steps, or the lists of the runs its steps started, to its +size limit when it was stored); an approval with more runs than the platform +can read in full, above; +and a decided request whose run is still parked at that request's own step (a +process stopped before the run was resumed), in the run that carries the record +or in a `subflow` or `map` run below it. An hour after the approval's marks +were set, each has stopped at the step last decided. Where a later step could +follow that step, the approval is abandoned, above, and a run still parked +there is cancelled, with the runs that wait on it, so nothing resumes it; the +decisions already made stay on their requests, and the submitter submits again. +The cancel is not tried again once the record is put back: where it fails, the +run stays parked, the approval stays abandoned, and continuing that run is +refused. Where the step was the last, its decision is written and, once it is +on the record, the organization's administrators are told that the flow did not go on after that step (the notice `approval.flow_not_continued`). The run's pause is left: where the run is still paused, an operator can continue the flow's remaining nodes or cancel the run; -where no run is left, check that the steps after the decision were done. A -write that a rule or a hook refuses sends no such notice; the notice goes out -with the write that lands. +where it has ended or no run is left, check that the steps after the decision +were done. A write that a rule or a hook refuses sends no such notice; the +notice goes out with the write that lands. An approval placed for a history +that does not list every run, or for more runs than the platform can read, can +be one whose flow did go on: the platform could not read it in full, so the +notice asks for a check and does not state a failure. + +One long history is not read as incomplete. A run that logged more than 200 +steps is stored with 200 of them: its top-level steps and its failed steps +first, then the most recent of the rest. A `subflow` or `map` step that is not +among them (one that succeeded inside a `loop`, `parallel` or `try_catch`, or +an early step of a very long run) no longer lists the runs it started. A +judgement made from the stored history does not read those runs: a failure the +flow routed inside one of them is not seen, and the approval can be written as +finished, with no notice. A process that still holds the run in memory reads +all of its steps. For a flow whose run can log more than 200 steps and that +starts child flows inside such a region, read the outcome of those child runs +in the flow's run history as well. Every decision on an approval any step of which can act on an object that declares `closedStates` leaves a mark on its request (`unjudged_since`), also @@ -1709,7 +1732,9 @@ next page of a walk over every marked request, so that approvals that stay in progress do not keep the newer ones from being judged. Once the mark has stood for an hour, it also reads as stopped where it stood a run that reports paused while its pause is gone, and a run parked at a `subflow` or a `map` whose child -run has ended or has no history left. +run has ended or has no history left. That holds for a `map` over records too: +the platform does not read such an item run's steps, which belong to the item's +own approval, only whether the run has ended. Where nothing was held back it clears the mark and writes nothing; where it concluded that a run had stopped, a line in the server log says so. A write that a rule or a hook refuses is reported as above, once, and tried again on each diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 6230cd99bc6..972b4fc71bc 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -1882,8 +1882,9 @@ const ABANDONED_APPROVAL_TOPIC = 'approval.abandoned'; /** * [ADR-0162 Execution item 8, ruling B2 on #37767] The topic of the notice * the organization's administrators get when an approval was decided at its - * last step and its outcome written, while its flow was not seen to go on - * after that step. + * last step and its outcome written, while its flow could not be seen through + * to its end after that step: it did not go on, or the plugin could not read + * all of it. */ const FLOW_NOT_CONTINUED_TOPIC = 'approval.flow_not_continued'; @@ -6610,9 +6611,13 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega /** * [ADR-0162 Execution item 8, ruling B2 on #37767] Tell the organization's * administrators that the approval of `latest`'s record was decided at its - * last step and its outcome written, while its flow was not seen to go on - * after that step, so the flow's nodes after it may not have run. The run's - * pause, where it has one, is left for an operator to continue or cancel. + * last step and its outcome written, while its flow could not be seen + * through to its end after that step, so the flow's nodes after it may not + * have run: the run did not go on, has no row, or could not be read in full + * (a cut step log, a tree of more runs than the judgements read). The + * notice asks for a check and states no failure (N19 of contract review + * 7266979193). The run's pause, where it has one, is left for an operator + * to continue or cancel. * Sent once per request, and only on the pass whose outcome write landed * (ruling 3 on #37767). */ diff --git a/packages/plugins/plugin-approvals/src/translations/messages.ts b/packages/plugins/plugin-approvals/src/translations/messages.ts index 96267dbe650..1512127a7ea 100644 --- a/packages/plugins/plugin-approvals/src/translations/messages.ts +++ b/packages/plugins/plugin-approvals/src/translations/messages.ts @@ -156,7 +156,7 @@ const enSentences = { approvalAbandonedTitle: 'Approval did not finish', approvalAbandonedBody: 'The approval of your {{object}} {{record}} stopped between two of its steps, so it did not finish and the record was put back to an open status. Submit it again when it is ready.', approvalFlowNotContinuedTitle: 'Approval flow did not go on', - approvalFlowNotContinuedBody: 'The approval of {{object}} {{record}} was decided at its last step and the decision was written, but its flow was not seen to go on after that step, so the steps that follow it may not have run. Check the approval\'s flow run: where it is still paused, continue or cancel it; where no run is left, check that the steps after the decision were done.', + approvalFlowNotContinuedBody: 'The approval of {{object}} {{record}} was decided at its last step and the decision was written, but its flow could not be seen through to its end after that step, so the steps that follow it may not have run. Check the approval\'s flow run: where it is still paused, continue or cancel it; where it has ended or no run is left, check that the steps after the decision were done.', approvalReturnedTitle: 'Sent back for revision', approvalReturnedBody: 'Your {{object}} {{record}} needs rework before it can be approved.', approvalRequestInfoTitle: 'More information requested', @@ -308,7 +308,7 @@ export const zhCNMessages: ApprovalMessages = { approvalAbandonedTitle: '审批未能完成', approvalAbandonedBody: '您的{{object}} {{record}} 的审批在两个步骤之间停止,未能完成,记录已恢复为未关闭的状态。准备好后请重新提交。', approvalFlowNotContinuedTitle: '审批流程未继续', - approvalFlowNotContinuedBody: '{{object}} {{record}} 的审批已在最后一步作出决定,决定也已写入,但未见其流程在该步之后继续,之后的步骤可能没有执行。请检查该审批的流程运行:若仍处于暂停,请继续或取消它;若已无运行记录,请核对该决定之后的步骤是否已完成。', + approvalFlowNotContinuedBody: '{{object}} {{record}} 的审批已在最后一步作出决定,决定也已写入,但无法确认其流程在该步之后已执行到结束,之后的步骤可能没有执行。请检查该审批的流程运行:若仍处于暂停,请继续或取消它;若运行已结束或已无运行记录,请核对该决定之后的步骤是否已完成。', approvalReturnedTitle: '已退回修改', approvalReturnedBody: '您的{{object}} {{record}} 需要修改后才能获批。', approvalRequestInfoTitle: '需要补充信息', @@ -397,7 +397,7 @@ export const jaJPMessages: ApprovalMessages = { approvalAbandonedTitle: '承認が完了しませんでした', approvalAbandonedBody: 'あなたの{{object}} {{record}} の承認は 2 つのステップの間で停止したため完了せず、レコードは閉じていないステータスに戻されました。準備ができたら再度申請してください。', approvalFlowNotContinuedTitle: '承認フローが続行されませんでした', - approvalFlowNotContinuedBody: '{{object}} {{record}} の承認は最後のステップで決定され、その決定は書き込まれましたが、フローがそのステップの後に続行されたことを確認できないため、後続のステップが実行されていない可能性があります。承認のフロー実行を確認してください。まだ一時停止中であれば続行またはキャンセルし、実行が残っていなければ、決定の後のステップが行われたかを確認してください。', + approvalFlowNotContinuedBody: '{{object}} {{record}} の承認は最後のステップで決定され、その決定は書き込まれましたが、フローがそのステップの後に最後まで実行されたことを確認できないため、後続のステップが実行されていない可能性があります。承認のフロー実行を確認してください。まだ一時停止中であれば続行またはキャンセルし、実行が終了しているか残っていなければ、決定の後のステップが行われたかを確認してください。', approvalReturnedTitle: '修正のため差し戻されました', approvalReturnedBody: 'あなたの{{object}} {{record}} は、承認を受ける前に修正が必要です。', approvalRequestInfoTitle: '追加情報が求められています', @@ -486,7 +486,7 @@ export const esESMessages: ApprovalMessages = { approvalAbandonedTitle: 'La aprobación no terminó', approvalAbandonedBody: 'La aprobación de su {{object}} {{record}} se detuvo entre dos de sus pasos, así que no terminó y el registro volvió a un estado abierto. Envíelo de nuevo cuando esté listo.', approvalFlowNotContinuedTitle: 'El flujo de la aprobación no continuó', - approvalFlowNotContinuedBody: 'La aprobación de {{object}} {{record}} se decidió en su último paso y la decisión se escribió, pero no se vio que su flujo continuara después de ese paso, así que es posible que los pasos siguientes no se hayan ejecutado. Revise la ejecución del flujo de la aprobación: si sigue en pausa, continúela o cancélela; si ya no queda ninguna ejecución, compruebe que se hicieron los pasos posteriores a la decisión.', + approvalFlowNotContinuedBody: 'La aprobación de {{object}} {{record}} se decidió en su último paso y la decisión se escribió, pero no se pudo comprobar que su flujo continuara hasta el final después de ese paso, así que es posible que los pasos siguientes no se hayan ejecutado. Revise la ejecución del flujo de la aprobación: si sigue en pausa, continúela o cancélela; si ya terminó o no queda ninguna ejecución, compruebe que se hicieron los pasos posteriores a la decisión.', approvalReturnedTitle: 'Devuelto para revisión', approvalReturnedBody: 'Su {{object}} {{record}} necesita cambios antes de poder aprobarse.', approvalRequestInfoTitle: 'Se solicita más información', @@ -575,7 +575,7 @@ export const zhHantMessages: ApprovalMessages = { approvalAbandonedTitle: '核准未能完成', approvalAbandonedBody: '你的{{object}} {{record}} 的核准在兩個步驟之間停止,未能完成,記錄已恢復為未關閉的狀態。準備好後請重新送出。', approvalFlowNotContinuedTitle: '核准流程未繼續', - approvalFlowNotContinuedBody: '{{object}} {{record}} 的核准已在最後一步作出決定,決定也已寫入,但未見其流程在該步之後繼續,之後的步驟可能沒有執行。請檢查該核准的流程執行:若仍處於暫停,請繼續或取消它;若已無執行記錄,請核對該決定之後的步驟是否已完成。', + approvalFlowNotContinuedBody: '{{object}} {{record}} 的核准已在最後一步作出決定,決定也已寫入,但無法確認其流程在該步之後已執行到結束,之後的步驟可能沒有執行。請檢查該核准的流程執行:若仍處於暫停,請繼續或取消它;若執行已結束或已無執行記錄,請核對該決定之後的步驟是否已完成。', approvalReturnedTitle: '已退回修改', approvalReturnedBody: '你的{{object}} {{record}} 需要修改後才能獲得核准。', approvalRequestInfoTitle: '需要補充資訊', @@ -664,7 +664,7 @@ export const arMessages: ApprovalMessages = { approvalAbandonedTitle: 'لم تكتمل الموافقة', approvalAbandonedBody: 'توقفت الموافقة على {{object}} {{record}} بين خطوتين من خطواتها، فلم تكتمل وأُعيد السجل إلى حالة مفتوحة. أعد إرساله عندما يكون جاهزًا.', approvalFlowNotContinuedTitle: 'لم يستمر مسار الموافقة', - approvalFlowNotContinuedBody: 'تم البت في الموافقة على {{object}} {{record}} في خطوتها الأخيرة وكُتب القرار، لكن لم يُرَ مسارها يستمر بعد تلك الخطوة، لذا ربما لم تُنفَّذ الخطوات التي تليها. راجع تشغيل مسار الموافقة: إن كان لا يزال متوقفًا مؤقتًا فتابعه أو ألغِه، وإن لم يبقَ له تشغيل فتحقّق من أن الخطوات التي تلي القرار قد نُفّذت.', + approvalFlowNotContinuedBody: 'تم البت في الموافقة على {{object}} {{record}} في خطوتها الأخيرة وكُتب القرار، لكن تعذّر التأكد من أن مسارها استمر حتى نهايته بعد تلك الخطوة، لذا ربما لم تُنفَّذ الخطوات التي تليها. راجع تشغيل مسار الموافقة: إن كان لا يزال متوقفًا مؤقتًا فتابعه أو ألغِه، وإن كان قد انتهى أو لم يبقَ له تشغيل فتحقّق من أن الخطوات التي تلي القرار قد نُفّذت.', approvalReturnedTitle: 'أُعيد للمراجعة', approvalReturnedBody: 'يحتاج طلبك بشأن {{object}} {{record}} إلى تعديل قبل أن تمكن الموافقة عليه.', approvalRequestInfoTitle: 'مطلوب مزيد من المعلومات', @@ -753,7 +753,7 @@ export const frMessages: ApprovalMessages = { approvalAbandonedTitle: 'L’approbation n’a pas abouti', approvalAbandonedBody: 'L’approbation de votre {{object}} {{record}} s’est arrêtée entre deux de ses étapes : elle n’a pas abouti et l’enregistrement est revenu à un statut ouvert. Soumettez-le à nouveau lorsqu’il est prêt.', approvalFlowNotContinuedTitle: 'Le flux de l’approbation n’a pas continué', - approvalFlowNotContinuedBody: 'L’approbation de {{object}} {{record}} a été décidée à sa dernière étape et la décision a été écrite, mais son flux n’a pas été vu se poursuivre après cette étape : les étapes suivantes n’ont peut-être pas été exécutées. Vérifiez l’exécution du flux de l’approbation : si elle est encore en pause, poursuivez-la ou annulez-la ; s’il n’en reste aucune, vérifiez que les étapes qui suivent la décision ont été faites.', + approvalFlowNotContinuedBody: 'L’approbation de {{object}} {{record}} a été décidée à sa dernière étape et la décision a été écrite, mais il n’a pas pu être vérifié que son flux s’est poursuivi jusqu’à son terme après cette étape : les étapes suivantes n’ont peut-être pas été exécutées. Vérifiez l’exécution du flux de l’approbation : si elle est encore en pause, poursuivez-la ou annulez-la ; si elle est terminée ou s’il n’en reste aucune, vérifiez que les étapes qui suivent la décision ont été faites.', approvalReturnedTitle: 'Renvoyé pour révision', approvalReturnedBody: 'Votre demande sur {{object}} {{record}} doit être retravaillée avant de pouvoir être approuvée.', approvalRequestInfoTitle: 'Informations complémentaires demandées', @@ -842,7 +842,7 @@ export const ptBRMessages: ApprovalMessages = { approvalAbandonedTitle: 'A aprovação não foi concluída', approvalAbandonedBody: 'A aprovação de {{object}} {{record}} parou entre duas de suas etapas, por isso não foi concluída e o registro voltou a um status aberto. Envie-o novamente quando estiver pronto.', approvalFlowNotContinuedTitle: 'O fluxo da aprovação não continuou', - approvalFlowNotContinuedBody: 'A aprovação de {{object}} {{record}} foi decidida em sua última etapa e a decisão foi gravada, mas não se viu o fluxo continuar depois dessa etapa, então as etapas seguintes podem não ter sido executadas. Verifique a execução do fluxo da aprovação: se ainda estiver pausada, continue-a ou cancele-a; se não restar nenhuma execução, confira se as etapas após a decisão foram feitas.', + approvalFlowNotContinuedBody: 'A aprovação de {{object}} {{record}} foi decidida em sua última etapa e a decisão foi gravada, mas não foi possível confirmar que o fluxo continuou até o fim depois dessa etapa, então as etapas seguintes podem não ter sido executadas. Verifique a execução do fluxo da aprovação: se ainda estiver pausada, continue-a ou cancele-a; se já tiver terminado ou não restar nenhuma execução, confira se as etapas após a decisão foram feitas.', approvalReturnedTitle: 'Devolvido para revisão', approvalReturnedBody: 'Sua solicitação sobre {{object}} {{record}} precisa de ajustes antes de poder ser aprovada.', approvalRequestInfoTitle: 'Mais informações solicitadas', @@ -931,7 +931,7 @@ export const ruMessages: ApprovalMessages = { approvalAbandonedTitle: 'Согласование не завершено', approvalAbandonedBody: 'Согласование {{object}} {{record}} остановилось между двумя шагами, поэтому не завершилось, и запись возвращена в открытый статус. Отправьте её снова, когда она будет готова.', approvalFlowNotContinuedTitle: 'Процесс согласования не продолжился', - approvalFlowNotContinuedBody: 'Согласование {{object}} {{record}} было решено на последнем шаге, и решение записано, но не видно, чтобы процесс продолжился после этого шага, поэтому следующие шаги могли не выполниться. Проверьте запуск процесса согласования: если он ещё приостановлен, продолжите или отмените его; если запуска уже нет, проверьте, что шаги после решения выполнены.', + approvalFlowNotContinuedBody: 'Согласование {{object}} {{record}} было решено на последнем шаге, и решение записано, но не удалось убедиться, что процесс после этого шага дошёл до конца, поэтому следующие шаги могли не выполниться. Проверьте запуск процесса согласования: если он ещё приостановлен, продолжите или отмените его; если он завершился или запуска уже нет, проверьте, что шаги после решения выполнены.', approvalReturnedTitle: 'Возвращено на доработку', approvalReturnedBody: 'Ваш запрос по {{object}} {{record}} нужно доработать, прежде чем его можно будет одобрить.', approvalRequestInfoTitle: 'Запрошены дополнительные сведения', @@ -1020,7 +1020,7 @@ export const deMessages: ApprovalMessages = { approvalAbandonedTitle: 'Genehmigung nicht abgeschlossen', approvalAbandonedBody: 'Die Genehmigung zu {{object}} {{record}} hat zwischen zwei ihrer Schritte angehalten. Sie wurde nicht abgeschlossen, und der Datensatz wurde auf einen offenen Status zurückgesetzt. Reichen Sie ihn erneut ein, wenn er bereit ist.', approvalFlowNotContinuedTitle: 'Der Ablauf der Genehmigung wurde nicht fortgesetzt', - approvalFlowNotContinuedBody: 'Die Genehmigung zu {{object}} {{record}} wurde in ihrem letzten Schritt entschieden und die Entscheidung geschrieben, aber ihr Ablauf wurde nach diesem Schritt nicht fortgesetzt gesehen, sodass die folgenden Schritte möglicherweise nicht ausgeführt wurden. Prüfen Sie den Ablauf der Genehmigung: Ist er noch pausiert, setzen Sie ihn fort oder brechen Sie ihn ab; ist kein Lauf mehr vorhanden, prüfen Sie, ob die Schritte nach der Entscheidung erledigt wurden.', + approvalFlowNotContinuedBody: 'Die Genehmigung zu {{object}} {{record}} wurde in ihrem letzten Schritt entschieden und die Entscheidung geschrieben, aber es ließ sich nicht feststellen, dass ihr Ablauf nach diesem Schritt bis zum Ende fortgesetzt wurde, sodass die folgenden Schritte möglicherweise nicht ausgeführt wurden. Prüfen Sie den Ablauf der Genehmigung: Ist er noch pausiert, setzen Sie ihn fort oder brechen Sie ihn ab; ist er beendet oder kein Lauf mehr vorhanden, prüfen Sie, ob die Schritte nach der Entscheidung erledigt wurden.', approvalReturnedTitle: 'Zur Überarbeitung zurückgesendet', approvalReturnedBody: 'Ihre Anfrage zu {{object}} {{record}} muss überarbeitet werden, bevor sie genehmigt werden kann.', approvalRequestInfoTitle: 'Weitere Informationen angefordert', @@ -1109,7 +1109,7 @@ export const koMessages: ApprovalMessages = { approvalAbandonedTitle: '승인이 완료되지 않았습니다', approvalAbandonedBody: '{{object}} {{record}}의 승인이 두 단계 사이에서 멈춰 완료되지 않았고, 레코드는 열린 상태로 되돌아갔습니다. 준비가 되면 다시 제출하세요.', approvalFlowNotContinuedTitle: '승인 흐름이 계속되지 않았습니다', - approvalFlowNotContinuedBody: '{{object}} {{record}}의 승인은 마지막 단계에서 결정되었고 결정도 기록되었지만, 그 단계 이후 흐름이 계속되는 것이 확인되지 않아 이후 단계가 실행되지 않았을 수 있습니다. 승인의 흐름 실행을 확인하세요. 아직 일시 중지되어 있으면 계속하거나 취소하고, 남은 실행이 없으면 결정 이후의 단계가 수행되었는지 확인하세요.', + approvalFlowNotContinuedBody: '{{object}} {{record}}의 승인은 마지막 단계에서 결정되었고 결정도 기록되었지만, 그 단계 이후 흐름이 끝까지 진행되었는지 확인할 수 없어 이후 단계가 실행되지 않았을 수 있습니다. 승인의 흐름 실행을 확인하세요. 아직 일시 중지되어 있으면 계속하거나 취소하고, 실행이 끝났거나 남은 실행이 없으면 결정 이후의 단계가 수행되었는지 확인하세요.', approvalReturnedTitle: '수정 요청됨', approvalReturnedBody: '{{object}} {{record}}을(를) 승인받으려면 먼저 수정해야 합니다.', approvalRequestInfoTitle: '추가 정보 요청', From b49e04ad1ee0c6943ff594b1f5dedd248775aaf9 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 03:11:16 +0000 Subject: [PATCH 16/23] test(approvals): three more pins on the S11 and S12 rules (ADR-0162 item 8) Each pins one condition of the fix in bed455197d that the first five cases leave free, and each is proven by its own ablation (in the PR): - [S11] a reading that cannot be kept does not read on: where the kept write does not land, past the bound the approval is placed at once. - [S11] the child a parked run waits on is read before the runs beside it: in a tree too large to read, a child that is in progress still says so, and the approval is not placed. - [S12] as a request opens, an item run of another record that has not ended is not kept as ended either. Added after the fix: they hold on this commit. Reconciler file on this commit: Tests 57 passed (57). Claude-Session: https://claude.ai/code/session_01JQwxbaoxpe1tyHuqnsAUFB Co-authored-by: Claude --- ...roval-reconciler-37767.integration.test.ts | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts index f3e31e6aabc..4f2f42daa0e 100644 --- a/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts @@ -1317,6 +1317,63 @@ describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); }); + it('[S11] a reading that cannot be kept does not read on: past the bound the approval is placed at once', async () => { + await start('two_step', 'crm_invoice', 'i_s11_unkept'); + await decide('i_s11_unkept', 'approve', 'approver'); + await withoutDoor(() => decide('i_s11_unkept', 'approve', 'approver2')); + const [, last] = await requestsOn('i_s11_unkept'); + // The tree of two map steps, whose first reading keeps 199 item runs. + tree(String(last.record_run_id), [fan('fan_a', ids('run_a')), fan('fan_b', ids('run_b'))], + (id) => (/^run_[ab]_\d+$/.test(id) ? ended(id, `line_of_${id}`) : undefined)); + await age('i_s11_unkept'); + // The store refuses the kept reading, on every try: the next + // judgement would start from nothing again, and so would every one after it. + const update = ql.update.bind(ql); + (ql as any).update = async (o: string, data: any, options?: any) => { + if (o === 'sys_approval_request' && String(data?.node_config_json ?? '').includes('__runsRead')) throw new Error('the store refused the write'); + return update(o, data, options); + }; + notices.length = 0; + + expect((await svc.reconcileMarkedApprovals()).judged, 'what it read is not on the request, so it does not wait for a next reading').toEqual({ finished: 1 }); + expect((await keptOn('i_s11_unkept'))?.ended ?? [], 'nothing was kept').toEqual([]); + expect(await field('crm_invoice', 'i_s11_unkept')).toBe('approved'); + expect(await marks('i_s11_unkept')).toEqual([false, false]); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + }); + + it('[S11] the child a parked run waits on is read before the runs beside it: in a tree too large to read, a child that is in progress still says so', async () => { + await start('two_step', 'crm_invoice', 'i_s11_live'); + await decide('i_s11_live', 'approve', 'approver'); + await withoutDoor(() => decide('i_s11_live', 'approve', 'approver2')); + const [, last] = await requestsOn('i_s11_live'); + const rootId = String(last.record_run_id); + // The run that carries the record is parked between two steps on a + // child run, after a `map` of 200 items that each called a + // `subflow`; the child it waits on is parked between two steps in + // its own right (matched by its node id, as a run of an unknown + // flow is). No step names that child, so the walk learns of it + // from the pause alone. + const delegating = itemsThatDelegate('i_s11_live'); + tree(rootId, [fan('fan', ids('run_item'))], (id) => (id === 'run_waited_on' + ? { id, flowName: 'fan_child', status: 'paused', startedAt: at, trigger: { object: 'crm_invoice', recordId: 'i_s11_live' }, steps: [] } + : delegating(id)), { status: 'paused', completedAt: undefined }); + const parkedAt = automation.suspensionOf.bind(automation); + (automation as any).suspensionOf = async (id: string) => { + if (id === rootId) return { nodeId: 'first', flowName: 'two_step', correlation: 'subflow:run_waited_on' }; + return id === 'run_waited_on' ? { nodeId: 'first', flowName: 'fan_child' } : parkedAt(id); + }; + await age('i_s11_live'); + notices.length = 0; + + for (const pass of ['the first pass', 'the pass after it']) { + expect((await svc.reconcileMarkedApprovals()).judged, `${pass}, past the bound`).toEqual({ in_progress: 1 }); + expect(await field('crm_invoice', 'i_s11_live'), pass).toBe('pending'); + expect(await marks('i_s11_live'), pass).toEqual([false, true]); + } + expect(notified('approval.flow_not_continued')).toEqual([]); + }); + it('[S12] a run parked at a map whose items are records, on an item run that has ended: past the bound nothing will resume it, and the approval is over', async () => { await seedLines(); await start('first_then_records', 'crm_ticket', 't_s12'); @@ -1362,6 +1419,23 @@ describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges expect(kept((await requestsOn('t_s12_live')).at(-1))?.ended, 'an item run that ended is kept').toContain(item); }); + it('[S12] as a request opens, an item run of another record that has not ended is not kept as ended either', async () => { + await start('two_step', 'crm_invoice', 'i_s12_open'); + const [first] = await requestsOn('i_s12_open'); + // A double of the run store: before its second step the run went + // through a `map` whose one item is a record of its own, and that + // item run has not ended. + tree(String(first.record_run_id), [fan('each', ['run_of_a_line'])], (id) => (id === 'run_of_a_line' + ? { id, flowName: 'fan_child', status: 'paused', startedAt: at, trigger: { object: 'crm_memo', recordId: 'm_line_9' }, steps: [] } + : undefined)); + + // The second step opens, and its request keeps what the plugin can read; the door then reads again. + await decide('i_s12_open', 'approve', 'approver'); + const [, second] = await requestsOn('i_s12_open'); + expect(second.status).toBe('pending'); + expect(kept(second)?.ended ?? [], 'neither the opening nor the door kept it').not.toContain('run_of_a_line'); + }); + it('[N20] the step last decided is placed in its own flow: a node of another flow of the set that carries its id does not answer for it', async () => { await start('gate_sub_final', 'crm_invoice', 'i_n20'); await decide('i_n20', 'approve', 'approver'); From 04635fce12cd0a7402aba86b3944da0b1b206e5a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 03:46:49 +0000 Subject: [PATCH 17/23] test(approvals): the real-engine case of 201 item runs carries its own timeout (ADR-0162 item 8) CI's Test Core (10/12) on b49e04ad1e went red on one case, and on nothing else: `[M5, N21, N22] on the real engine, a map of 201 items` timed out at the default 5000 ms. The case took 11875 ms there, on a runner that shares its cores with the shard's other packages, against 2077 ms here. It runs 201 runs of a child flow through the real engine and its store, which is what it is for; it now carries 60 s, as the heavy integration cases of this package do. No other case of the file passed 2 s on that runner. Reconciler file on this commit: Tests 57 passed (57). Claude-Session: https://claude.ai/code/session_01JQwxbaoxpe1tyHuqnsAUFB Co-authored-by: Claude --- .../src/approval-reconciler-37767.integration.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts index 4f2f42daa0e..67be38d9378 100644 --- a/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts @@ -1534,7 +1534,9 @@ describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges expect(await field('crm_invoice', 'i_m5_real'), 'the last step: its decision stands').toBe('approved'); expect(await marks('i_m5_real')).toEqual([false]); expect(notified('approval.flow_not_continued'), 'placed by the step last decided, with its notice').toEqual([['org_admin']]); - }); + // 201 runs of the child flow through the real engine and its store: + // well over the default timeout on a loaded runner (12 s measured in CI). + }, 60_000); }); }); }); From c885ffce7072725284a1dae39db8cabc84753109 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 03:51:24 +0000 Subject: [PATCH 18/23] docs(approvals): the compacted-log gap is stated as the limit the maintainer ruled (ADR-0162 item 8) Ruling 7268216330 on #37767 answers the review's question q1: keep what is built, and state it in the docs. The changeset, the guide and the docblock of `stepLogCut` now say, and cite the ruling where they say it: - A log that loses whole steps carries no mark: the engine's compaction past 200 steps, the row's halving over its 64 KB cap, a row stored as null. - Only a step whose child-run links were shed carries `childRunIdsTruncated`. - The plugin reads what the log kept, and a child run named only by a dropped step reads as one the run went past. They also say what the tree does beside that, so that no sentence says more than it: a halved row and a null row are still told from the run's summary and read as cut, as built; a compacted log is not, and there an approval can be written as finished over a failure in such a child run. The sentence that left the question open is gone. No behaviour changes: a comment and two texts. Claude-Session: https://claude.ai/code/session_01JQwxbaoxpe1tyHuqnsAUFB Co-authored-by: Claude --- .changeset/37767-reconciler.md | 4 +-- content/docs/automation/approvals.mdx | 29 ++++++++++++------- .../plugin-approvals/src/approval-service.ts | 15 ++++++++-- 3 files changed, 33 insertions(+), 15 deletions(-) diff --git a/.changeset/37767-reconciler.md b/.changeset/37767-reconciler.md index fb6fb34084c..8d57563d33b 100644 --- a/.changeset/37767-reconciler.md +++ b/.changeset/37767-reconciler.md @@ -13,10 +13,10 @@ Widened: `ApprovalService` gains `reconcileMarkedApprovals(options?)`, which the Only for an approval the check stamped when it opened (one with a step that can act on an object that declares `closedStates`): - **The door reads every run of the approval.** Where it read the run that carries the record and the latest request's own run, it now walks the tree from the run that carries the record, following the child runs each delegating step records: every `subflow` child, and every `map` item run that does not carry another record (an item that is a record carries an approval of its own). It reads the whole tree before it answers, and one run decides for the whole approval: one that another process is advancing, or that the store could not answer for, makes it cannot tell; otherwise one parked at a node a step can follow, in progress; otherwise one that ended between two steps, abandoned. A run parked at such a node on a child run says what its child says, so the walk reads the child, at any depth. So a sibling child whose failure the flow routed, a middle run two levels down that failed, an item run that failed before its step, and a run between two others that is being advanced are no longer read as finished. A failure routed to a pause no step follows is read as abandoned, as on the base. A stop is answered where a request of the approval opened after it. One judgement reads at most 200 runs beside those it kept as ended: past them it is cannot tell, keeps what it read, and the next judgement reads on. That has an end: once the approval's marks have stood for the hour of the age bound, a judgement reads on only while it keeps a run the approval had not kept (the kept list holds 200 runs), and the judgement that keeps none places the approval by the step last decided, below. A run parked on a child run that such a judgement did not get to says nothing of its own, and the child a parked run waits on is read next, before the runs beside it. -- **The plugin keeps what it read.** At every door, one that leaves the next request pending included, and as each request opens, the approval's latest request keeps, in its config snapshot (`__runsRead`): the runs that are not read again (`ended`), the runs read to their end over a child run that was not (`open`), and a failure between two steps found in a run that ended. A run is kept as ended only once it was read to an end and every child run its steps name is kept as ended too. So a child whose read failed, a child with no row, and the runs past the 200 one judgement reads are read on the next pass, which starts from the open runs as well. A run that a stored step names and that a pass did not read is never left out without a word: it is read on a later pass, it counts as passed by the rule below, or the approval is cannot tell and then placed. A run that no stored step names any more is not covered by that: see the compacted log, below. A run the plugin read before the automation engine trimmed its history is not needed again, so an approval whose refused outcome is tried again after its run's history went is judged as it would have been. +- **The plugin keeps what it read.** At every door, one that leaves the next request pending included, and as each request opens, the approval's latest request keeps, in its config snapshot (`__runsRead`): the runs that are not read again (`ended`), the runs read to their end over a child run that was not (`open`), and a failure between two steps found in a run that ended. A run is kept as ended only once it was read to an end and every child run its steps name is kept as ended too. So a child whose read failed, a child with no row, and the runs past the 200 one judgement reads are read on the next pass, which starts from the open runs as well. A run that a stored step names and that a pass did not read is never left out without a word: it is read on a later pass, it counts as passed by the rule below, or the approval is cannot tell and then placed. A run that no stored step names any more is not covered by that: see the limit of this release, below. A run the plugin read before the automation engine trimmed its history is not needed again, so an approval whose refused outcome is tried again after its run's history went is judged as it would have been. - **A run with no row, under a run that went on past it, is passed.** A run the engine has no row for counts as passed, and is kept as ended, where a run the plugin read went on past the step that names it: that step succeeded, and the run reached an end of its flow, or logged a later step and is not parked at that step. So an early child run trimmed before the plugin read it does not hold the approval back. A step that failed is never passed, also where the flow routed the failure and went on. A run the plugin had read to its end over an unread child, and whose own row is gone since, is not passed either: nothing names that child any more. - **A step log the engine marked, or the history row cut, is cannot tell.** Two logs are read as cut, and are not judged from as they stand: one with a step that carries the engine's mark `childRunIdsTruncated` (its execution started more child runs than the 200 a step names, or the history row shed the step's list to fit its size), and the log of a run that ended whose history row keeps fewer steps than the run logged (the row bounds the log by bytes, to a tail of it or to none, while the run's summary still counts every step). Within the age bound nothing is written; past it the approval is placed by the step last decided, as for a run with no row, below. A run whose log is cut is not kept as ended, the child runs it does name are still read, and it speaks for none of them: no run it names counts as passed. A summary that is absent or dropped its per-node detail gives nothing to compare, and reads as cut. -- **Not read as cut: a log the engine compacted.** A run that logged more than 200 steps is stored with 200 of them: every top-level step and every failed step, then the most recent of the rest (the most recent 200 of the top-level and failed steps, where those alone pass 200). It is judged from the steps the row keeps, as before this change. What an operator gets in that case: a `subflow` or `map` step the compaction dropped (one that succeeded inside a `loop`, `parallel` or `try_catch` region, or an early step of a very long run) no longer names the child runs it started, so a judgement made from the stored row does not read them. A failure the flow routed inside such a child run, between two steps, is not seen, and the approval can be written as finished, with no notice and no line in the log. A process that still holds the run in memory reads its whole log, so this is a judgement made once that process is gone. No approval is judged worse than before this change, whose door read no child run. Whether such a log should be read as cut instead is not decided yet; this entry states what is built. +- **The limit of this release: a log that loses whole steps carries no mark (ruling 7268216330 on #37767).** The engine marks one thing: a step whose child-run links were shed carries `childRunIdsTruncated`, above. A log that loses whole steps carries no mark, whichever way it loses them: the engine's compaction of a log of more than 200 steps, the history row's halving of a log over its 64 KB cap, a row stored as null. The plugin reads what the log kept, and a child run named only by a dropped step reads as one the run went past: it is not read. For a halved row and a null row the plugin can still tell that steps are missing, from the run's summary, which counts every step: that is the second log read as cut, above, and the approval is held and then placed. For a compacted log it cannot tell. A run that logged more than 200 steps is stored with 200 of them: every top-level step and every failed step, then the most recent of the rest (the most recent 200 of the top-level and failed steps, where those alone pass 200), and it is judged from those, as before this change. What an operator gets in that case: a `subflow` or `map` step the compaction dropped (one that succeeded inside a `loop`, `parallel` or `try_catch` region, or an early step of a very long run) no longer names the child runs it started; a failure the flow routed inside such a child run, between two steps, is not seen; and the approval can be written as finished, with no notice and no line in the log. A process that still holds the run in memory reads its whole log, so this is a judgement made once that process is gone. No approval is judged worse than before this change, whose door read no child run. - **The kept reading is its own key.** It is written onto the snapshot read again just before the write, and only while the column still reads the same, at most three times. It cannot write a stale snapshot over a note another writer left there (`__laterStepNotOpened`, `__strandedContinuation`). The judgement reads the note that a later step could not open once it has read the runs, so a note that lands while they are read is judged with. - **A run that stopped, placed by the step last decided.** A run the engine has no row for and that no run the plugin read speaks for (its history is gone, or a process stopped while advancing it), a run whose step log is cut, above, a tree of more runs than the judgements can read in full, above, and the latest request's own run still parked at the step its decision was recorded on (a process stopped before the run was resumed), in the run that carries the record or in a child run any number of levels below it, are cannot tell for an hour from the approval's marks (the age bound). Past it, they have stopped at the step last decided. Whether a later step can follow that step is asked in the flow its request records, so a node of another flow that carries the step's id does not answer for it. Where one can, the approval is abandoned: the record is put back, the submitter is told and submits again, the decisions already made stay on their requests, and a run still parked there is cancelled, with the runs that wait on it up to the run that carries the record, through a `map` whose items are not records as through a `subflow`. The cancel follows the put-back, and is not tried again once the put-back has landed: where it fails, or the process stops between the two, the run stays parked, the approval stays abandoned, and the door that continues a restored run refuses it. At the last step, the outcome is written and, once that write has landed, the administrators are told that the flow did not go on after that step; the run's pause is left for an operator. A refused write sends no such notice, and the pass on which the write lands sends it. The notice says what to do in each case: continue or cancel a run that is still paused, and where the run has ended or no run is left, check that the steps after the decision were done. An approval placed for a cut log or a tree too large to read can be one whose flow did go on, which the plugin could not read in full: at its last step the administrators get the notice for a flow that ran, and where a later step can follow, the submitter submits again. - **The reconciler.** Each pass reads two windows of at most 200 marked requests (`unjudged_since`): the oldest marks, and the next page of a walk over every marked request by id, so that marks which stay cannot keep the newer ones from being read. It judges each approval among them once, as the door would have: it writes the outcome in the name of the request's recorded decider, abandons the approval, or, where nothing was held back, clears the mark and writes nothing (where it concluded that a run had stopped, a line in the log says so). It ends what no door saw: a run that was cancelled, a parent run cancelled while its child's request was pending, and the stopped runs above. Past the age bound it also reads as stopped where it stood a run that reports paused while its pause is gone, and a run parked at a `subflow` or a `map` whose child run has ended or has no row. The item run of a `map` whose items are records is such a child once it is in a terminal status: its steps are an approval of the item's own record and are not read, only whether it has ended, and it is kept as ended only once it has. diff --git a/content/docs/automation/approvals.mdx b/content/docs/automation/approvals.mdx index 9b3e7899954..dd2ad7ab885 100644 --- a/content/docs/automation/approvals.mdx +++ b/content/docs/automation/approvals.mdx @@ -1709,17 +1709,24 @@ that does not list every run, or for more runs than the platform can read, can be one whose flow did go on: the platform could not read it in full, so the notice asks for a check and does not state a failure. -One long history is not read as incomplete. A run that logged more than 200 -steps is stored with 200 of them: its top-level steps and its failed steps -first, then the most recent of the rest. A `subflow` or `map` step that is not -among them (one that succeeded inside a `loop`, `parallel` or `try_catch`, or -an early step of a very long run) no longer lists the runs it started. A -judgement made from the stored history does not read those runs: a failure the -flow routed inside one of them is not seen, and the approval can be written as -finished, with no notice. A process that still holds the run in memory reads -all of its steps. For a flow whose run can log more than 200 steps and that -starts child flows inside such a region, read the outcome of those child runs -in the flow's run history as well. +A step history that loses whole steps carries no mark of it; this is a limit +of this release (ruling 7268216330 on #37767). The platform marks one thing: a +step that lost the list of the runs it started. Whole steps are lost in three +ways: a run that logged more than 200 steps is stored with 200 of them (its +top-level steps and its failed steps first, then the most recent of the rest); +a history over its 64 KB limit is stored as its most recent steps; and one that +still does not fit is stored with none. The platform reads what the history +kept, and a run named only by a step that was dropped reads as one the flow +went past: it is not read. In the last two cases the platform can still tell, +from the run's count of its steps, that steps are missing, and treats the +history as one that does not list every run, above. In the first it cannot. A +`subflow` or `map` step that is not among the 200 (one that succeeded inside a +`loop`, `parallel` or `try_catch`, or an early step of a very long run) no +longer lists the runs it started: a failure the flow routed inside one of them +is not seen, and the approval can be written as finished, with no notice. A +process that still holds the run in memory reads all of its steps. For a flow +whose run can log more than 200 steps and that starts child flows inside such a +region, read the outcome of those child runs in the flow's run history as well. Every decision on an approval any step of which can act on an object that declares `closedStates` leaves a mark on its request (`unjudged_since`), also diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 972b4fc71bc..0ad496792b4 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -2007,8 +2007,10 @@ export const HISTORY_STEPS_KEPT = 200; * the runs it leaves out are not read, and it does not speak for the runs * it does name. * - * - A step carries `childRunIdsTruncated`: its execution started more - * child runs than the 200 the engine names on a step. + * - A step carries `childRunIdsTruncated`: its links to child runs were + * shed. Its execution started more child runs than the 200 the engine + * names on a step, or the history row shed the step's list to fit its + * size. * - The history row of a run in a terminal status keeps fewer steps than * the run logged. The row bounds the log by bytes: over the bound it * keeps a tail of it, or stores none. The run's summary is folded before @@ -2019,6 +2021,15 @@ export const HISTORY_STEPS_KEPT = 200; * is absent, or that dropped its per-node detail, gives nothing to * compare, and the log is read as cut. * + * [Ruling 7268216330 on #37767, its question q1: as built] The mark is the + * only one the engine leaves. A log that loses whole steps carries none: + * the engine's compaction of a log of more than {@link HISTORY_STEPS_KEPT} + * steps, the row's halving over its size cap, a row stored as null. The + * plugin reads what the log kept. The second case above tells a halved row + * and a null row from the summary; a compacted log gives nothing to tell it + * by, and a child run named only by a step the compaction dropped reads as + * one the run went past. That is a stated limit of this release. + * * A run that has not ended is read from its pause, whose step log is not * bounded, so only the mark applies to it. */ From 596ee28f4b1c79f44a4b795cd92f3bee397cb762 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 05:05:44 +0000 Subject: [PATCH 19/23] test(approvals): the cases S14 of delta review 7269135624 owes, failing first (ADR-0162 item 8) Four cases on the reconciler's age bound, each red on this tree: - a run the engine is resuming past the bound, read inside that passage on the real engine (a wait between two steps that outlasts the hour): it reports paused with its pause gone, and the first judgement to read it so ends the approval's hold; - a run with no row on one judgement and back on the next; - a held approval whose run a judgement first reads as stopped past the bound: the record is put back at once; - a batch over records parked on an item that has just ended, which the engine then resumes. The suite's `mark` node gains a hook that runs inside the passage that reaches it, and the fixtures gain `wait_between`. An object that closes on its approval field admits no pause between two steps, so the two shapes that wait there by design run on a ticket, which holds nothing back. Claude-Session: https://claude.ai/code/session_01JQwxbaoxpe1tyHuqnsAUFB Co-authored-by: Claude --- ...roval-reconciler-37767.integration.test.ts | 115 ++++++++++++++++++ 1 file changed, 115 insertions(+) diff --git a/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts index 67be38d9378..510377d0e11 100644 --- a/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts @@ -161,6 +161,10 @@ const FLOWS = [ flow('child_named_final', [mark('final')], [edge('start', 'final'), edge('final', 'end')]), flow('gate_sub_final', [step('gate', 'approver'), { id: 'sub', type: 'subflow', label: 'Sub', config: { flowName: 'child_named_final' } }, step('final', 'approver2')], [edge('start', 'gate'), edge('gate', 'sub', 'approve'), edge('gate', 'end', 'reject'), edge('sub', 'final'), ...decided('final', 'end')]), + // ── The fixture of the patch on delta review 7269135624 ── + // A wait between the two steps that outlasts the age bound by design, then a node before the second step. + flow('wait_between', [step('first', 'approver'), WAIT, mark('probe'), step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'hold', 'approve'), edge('first', 'end', 'reject'), edge('hold', 'probe'), edge('probe', 'second'), ...decided('second', 'end')]), ]; describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges what no door did', () => { @@ -170,6 +174,8 @@ describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges let svc: ApprovalService; /** Nodes of type `mark` that throw, by id. */ let throwOn: Set; + /** What runs while a node of type `mark` executes, by id: inside the passage that reached it. */ + let during: Map Promise>; /** What each `read` node saw on the record's field. */ let seen: unknown[]; let notices: Array<{ topic: string; audience: string[] }>; @@ -181,6 +187,7 @@ describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges beforeEach(async () => { throwOn = new Set(); + during = new Map(); seen = []; notices = []; kernel = new ObjectKernel({ logger: { level: 'silent' } } as any); @@ -220,6 +227,7 @@ describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges descriptor: { type: 'mark', supportsPause: false }, async execute(node: any, _variables: any, context: any) { if (throwOn.has(node.id)) throw new Error(`${node.id} failed`); + await during.get(node.id)?.(); if (node.id === 'read') { const id = context?.record?.id; seen.push((await ql.find(context?.object ?? 'crm_invoice', { where: { id }, context: SYS }))[0]?.approval_status); @@ -1537,6 +1545,113 @@ describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges // 201 runs of the child flow through the real engine and its store: // well over the default timeout on a loaded runner (12 s measured in CI). }, 60_000); + + describe('the patch on delta review 7269135624: past the bound, a run is placed only once two judgements in a row read it the same', () => { + // An object that closes on its approval field admits no pause + // between two steps (the opening check refuses the flow), so the + // approvals that wait there by design are those that hold nothing + // back: a ticket, which closes on another field. + it('[S14] a run the engine is resuming past the bound is not placed: its approval waited longer than the bound between two steps, by design', async () => { + await start('wait_between', 'crm_ticket', 't_s14_live'); + await decide('t_s14_live', 'approve', 'approver'); + const [first] = await requestsOn('t_s14_live'); + const runId = String(first.record_run_id); + expect((await automation.suspensionOf(runId))?.nodeId, 'parked at the wait, between the two steps').toBe('hold'); + expect(await marks('t_s14_live')).toEqual([true]); + // The wait outlasts the bound, and a sweep in that time reads the run as in progress. + await age('t_s14_live'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ in_progress: 1 }); + + // The wait ends and the engine resumes the run. The sweep of + // another process reads the run inside that passage: its pause is + // consumed, and it has not parked again. + let inside: unknown; + during.set('probe', async () => { + const readAs = [(await automation.getRun(runId))?.status, (await automation.suspensionOf(runId))?.nodeId]; + const judged = (await svc.reconcileMarkedApprovals()).judged; + inside = { readAs, judged, marks: await marks('t_s14_live') }; + }); + await automation.resume(runId); + expect(inside, 'inside the passage the run reports paused with its pause gone, and the first judgement to read it so cannot tell').toEqual({ + readAs: ['paused', undefined], judged: { undetermined: 1 }, marks: [true], + }); + expect(await steps('t_s14_live'), 'the run went on to its second step').toEqual([['first', 'approved'], ['second', 'pending']]); + expect(await marks('t_s14_live'), 'the approval is still held').toEqual([true, false]); + expect((await svc.reconcileMarkedApprovals()).judged, 'the second step is pending').toEqual({ in_progress: 1 }); + }); + + it('[S14] a run with no row on one judgement and back on the next is not placed; one that stays without a row is placed by the judgement after', async () => { + await start('wait_between', 'crm_ticket', 't_s14_norow'); + await decide('t_s14_norow', 'approve', 'approver'); + const [first] = await requestsOn('t_s14_norow'); + const runId = String(first.record_run_id); + await age('t_s14_norow'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ in_progress: 1 }); + + // A process that does not hold the run reads no row for it while another advances it. + trimmed.add(runId); + expect((await svc.reconcileMarkedApprovals()).judged, 'the first judgement to read no row cannot tell').toEqual({ undetermined: 1 }); + expect(await marks('t_s14_norow')).toEqual([true]); + trimmed.delete(runId); + expect((await svc.reconcileMarkedApprovals()).judged, 'the run is back, parked between two steps').toEqual({ in_progress: 1 }); + + // The row goes again and stays gone: the judgement that reads it + // so starts over, and the one after it places the run. + trimmed.add(runId); + expect((await svc.reconcileMarkedApprovals()).judged, 'read so anew: the earlier reading does not count').toEqual({ undetermined: 1 }); + expect(await marks('t_s14_norow')).toEqual([true]); + expect((await svc.reconcileMarkedApprovals()).judged, 'read the same twice in a row: the hold ends').toEqual({ ended: 1 }); + expect(await marks('t_s14_norow')).toEqual([false]); + }); + + it('[S14] where the approval holds a decision back, the judgement that first reads a run as stopped past the bound writes nothing, and the next one puts the record back', async () => { + await start('two_step', 'crm_invoice', 'i_s14_held'); + const [first] = await requestsOn('i_s14_held'); + // Decided, marked, and a run that reports paused with no pause; + // no judgement read it before the bound passed. + await ql.update('sys_approval_request', { id: first.id, status: 'approved', unjudged_since: new Date().toISOString() }, { context: SYS }); + const runId = String(first.flow_run_id); + const suspensionOf = (automation as any).suspensionOf.bind(automation); + (automation as any).suspensionOf = async (id: string) => (id === runId ? undefined : suspensionOf(id)); + await age('i_s14_held'); + notices.length = 0; + + expect((await svc.reconcileMarkedApprovals()).judged, 'the first judgement to read it so').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_s14_held'), 'nothing is put back').toBe('pending'); + expect(await marks('i_s14_held')).toEqual([true]); + expect(notified('approval.abandoned'), 'and nobody is told to submit again').toEqual([]); + + expect((await svc.reconcileMarkedApprovals()).judged, 'read the same twice in a row').toEqual({ abandoned: 1 }); + expect(await field('crm_invoice', 'i_s14_held')).toBe('recalled'); + expect(await marks('i_s14_held')).toEqual([false]); + }); + + it('[S14] a batch over records parked on an item that has just ended is not placed by the first judgement that reads it so, and goes on when the engine resumes it', async () => { + await seedLines(); + await start('first_then_records', 'crm_ticket', 't_s14'); + await withoutDoor(() => decide('t_s14', 'approve', 'approver')); + const [first] = await requestsOn('t_s14'); + const batch = String(first.record_run_id); + const item = await itemOf(batch); + // The item waits for its own approval longer than the bound. + await age('t_s14'); + expect((await svc.reconcileMarkedApprovals()).judged, 'the item has not ended').toEqual({ in_progress: 1 }); + + // The item's run ends, and the engine has not resumed the batch yet. + await automation.cancelRun(item); + expect([await statusOf(item), await statusOf(batch)]).toEqual(['cancelled', 'paused']); + expect((await svc.reconcileMarkedApprovals()).judged, 'the first judgement to read the item as ended does not place the batch').toEqual({ in_progress: 1 }); + expect(await marks('t_s14')).toEqual([true]); + + // The engine resumes the batch, which goes on to its next item. + await automation.resume(batch); + const next = await itemOf(batch); + expect(next, 'the batch waits on another item').not.toBe(item); + expect(await statusOf(next)).toBe('paused'); + expect((await svc.reconcileMarkedApprovals()).judged, 'parked on an item that has not ended').toEqual({ in_progress: 1 }); + expect(await marks('t_s14')).toEqual([true]); + }); + }); }); }); }); From 9e225b1983f752e02b56eabb9cb54e403a2980d6 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 05:26:48 +0000 Subject: [PATCH 20/23] fix(approvals): past the bound, a run is placed only once two judgements in a row read it the same (ADR-0162 item 8) S14 of delta review 7269135624. The hour of the age bound is counted from the approval's marks, and a run the engine is resuming reads as paused with its pause gone, or as a run with no row. An approval that waits longer than the hour between two steps is past the bound whenever it resumes, so a pass that read its run inside that passage placed it. A state that says a run has stopped now stands only where the judgement before read the same state for the same run. Every judgement keeps the states it read on the approval's latest request (`stood` in `__runsRead`), in place of those kept before, whatever it answers and whether the marks have aged or not: - a run that reports paused while its pause is gone; - a run parked at a `subflow` or a `map` on a child that has ended or has no row, with that child; - the latest request's own run still parked at its step, a run whose step log is cut, a run with no row that no run speaks for, and a tree of more runs than one judgement reads. The first judgement to read one of them past the bound cannot tell (in progress, for a run parked on an ended child), and the next places the run if it reads the same. A reading taken while a request is open keeps no such state, and only the latest request's kept states count, so nothing read before a later request opened stands after it. A reading that cannot be kept leaves the next judgement nothing to stand on. The suite: the four cases of the commit before pass, and the tail of the live-resume case is corrected (the opening of the second request clears the first one's mark, and the reconciler then scans nothing). Four earlier cases that placed at the first aged judgement now take a judgement within the bound first, as a sweep gives them. Three cases are new: a reading that cannot be kept, a request still open, and a state read before a later request opened. N25 of the same review: the docblock of `runsReadAfter` said the opposite of what the overflow rule does; it now says what the rule does and what keeps it from changing an answer. The sentences that say what the administrators are told follow the notice's own words. Claude-Session: https://claude.ai/code/session_01JQwxbaoxpe1tyHuqnsAUFB Co-authored-by: Claude --- ...roval-reconciler-37767.integration.test.ts | 106 +++++- .../plugin-approvals/src/approval-service.ts | 344 +++++++++++++----- 2 files changed, 357 insertions(+), 93 deletions(-) diff --git a/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts index 510377d0e11..7f4424c4dad 100644 --- a/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts @@ -646,9 +646,10 @@ describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges await settle(withoutResume(() => decide('i_norow_mid', 'approve', 'approver'))); const [first] = await requestsOn('i_norow_mid'); trimmed.add(String(first.record_run_id)); + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound: cannot tell').toEqual({ undetermined: 1 }); await age('i_norow_mid'); notices.length = 0; - expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ abandoned: 1 }); + expect((await svc.reconcileMarkedApprovals()).judged, 'past the bound, and the judgement before read the same').toEqual({ abandoned: 1 }); expect(await steps('i_norow_mid'), 'the decision stays on its request').toEqual([['first', 'approved']]); expect(await field('crm_invoice', 'i_norow_mid')).toBe('recalled'); expect(notified('approval.abandoned')).toEqual([['owner']]); @@ -1333,9 +1334,11 @@ describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges // The tree of two map steps, whose first reading keeps 199 item runs. tree(String(last.record_run_id), [fan('fan_a', ids('run_a')), fan('fan_b', ids('run_b'))], (id) => (/^run_[ab]_\d+$/.test(id) ? ended(id, `line_of_${id}`) : undefined)); + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound: the tree is too large to read, and what was read is kept').toEqual({ undetermined: 1 }); + expect((await keptOn('i_s11_unkept')).ended).toHaveLength(199); await age('i_s11_unkept'); - // The store refuses the kept reading, on every try: the next - // judgement would start from nothing again, and so would every one after it. + // From here the store refuses the kept reading, on every try: a + // judgement that reads on would find the next one where it is itself. const update = ql.update.bind(ql); (ql as any).update = async (o: string, data: any, options?: any) => { if (o === 'sys_approval_request' && String(data?.node_config_json ?? '').includes('__runsRead')) throw new Error('the store refused the write'); @@ -1344,7 +1347,7 @@ describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges notices.length = 0; expect((await svc.reconcileMarkedApprovals()).judged, 'what it read is not on the request, so it does not wait for a next reading').toEqual({ finished: 1 }); - expect((await keptOn('i_s11_unkept'))?.ended ?? [], 'nothing was kept').toEqual([]); + expect((await keptOn('i_s11_unkept')).ended, 'the one run more it read to its end was not kept').toHaveLength(199); expect(await field('crm_invoice', 'i_s11_unkept')).toBe('approved'); expect(await marks('i_s11_unkept')).toEqual([false, false]); expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); @@ -1396,10 +1399,11 @@ describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges // The item run ends, and nothing resumes the batch. await automation.cancelRun(item); expect([await statusOf(item), await statusOf(batch)]).toEqual(['cancelled', 'paused']); + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound: the engine may still be resuming the batch').toEqual({ in_progress: 1 }); expect(await marks('t_s12')).toEqual([true]); await age('t_s12'); - expect((await svc.reconcileMarkedApprovals()).judged, 'the batch is parked between two steps on a run that has ended').toEqual({ ended: 1 }); + expect((await svc.reconcileMarkedApprovals()).judged, 'the batch is parked between two steps on a run that has ended, as the judgement before read it').toEqual({ ended: 1 }); expect(await marks('t_s12'), 'the ticket closes on another field, so nothing was held back: the hold ends').toEqual([false]); expect(await steps('t_s12'), 'the decision stays on its request').toEqual([['first', 'approved']]); expect((await svc.reconcileMarkedApprovals()).scanned, 'nothing left to judge').toBe(0); @@ -1459,6 +1463,7 @@ describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges // No door judged, and the run that carries the record has no row any more. trimmed.add(String(last.record_run_id)); + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound: cannot tell').toEqual({ undetermined: 1 }); await age('i_n20'); notices.length = 0; expect((await svc.reconcileMarkedApprovals()).judged, 'placed by its last step: no step can follow it').toEqual({ finished: 1 }); @@ -1576,8 +1581,8 @@ describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges readAs: ['paused', undefined], judged: { undetermined: 1 }, marks: [true], }); expect(await steps('t_s14_live'), 'the run went on to its second step').toEqual([['first', 'approved'], ['second', 'pending']]); - expect(await marks('t_s14_live'), 'the approval is still held').toEqual([true, false]); - expect((await svc.reconcileMarkedApprovals()).judged, 'the second step is pending').toEqual({ in_progress: 1 }); + expect(await marks('t_s14_live'), 'the opening of the second step answers the mark of the first, as any opening does').toEqual([false, false]); + expect((await svc.reconcileMarkedApprovals()).scanned, 'the approval is in its second step: nothing is left to judge').toBe(0); }); it('[S14] a run with no row on one judgement and back on the next is not placed; one that stays without a row is placed by the judgement after', async () => { @@ -1626,6 +1631,34 @@ describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges expect(await marks('i_s14_held')).toEqual([false]); }); + it('[S14] a judgement whose reading cannot be kept leaves nothing for the next to stand on: the approval is held until one is kept, and placed by the judgement after', async () => { + await start('two_step', 'crm_invoice', 'i_s14_unkept'); + await decide('i_s14_unkept', 'approve', 'approver'); + await withoutDoor(() => decide('i_s14_unkept', 'approve', 'approver2')); + const [, last] = await requestsOn('i_s14_unkept'); + trimmed.add(String(last.record_run_id)); + await age('i_s14_unkept'); + const update = ql.update.bind(ql); + let refuse = true; + (ql as any).update = async (o: string, data: any, options?: any) => { + if (refuse && o === 'sys_approval_request' && String(data?.node_config_json ?? '').includes('__runsRead')) throw new Error('the store refused the write'); + return update(o, data, options); + }; + notices.length = 0; + + for (const pass of ['the first judgement', 'the one after it']) { + expect((await svc.reconcileMarkedApprovals()).judged, `${pass}: what it read is not on the request`).toEqual({ undetermined: 1 }); + expect(await keptOn('i_s14_unkept'), pass).toBeUndefined(); + expect(await field('crm_invoice', 'i_s14_unkept'), pass).toBe('pending'); + } + refuse = false; + expect((await svc.reconcileMarkedApprovals()).judged, 'the reading is kept').toEqual({ undetermined: 1 }); + expect((await keptOn('i_s14_unkept')).stood, 'with the state it read, and the run').toEqual([`no_row ${String(last.record_run_id)}`]); + expect((await svc.reconcileMarkedApprovals()).judged, 'read the same twice in a row').toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_s14_unkept')).toBe('approved'); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + }); + it('[S14] a batch over records parked on an item that has just ended is not placed by the first judgement that reads it so, and goes on when the engine resumes it', async () => { await seedLines(); await start('first_then_records', 'crm_ticket', 't_s14'); @@ -1648,8 +1681,65 @@ describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges const next = await itemOf(batch); expect(next, 'the batch waits on another item').not.toBe(item); expect(await statusOf(next)).toBe('paused'); - expect((await svc.reconcileMarkedApprovals()).judged, 'parked on an item that has not ended').toEqual({ in_progress: 1 }); + expect(await marks('t_s14'), 'the approval is still held').toEqual([true]); + + // That item ends in turn before a judgement comes. The batch is + // parked on a run that has ended, as the judgement before read + // it; but on another run, so it is read anew. + await automation.cancelRun(next); + expect((await svc.reconcileMarkedApprovals()).judged, 'parked on another item that has ended: not the state read before').toEqual({ in_progress: 1 }); expect(await marks('t_s14')).toEqual([true]); + // Nothing resumes the batch this time, and the judgement after reads the same. + expect((await svc.reconcileMarkedApprovals()).judged, 'read the same twice in a row: the hold ends').toEqual({ ended: 1 }); + expect(await marks('t_s14')).toEqual([false]); + }); + + it('[S14] a run parked at the step of a request that is still open has not stopped there: what is read while the request is open does not stand once it is decided', async () => { + await start('two_step', 'crm_invoice', 'i_s14_open'); + // The door after the first decision reads the runs with the second request open. + await decide('i_s14_open', 'approve', 'approver'); + const [, open] = await requestsOn('i_s14_open'); + expect([open.status, kept(open)?.stood], 'read with the request open: no state is kept').toEqual(['pending', undefined]); + // The second step is decided, and the process stops before its + // run is resumed and before the door judges. + await withoutDoor(() => settle(withoutResume(() => decide('i_s14_open', 'approve', 'approver2')))); + const [, last] = await requestsOn('i_s14_open'); + expect([last.status, (await automation.suspensionOf(String(last.flow_run_id)))?.nodeId], 'decided, and its run still parked at its step').toEqual(['approved', 'second']); + expect(kept(last)?.stood, 'nothing read while it was open is kept as a state').toBeUndefined(); + await age('i_s14_open'); + notices.length = 0; + + expect((await svc.reconcileMarkedApprovals()).judged, 'the first judgement to read the run as stopped at its own step').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_s14_open')).toBe('pending'); + expect((await svc.reconcileMarkedApprovals()).judged, 'read the same twice in a row: placed by its last step').toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_s14_open')).toBe('approved'); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + }); + + it('[S14] a state read before a later request opened does not stand for the judgement after it', async () => { + await start('wait_between', 'crm_ticket', 't_s14_later'); + await decide('t_s14_later', 'approve', 'approver'); + const [first] = await requestsOn('t_s14_later'); + const runId = String(first.record_run_id); + // A judgement reads no row for the run, and keeps that on the first request. + trimmed.add(runId); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ undetermined: 1 }); + expect(kept((await requestsOn('t_s14_later'))[0]).stood).toEqual([`no_row ${runId}`]); + trimmed.delete(runId); + // The run goes on: the second request opens and is decided, with + // no door judging, and the run reaches its end. + await automation.resume(runId); + await withoutDoor(() => decide('t_s14_later', 'approve', 'approver2')); + expect(await statusOf(runId)).toBe('completed'); + expect(await marks('t_s14_later')).toEqual([false, true]); + + // Its row is gone again when the first judgement after comes, past the bound. + trimmed.add(runId); + await age('t_s14_later'); + expect((await svc.reconcileMarkedApprovals()).judged, 'what was read before the second request opened does not stand').toEqual({ undetermined: 1 }); + expect(await marks('t_s14_later')).toEqual([false, true]); + expect((await svc.reconcileMarkedApprovals()).judged, 'read the same twice in a row').toEqual({ finished: 1 }); + expect(await marks('t_s14_later')).toEqual([false, false]); }); }); }); diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 0ad496792b4..cc626e56d0c 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -1947,9 +1947,19 @@ type RunStepRead = { * it cannot tell, and the approval keeps its mark. Past the bound it answers * so only while it keeps a run the approval had not kept; the judgement that * keeps none cannot finish the tree, and the approval is placed by the step - * last decided ({@link RECONCILER_AGE_BOUND_MS}; S11 of contract review - * 7266979193). The kept list only grows and holds this many runs, so the - * judgements that read on are numbered. + * last decided, as a tree the judgement before it met too + * ({@link RECONCILER_AGE_BOUND_MS}; S11 of contract review 7266979193). The + * kept list only grows and holds this many runs, so the judgements that + * read on are numbered: at most this many passes of the reconciler. + * + * The tree it does not finish is placed without being finished, which is + * the cost the seat accepted with that rule (L1 7269166540). It is not only + * a tree of more runs than the two kept lists hold: the walk reads the runs + * it starts from before the runs below them, so a `map` of 199 items that + * each call a `subflow`, about 399 runs, is already one no reading finishes + * (N26 of delta review 7269135624). And the placement follows from the + * flow's shape, so an approval submitted again on the same flow meets the + * same end (N27 of that review). * * It is also how many child runs the engine names on one step before it * marks the step (`childRunIdsTruncated`); the suite ties the two on a real @@ -1959,10 +1969,24 @@ export const MAX_RUNS_READ_PER_APPROVAL = 200; /** * [ADR-0162 Execution item 8] How long an approval's marks stand before the - * reconciler reads a run that will not move again as stopped. It is measured + * reconciler reads a run in one of six states as stopped. It is measured * from the marks: every mark of the approval has stood this long. Within it * nothing is written for any of the six states it governs, at the - * approval's last step as at any other (ruling 3 on #37767). Past it: + * approval's last step as at any other (ruling 3 on #37767). + * + * Past it, a state says the run has stopped only where two judgements in a + * row read it, for the same run (S14 of delta review 7269135624; + * {@link stoodState}). The hour is counted from the marks and not from the + * run's last movement, so an approval that waits longer than the hour + * between two steps by design (a `wait` node, a batch over records whose + * items are approved one by one, a child parked outside the set) is past + * the bound from the first instant of every later resume; and a run the + * engine is resuming reads as paused with its pause gone, or as a run with + * no row. That state clears within the passage, and the one a dead process + * left is read again by the next judgement. The judgement that reads a + * state for the first time answers that it cannot tell, and keeps what it + * read; a judgement within the bound keeps it too, so an approval that was + * read within the hour is placed by the first judgement past it. The six: * * - a run that reports paused while its pause is gone has stopped at the * last step it logged; @@ -1985,7 +2009,11 @@ export const MAX_RUNS_READ_PER_APPROVAL = 200; * One hour: far past any passage a live process completes (a passage is the * work between a decision and the next step, run in the same call), and * short enough that a record a dead process left held is released the same - * working session. + * working session. A passage that begins after the hour is what the second + * reading is for. Two judgements in a row that each fall inside a passage + * of the same run, one passage or two, still read it as stopped: the sweep + * clock sets how far apart two passes of one process are, and nothing sets + * it for two processes or for a pass at boot. */ export const RECONCILER_AGE_BOUND_MS = 60 * 60 * 1000; @@ -2136,7 +2164,13 @@ const KEEP_RUNS_READ_ATTEMPTS = 3; * since nothing can name its children any more; * - `between`: a failure between two steps found in a run that ended, with * its instant, which counts while no later request of the approval - * opened after it (an instant it could not read always counts). + * opened after it (an instant it could not read always counts); + * - `stood`: the states the last judgement read that say a run has stopped + * only once they stand ({@link stoodState}), each with its run. It is + * what that one judgement read and no more: the next judgement places a + * run only where its state is in this list, and writes its own list in + * its place (S14 of delta review 7269135624). It holds at most two + * states for each run one judgement reads, and one for the tree. * * A run that has not ended is not kept: the engine does not trim it, and * the walk reaches it again from the runs above it. @@ -2145,6 +2179,37 @@ interface RunsRead { readonly ended: readonly string[]; readonly open: readonly string[]; readonly between?: { readonly why: string; readonly at: string | null }; + readonly stood?: readonly string[]; +} + +/** + * [ADR-0162 Execution item 8, S14 of delta review 7269135624] A state of a + * run that says the run has stopped only once it stands: a judgement past + * the age bound places it only where the judgement before read the same + * state for the same run ({@link RunsRead}, `stood`). While the engine + * advances a run, the run has no pause and has not parked again or ended, + * so every reader sees it as paused with its pause gone, or as a run with + * no row; and between a child's end and the resume of the run parked on it, + * that run is parked on a child that has ended. Each of these is also what + * a dead process leaves. The first clears within the passage that causes + * it, and the second stands. + * + * - `pause_gone`: the run reports paused, and no pause of it can be found; + * - `on_ended`: the run is parked at a `subflow` or a `map` on the child + * `on`, which has ended or has no row; + * - `own_node`: the latest request's own run is still parked at the step + * its decision was recorded on; + * - `cut`: the run's step log does not name every child run it started; + * - `no_row`: the run has no row, and no run that was read speaks for it; + * - `tree`: the approval's runs number more than one judgement reads (on + * the run that carries the record). + * + * Spelled with spaces, kind first: it is compared as a whole and never + * parsed, and it is not of the `:` shape this package keeps for + * approver addresses. + */ +function stoodState(kind: 'pause_gone' | 'on_ended' | 'own_node' | 'cut' | 'no_row' | 'tree', runId: string, on?: string): string { + return on === undefined ? `${kind} ${runId}` : `${kind} ${runId} ${on}`; } /** The instant of an ISO date, or `NaN`. */ @@ -2152,14 +2217,23 @@ function instantOf(v: unknown): number { return v == null || v === '' ? NaN : new Date(v as string).getTime(); } -/** [ruling A3] What the requests of one approval kept of its runs, merged ({@link RUNS_READ_KEY}). */ +/** + * [ruling A3] What the requests of one approval kept of its runs, merged + * ({@link RUNS_READ_KEY}); `approval` is read oldest first. `stood` is not + * merged: it is the list on the approval's latest request, where every + * judgement keeps its reading, and no other. A request that opened since + * the last judgement carries none, so the states are read anew after it. + */ function runsReadOf(approval: readonly any[]): RunsRead { const ended = new Set(); const open = new Set(); let between: RunsRead['between']; + let stood: string[] = []; + const latest = approval[approval.length - 1]; for (const r of approval) { const kept = parseJson>(r?.node_config_json, {})[RUNS_READ_KEY] as Partial | undefined; if (!kept || typeof kept !== 'object') continue; + if (r === latest && Array.isArray(kept.stood)) stood = kept.stood.filter((v): v is string => typeof v === 'string' && v !== ''); for (const id of Array.isArray(kept.ended) ? kept.ended : []) if (typeof id === 'string' && id) ended.add(id); for (const id of Array.isArray(kept.open) ? kept.open : []) if (typeof id === 'string' && id) open.add(id); const b = kept.between; @@ -2170,13 +2244,17 @@ function runsReadOf(approval: readonly any[]): RunsRead { } } // A run one request kept as open and a later one as ended has ended. - return { ended: [...ended], open: [...open].filter((id) => !ended.has(id)), ...(between ? { between } : {}) }; + return { + ended: [...ended], open: [...open].filter((id) => !ended.has(id)), ...(between ? { between } : {}), + ...(stood.length > 0 ? { stood } : {}), + }; } /** Whether two kept readings say the same, whatever the order of their lists. */ function sameRunsRead(a: RunsRead, b: RunsRead): boolean { const same = (x: readonly string[], y: readonly string[]) => x.length === y.length && [...x].sort().join('\n') === [...y].sort().join('\n'); - return same(a.ended, b.ended) && same(a.open, b.open) && JSON.stringify(a.between ?? null) === JSON.stringify(b.between ?? null); + return same(a.ended, b.ended) && same(a.open, b.open) && same(a.stood ?? [], b.stood ?? []) + && JSON.stringify(a.between ?? null) === JSON.stringify(b.between ?? null); } /** @@ -2213,8 +2291,9 @@ function keptAsEnded( * for {@link runsReadAfter}: the runs read in a terminal status * (`terminal`), the item runs of another record that are in a terminal * status (`foreign`), the runs with no row (`noRow`), the runs a run that - * was read went on past (`passed`), and the child runs each run that was - * read names (`childrenOf`). + * was read went on past (`passed`), the child runs each run that was read + * names (`childrenOf`), and the states it read that say a run has stopped + * only once they stand (`stood`, {@link stoodState}). */ interface RunsFound { readonly terminal: Set; @@ -2222,10 +2301,11 @@ interface RunsFound { readonly noRow: Set; readonly passed: Set; readonly childrenOf: Map; + readonly stood: Set; } const noRunsFound = (): RunsFound => ({ - terminal: new Set(), foreign: new Set(), noRow: new Set(), passed: new Set(), childrenOf: new Map(), + terminal: new Set(), foreign: new Set(), noRow: new Set(), passed: new Set(), childrenOf: new Map(), stood: new Set(), }); /** @@ -2246,10 +2326,25 @@ function passedWithNoRow(prior: RunsRead, found: RunsFound): Set { * `ended` only grows, by the runs {@link keptAsEnded} allows; `open` is the * runs read in a terminal status, now or before, that are not ended. * - * Each list holds at most {@link MAX_RUNS_READ_PER_APPROVAL} runs. A run - * left out of `ended` is read again, which costs a read and changes no - * answer. A run left out of `open` could later be taken as passed, so a - * reading whose `open` does not fit keeps the lists as they were. + * Each of the two lists holds at most {@link MAX_RUNS_READ_PER_APPROVAL} + * runs. A run left out of `ended` is read again, which costs a read and + * changes no answer. + * + * A reading whose `open` would not fit keeps both lists as they were (N25 + * of delta review 7269135624: this is what the rule does). The runs it read + * in a terminal status beyond them are then in neither list: they are not + * kept as open, so one of them whose row is gone by a later reading can be + * taken as passed where a run that was read went on past it + * ({@link passedWithNoRow}). The rule does not prevent that. It does not + * change the answer either, by two facts nothing pins: a list holds as many + * runs as one judgement reads, and the walk reads the runs it starts from, + * the `open` runs among them, before the runs below them (the child a + * parked run waits on excepted). So `open` passes the bound only where the + * approval already holds nearly that many open runs, and from then on every + * reading spends its reads on them and cannot finish the tree: the approval + * is cannot tell and, past the age bound, placed. + * + * `stood` is not merged: it is what this reading read ({@link RunsRead}). */ function runsReadAfter(prior: RunsRead, found: RunsFound, between: RunsRead['between']): RunsRead { const settled = new Set(prior.ended); @@ -2258,10 +2353,10 @@ function runsReadAfter(prior: RunsRead, found: RunsFound, between: RunsRead['bet for (const id of [...found.foreign, ...gone]) childrenOf.set(id, []); const now = keptAsEnded(new Set([...found.terminal, ...found.foreign, ...gone]), childrenOf, settled); const open = [...new Set([...prior.open, ...found.terminal])].filter((id) => !settled.has(id) && !now.has(id)); - const withBetween = between ? { between } : {}; - if (open.length > MAX_RUNS_READ_PER_APPROVAL) return { ended: prior.ended, open: prior.open, ...withBetween }; + const rest = { ...(between ? { between } : {}), ...(found.stood.size > 0 ? { stood: [...found.stood] } : {}) }; + if (open.length > MAX_RUNS_READ_PER_APPROVAL) return { ended: prior.ended, open: prior.open, ...rest }; const ended = [...prior.ended, ...[...now].filter((id) => !settled.has(id))].slice(0, MAX_RUNS_READ_PER_APPROVAL); - return { ended, open, ...withBetween }; + return { ended, open, ...rest }; } /** @@ -2279,8 +2374,9 @@ function runsReadAfter(prior: RunsRead, found: RunsFound, between: RunsRead['bet * which says what this run says (`ApprovalService.waitingRun`); * - `own_node`: the latest request's own run, parked at that request's node; * - `read`: everything else. `over`: it is in a terminal status. `stopped`: - * it reports paused at a pause that is gone, past the age bound, so it - * will not go on. `endedWhy`: it ended, or stopped, between two steps. + * it reports paused at a pause that is gone, past the age bound and as + * the judgement before read it ({@link stoodState}), so it will not go + * on. `endedWhy`: it ended, or stopped, between two steps. * * `cut`, on any of the last four: why its step log does not name every * child run it started ({@link stepLogCut}). @@ -5710,13 +5806,17 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * reconciler. * * Past the age bound (`opts.ageBoundMs`, the reconciler's), the last four - * have stopped at the step last decided (rulings A3 and B2 on #37767; a - * tree of more runs than one judgement reads, once a judgement keeps no - * run the approval had not kept, S11 of contract review 7266979193): where + * have stopped at the step last decided, once two judgements in a row + * read the same of the same run (S14 of delta review 7269135624; + * {@link stoodState}), and the first of the two cannot tell (rulings A3 + * and B2 on #37767; a tree of more runs than one judgement reads, once a + * judgement keeps no run the approval had not kept, S11 of contract + * review 7266979193): where * a step can follow it, the approval is abandoned and a run still parked * there is cancelled, with the runs that wait on it ({@link cancelStoppedRun}); * where none can, it is finished, and once its outcome is on the record the - * administrators are told that its flow did not go on after its last step + * administrators are told that its flow could not be seen through to its + * end after its last step * ({@link reportFlowNotContinued}; ruling 3 on #37767: the outcome and the * notice in one stroke, so a refused write sends no notice, and the pass on * which the write lands sends it). @@ -5767,8 +5867,15 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // runs it can reach and keeps what it read, so that a child run that // ended in this passage is read before its row can be trimmed. The // answer of the reading is not used: an open request is in progress. + // Nor are the states it read kept (S14 of delta review 7269135624): + // this is no judgement, and a run parked at the step of a request + // that is still open has not stopped there. What it keeps carries no + // such state, so a judgement after it reads them anew. try { - await this.keepRunsRead(latest, approval, (await this.readCarryingRun(latest, stamp, approval)).kept); + const read = (await this.readCarryingRun(latest, stamp, approval)).kept; + await this.keepRunsRead(latest, approval, read && { + ended: read.ended, open: read.open, ...(read.between ? { between: read.between } : {}), + }); } catch (err: any) { this.logger?.warn?.('[approvals] could not read an approval\'s runs at a door that left a request open; the next door reads them', { request: requestId, error: err?.message ?? String(err), @@ -5784,7 +5891,8 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega } // The reconciler's age bound: every mark of the approval has stood past - // it, so a run that has not moved since will not move again. + // it. A state that says a run has stopped then places the run, where + // the judgement before read the same ({@link stoodState}). const now = this.clock.now().getTime(); const aged = opts?.ageBoundMs != null && marked.every((r) => { const at = new Date(r.unjudged_since).getTime(); @@ -5857,8 +5965,8 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega ); // [ruling 3 on #37767] The outcome and the administrators' notice in // one stroke. A refused write keeps the marks and sends no notice - // that the flow did not go on (the mirror reports its refusal); the - // pass on which the write lands sends it. + // that the flow could not be seen through to its end (the mirror + // reports its refusal); the pass on which the write lands sends it. if (!refusal) { if (lastStepStopped !== undefined) await this.reportFlowNotContinued(latest, lastStepStopped); await this.clearMarks(marked); @@ -5904,7 +6012,8 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * * - A run that cannot be read because the store did not answer, that * another process is advancing, or that reports paused with no pause to - * be found (within the age bound): `undetermined`. + * be found (within the age bound, and past it where the judgement + * before did not read it so): `undetermined`. * - A tree of more runs than one judgement reads * ({@link MAX_RUNS_READ_PER_APPROVAL}): `undetermined` within the age * bound, and past it while this reading keeps a run the approval had @@ -5925,8 +6034,10 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * step log is cut ({@link stepLogCut}: the runs it leaves out cannot be * read), a tree this reading could not finish, or the latest request's * own run still parked at its own node: within the bound - * `undetermined`, past it `placed`: the run has stopped at the step - * last decided (rulings A3 and B2 on #37767, one rule), and + * `undetermined`; past it `placed` where the judgement before read + * every such state of this reading too, and `undetermined` where it + * did not. Placed, the run has stopped at the step last decided + * (rulings A3 and B2 on #37767, one rule), and * {@link judgeApprovalAfterDoor} ends the approval by whether a step can * follow that step. * - Otherwise `finished`. @@ -5946,12 +6057,21 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * step failed. * * `aged` is the reconciler's: every mark of the approval has stood past - * {@link RECONCILER_AGE_BOUND_MS}, so a run that has not moved since will - * not move again. Then a run that reports paused while its pause is gone is - * read as stopped at its last step, and a run parked at a `subflow` or a - * `map` whose child run has ended (an item run that carries another - * record included), has no row or will not go on itself, as stopped at - * that node. + * {@link RECONCILER_AGE_BOUND_MS}. Then a run that reports paused while its + * pause is gone is read as stopped at its last step, and a run parked at a + * `subflow` or a `map` whose child run has ended (an item run that carries + * another record included), has no row or will not go on itself, as + * stopped at that node. + * + * Each of these, and each state that places the approval by the step last + * decided, is also what a run the engine is advancing reads as, and the + * bound is counted from the marks, not from the run's last movement. So a + * state stands only where the judgement before this one read it too, for + * the same run (S14 of delta review 7269135624; {@link stoodState}): the + * reading that meets a state first answers `undetermined`, or + * `in_progress` for a run parked on a child that has ended, and keeps the + * state. Every reading keeps the states it read, aged or not, in place of + * those kept before; a reading that reaches none keeps none. * * Every answer carries `kept`: the kept reading with what this reading * found ({@link runsReadAfter}), which the door writes on the latest @@ -5986,6 +6106,16 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const found = noRunsFound(); let between = prior.between && !(instantOf(prior.between.at) < lastOpened) ? prior.between : undefined; const kept = (): RunsRead => runsReadAfter(prior, found, between); + // [S14 of delta review 7269135624] A state that says a run has stopped + // stands only where the judgement before this one read it too, for the + // same run: the engine may be advancing the run, and then the state + // clears within that passage. Every such state this reading reads is + // kept for the next judgement, whatever this one answers. + const stoodBefore = new Set(prior.stood ?? []); + const stands = (state: string): boolean => { + found.stood.add(state); + return aged && stoodBefore.has(state); + }; const ownRunId = latest.flow_run_id != null ? String(latest.flow_run_id) : ''; const queue: ChildRunRef[] = [{ id: rootId, item: false, passed: false }]; @@ -5995,6 +6125,8 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const read = new Map(); /** The first run read whose step log is cut ({@link stepLogCut}). */ let cutLog: { runId: string; why: string } | undefined; + /** Every run read whose step log is cut. */ + const cutRuns: string[] = []; /** The first run this reading did not get to: the tree holds more runs than one judgement reads. */ let unread: string | undefined; while (queue.length > 0) { @@ -6009,7 +6141,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega continue; } const one = await this.readApprovalRun(runId, { - stamp, lastOpened, aged, item: next.item && !ownRuns.has(runId), latest, + stamp, lastOpened, aged, stands, item: next.item && !ownRuns.has(runId), latest, }); read.set(runId, one); if (one.answer === 'undetermined') return { answer: 'undetermined', why: one.why, runId, kept: kept() }; @@ -6026,7 +6158,10 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // A run whose log is cut names its children in part: they are read, // and it is never kept as ended ({@link keptAsEnded} wants its children). if (one.cut === undefined) found.childrenOf.set(runId, one.children.map((c) => c.id)); - else cutLog ??= { runId, why: one.cut }; + else { + cutLog ??= { runId, why: one.cut }; + cutRuns.push(runId); + } if (one.answer === 'read' && one.over) { found.terminal.add(runId); if (one.endedWhy !== undefined && !between) between = { why: one.endedWhy, at: one.endedAt ?? null }; @@ -6038,6 +6173,38 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega if (one.answer === 'waits') queue.unshift({ id: one.on, item: one.item, passed: false }); } + const missing = [...found.noRow].filter((id) => !passedWithNoRow(prior, found).has(id)); + let inProgress = false; + let endedWhy: string | undefined; + let parkedAtOwnNode: { runId: string; flow?: string } | undefined; + for (const [runId, one] of read) { + if (one.answer === 'in_progress') { + inProgress = true; + } else if (one.answer === 'own_node') { + parkedAtOwnNode = { runId, flow: one.flow }; + } else if (one.answer === 'read') { + endedWhy ??= one.endedWhy; + } else if (one.answer === 'waits') { + const says = this.waitingRun(runId, read, settled, stands); + // A child the reading did not get to says nothing of the run parked + // on it: in a tree that cannot be finished, it is not in progress. + if (says === 'moving' || (says === 'unread' && unread === undefined)) inProgress = true; + else if (typeof says !== 'string') endedWhy ??= says.why; + } + } + // The states that place the approval by the step last decided. Each is + // read here, before any answer, so that it is kept for the next + // judgement also where this one answers something else; and the + // approval is placed only where every one of them stood before + // ({@link stoodState}). + const placing = [ + ...(parkedAtOwnNode ? [stoodState('own_node', parkedAtOwnNode.runId)] : []), + ...cutRuns.map((id) => stoodState('cut', id)), + ...(unread !== undefined ? [stoodState('tree', rootId)] : []), + ...missing.map((id) => stoodState('no_row', id)), + ]; + const allStood = placing.map(stands).every(Boolean); + // [S11 of contract review 7266979193] A tree of more runs than one // judgement reads has an end. Within the age bound the next judgement // reads on. Past it, it reads on only where this reading kept a run the @@ -6057,25 +6224,6 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega } } - const missing = [...found.noRow].filter((id) => !passedWithNoRow(prior, found).has(id)); - let inProgress = false; - let endedWhy: string | undefined; - let parkedAtOwnNode: { runId: string; flow?: string } | undefined; - for (const [runId, one] of read) { - if (one.answer === 'in_progress') { - inProgress = true; - } else if (one.answer === 'own_node') { - parkedAtOwnNode = { runId, flow: one.flow }; - } else if (one.answer === 'read') { - endedWhy ??= one.endedWhy; - } else if (one.answer === 'waits') { - const says = this.waitingRun(runId, read, settled, aged); - // A child the reading did not get to says nothing of the run parked - // on it: in a tree that cannot be finished, it is not in progress. - if (says === 'moving' || (says === 'unread' && unread === undefined)) inProgress = true; - else if (typeof says !== 'string') endedWhy ??= says.why; - } - } if (inProgress) return { answer: 'in_progress', kept: kept() }; const notOpened = await this.laterStepNotOpenedOn(latest); if (notOpened) { @@ -6087,7 +6235,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega } const failed = endedWhy ?? between?.why; if (failed) return { answer: 'abandoned', why: failed, kept: kept() }; - if (parkedAtOwnNode || cutLog || unread !== undefined || missing.length > 0) { + if (placing.length > 0) { const what = parkedAtOwnNode ? `its run '${parkedAtOwnNode.runId}' is still parked at the step '${String(latest.flow_node_id ?? '')}' its decision was recorded on, so the run did not go on after it` : cutLog @@ -6095,12 +6243,19 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega : unread !== undefined ? `its runs number more than the ${MAX_RUNS_READ_PER_APPROVAL} one judgement reads, and this judgement kept no further run as read to its end, so its runs (the run '${unread}' among them) cannot all be read` : `its run '${missing[0]}' has no row the automation engine can read, and no run that was read went on past it, so where it stopped cannot be read`; + const runId = parkedAtOwnNode?.runId ?? cutLog?.runId ?? missing[0]; if (!aged) { return { - answer: 'undetermined', runId: parkedAtOwnNode?.runId ?? cutLog?.runId ?? missing[0], kept: kept(), + answer: 'undetermined', runId, kept: kept(), why: parkedAtOwnNode || !cutLog ? `${what}, and a process may still be moving it.` : `${what}; within the age bound nothing is concluded from it.`, }; } + if (!allStood) { + return { + answer: 'undetermined', runId, kept: kept(), + why: `${what}; the judgement before this one did not read the same, so a process may be moving it, and the next judgement places it if it still reads so.`, + }; + } return { answer: 'placed', why: `${what}; past the age bound it has stopped at that step.`, @@ -6136,9 +6291,10 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * * - `moving`: the child is in progress in its own right, is parked at a * pause that is not of the set, or carries another record and has not - * ended; or, within the age bound, the child has ended or has no row, - * and the engine may still be resuming the parent. The approval is in - * progress. + * ended; or the child has ended or has no row, and the engine may still + * be resuming the parent: within the age bound, and past it where the + * judgement before did not read the parent parked on that same child + * so ({@link stoodState}). The approval is in progress. * - `unread`: the reading did not get to the child, so the parent says * nothing. The caller reads it as moving, except in a tree of more runs * than one judgement reads ({@link readCarryingRun}). @@ -6146,17 +6302,17 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * its decision was recorded on, or a run that waits on that run in turn. * The parent says nothing of its own: the one rule places the approval * by that step (B2 on #37767), at whatever depth the step sits. - * - `{ why }`: past the age bound, the child has ended, has no row, or - * reports paused at a pause that is gone, so nothing will resume the - * parent, between two steps. An item run of a `map` that carries - * another record has ended once it is in a terminal status (S12 of - * contract review 7266979193). + * - `{ why }`: past the age bound, and as the judgement before read it, + * the child has ended, has no row, or reports paused at a pause that is + * gone, so nothing will resume the parent, between two steps. An item + * run of a `map` that carries another record has ended once it is in a + * terminal status (S12 of contract review 7266979193). */ private waitingRun( runId: string, read: ReadonlyMap, settled: ReadonlySet, - aged: boolean, + stands: (state: string) => boolean, above: ReadonlySet = new Set(), ): 'moving' | 'still' | 'unread' | { why: string } { const parent = read.get(runId); @@ -6165,14 +6321,17 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const stopped = (how: string) => ({ why: `its run '${runId}' is parked at '${parent.node}' on a child run that ${how}, so nothing will resume it, between two steps.`, }); - const ended = () => (aged ? stopped('has ended') : 'moving' as const); + // Between a child's end and the resume of the run parked on it, the + // engine has not claimed the parent's pause yet: the state stands only + // where the judgement before read it too ({@link stoodState}). + const ended = () => (stands(stoodState('on_ended', runId, parent.on)) ? stopped('has ended') : 'moving' as const); if (!child) return settled.has(parent.on) ? ended() : 'unread'; switch (child.answer) { case 'no_row': return ended(); case 'foreign': return child.over ? ended() : 'moving'; case 'own_node': return 'still'; case 'waits': { - const says = this.waitingRun(parent.on, read, settled, aged, new Set([...above, runId])); + const says = this.waitingRun(parent.on, read, settled, stands, new Set([...above, runId])); return typeof says === 'string' ? says : stopped('will not go on'); } case 'read': @@ -6194,7 +6353,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega */ private async readApprovalRun( runId: string, - at: { stamp: readonly StampedNode[]; lastOpened: number; aged: boolean; item: boolean; latest: any }, + at: { stamp: readonly StampedNode[]; lastOpened: number; aged: boolean; stands: (state: string) => boolean; item: boolean; latest: any }, ): Promise { const log: { cut?: string } = {}; const one = await this.placeApprovalRun(runId, at, log); @@ -6204,10 +6363,10 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega /** The body of {@link readApprovalRun}; `log.cut` is set where the run's step log is cut ({@link stepLogCut}). */ private async placeApprovalRun( runId: string, - at: { stamp: readonly StampedNode[]; lastOpened: number; aged: boolean; item: boolean; latest: any }, + at: { stamp: readonly StampedNode[]; lastOpened: number; aged: boolean; stands: (state: string) => boolean; item: boolean; latest: any }, log: { cut?: string }, ): Promise { - const { stamp, lastOpened, aged, item, latest } = at; + const { stamp, lastOpened, aged, stands, item, latest } = at; const automation = this.automation!; let run: { status?: string; flowName?: string; completedAt?: string; trigger?: { object?: string; recordId?: string }; steps?: unknown; @@ -6257,7 +6416,17 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega return { answer: 'undetermined', why: `where the run '${runId}' is parked could not be read (${err?.message ?? err}).` }; } if (!parked?.nodeId) { - if (!aged) return { answer: 'undetermined', why: `the run '${runId}' reports paused, and no pause of it can be found.` }; + // What a run the engine is advancing reads as, too: its pause is + // consumed, and it has not parked again or ended. It has stopped + // only where the judgement before read it so as well (S14). + if (!stands(stoodState('pause_gone', runId))) { + return { + answer: 'undetermined', + why: aged + ? `the run '${runId}' reports paused, and no pause of it can be found; the judgement before this one did not read the same, so a process may be resuming it, and the next judgement places it if it still reads so.` + : `the run '${runId}' reports paused, and no pause of it can be found.`, + }; + } const stop = stopOf(steps, 'failed'); const routed = routedFailure(stop); if (routed) return { answer: 'read', over: false, stopped: true, endedWhy: routedWhy(routed), children }; @@ -6330,9 +6499,11 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * {@link KEEP_RUNS_READ_ATTEMPTS} times. It can therefore not write a * stale snapshot over another writer's note, whenever that note lands. * - * Best-effort: a reading that is not kept leaves the runs to be read again. - * It answers whether `kept` is on the approval's rows now, which a - * judgement that relies on the next one reading on from it asks + * Best-effort: a reading that is not kept leaves the runs to be read + * again, and leaves the next judgement no state to stand on: past the age + * bound nothing is placed until a reading is kept ({@link stoodState}). It + * answers whether `kept` is on the approval's rows now, which a judgement + * that relies on the next one reading on from it asks * ({@link readCarryingRun}). */ private async keepRunsRead(latest: any, approval: readonly any[], kept: RunsRead | undefined): Promise { @@ -6656,12 +6827,12 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega }), }); } else if ('failure' in admins) { - this.logger?.warn?.('[approvals] could not read the organization\'s administrators to tell them a flow did not go on after its last step', { + this.logger?.warn?.('[approvals] could not read the organization\'s administrators to tell them a flow could not be seen through to its end after its last step', { request: latest.id, organizationId: org, error: admins.failure, }); } } catch (err: any) { - this.logger?.warn?.('[approvals] could not tell the organization\'s administrators that a flow did not go on after its last step', { + this.logger?.warn?.('[approvals] could not tell the organization\'s administrators that a flow could not be seen through to its end after its last step', { request: latest.id, error: err?.message ?? String(err), }); } @@ -12164,8 +12335,10 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * is abandoned, or, where nothing was held back, the mark is cleared and * nothing is written. It places what the door does not see: a run that was * cancelled, a parent run that is gone. Once every mark of an approval has - * stood past {@link RECONCILER_AGE_BOUND_MS}, it also places a run that - * will not move again (rulings A3 and B2 on #37767): a run that reports + * stood past {@link RECONCILER_AGE_BOUND_MS}, it also places a run that two + * passes in a row read in the same of these states, the first of which + * may be a pass within the bound or a door (rulings A3 and B2 on #37767; + * S14 of delta review 7269135624, {@link stoodState}): a run that reports * paused while its pause is gone, a run parked at a `subflow` or a `map` * whose child run has ended or has no row (an item run of a `map` that * carries another record included, once it is in a terminal status), and, @@ -12178,7 +12351,8 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * step last decided. Where a step can follow it, the approval is abandoned (and * a run still parked there is cancelled, with the runs that wait on it); * where none can, the outcome is written and, once it has landed, the - * administrators are told that the flow did not go on after its last step. + * administrators are told that the flow could not be seen through to its + * end after its last step. * * What each judgement reads of the runs is kept on the approval's latest * request ({@link RunsRead}), so a pass reads on from where the last one From e29d0977d51039611db55c99e2e163f78c523eaa Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 05:26:49 +0000 Subject: [PATCH 21/23] fix(approvals): the title of the administrators' notice says what its body says, in the 11 packs (ADR-0162 item 8) N28 of delta review 7269135624. The body of the notice on `approval.flow_not_continued` says the flow could not be seen through to its end; the title still said it did not go on, which is not what the plugin knows of a cut log or a tree too large to read. The title now says the same as the body in every locale pack. The key and its variables are unchanged. Claude-Session: https://claude.ai/code/session_01JQwxbaoxpe1tyHuqnsAUFB Co-authored-by: Claude --- .../src/translations/messages.ts | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/packages/plugins/plugin-approvals/src/translations/messages.ts b/packages/plugins/plugin-approvals/src/translations/messages.ts index 1512127a7ea..5f995e5dcd9 100644 --- a/packages/plugins/plugin-approvals/src/translations/messages.ts +++ b/packages/plugins/plugin-approvals/src/translations/messages.ts @@ -155,7 +155,7 @@ const enSentences = { approvalAutoRejectedBody: 'Your {{object}} {{record}} exceeded the revision limit ({{limit}}) and was rejected.', approvalAbandonedTitle: 'Approval did not finish', approvalAbandonedBody: 'The approval of your {{object}} {{record}} stopped between two of its steps, so it did not finish and the record was put back to an open status. Submit it again when it is ready.', - approvalFlowNotContinuedTitle: 'Approval flow did not go on', + approvalFlowNotContinuedTitle: 'Approval flow could not be seen through to its end', approvalFlowNotContinuedBody: 'The approval of {{object}} {{record}} was decided at its last step and the decision was written, but its flow could not be seen through to its end after that step, so the steps that follow it may not have run. Check the approval\'s flow run: where it is still paused, continue or cancel it; where it has ended or no run is left, check that the steps after the decision were done.', approvalReturnedTitle: 'Sent back for revision', approvalReturnedBody: 'Your {{object}} {{record}} needs rework before it can be approved.', @@ -307,7 +307,7 @@ export const zhCNMessages: ApprovalMessages = { approvalAutoRejectedBody: '您的{{object}} {{record}} 已超过退回修改次数上限({{limit}}),已被驳回。', approvalAbandonedTitle: '审批未能完成', approvalAbandonedBody: '您的{{object}} {{record}} 的审批在两个步骤之间停止,未能完成,记录已恢复为未关闭的状态。准备好后请重新提交。', - approvalFlowNotContinuedTitle: '审批流程未继续', + approvalFlowNotContinuedTitle: '无法确认审批流程已执行到结束', approvalFlowNotContinuedBody: '{{object}} {{record}} 的审批已在最后一步作出决定,决定也已写入,但无法确认其流程在该步之后已执行到结束,之后的步骤可能没有执行。请检查该审批的流程运行:若仍处于暂停,请继续或取消它;若运行已结束或已无运行记录,请核对该决定之后的步骤是否已完成。', approvalReturnedTitle: '已退回修改', approvalReturnedBody: '您的{{object}} {{record}} 需要修改后才能获批。', @@ -396,7 +396,7 @@ export const jaJPMessages: ApprovalMessages = { approvalAutoRejectedBody: 'あなたの{{object}} {{record}} は差し戻し回数の上限({{limit}})を超えたため却下されました。', approvalAbandonedTitle: '承認が完了しませんでした', approvalAbandonedBody: 'あなたの{{object}} {{record}} の承認は 2 つのステップの間で停止したため完了せず、レコードは閉じていないステータスに戻されました。準備ができたら再度申請してください。', - approvalFlowNotContinuedTitle: '承認フローが続行されませんでした', + approvalFlowNotContinuedTitle: '承認フローが最後まで実行されたか確認できません', approvalFlowNotContinuedBody: '{{object}} {{record}} の承認は最後のステップで決定され、その決定は書き込まれましたが、フローがそのステップの後に最後まで実行されたことを確認できないため、後続のステップが実行されていない可能性があります。承認のフロー実行を確認してください。まだ一時停止中であれば続行またはキャンセルし、実行が終了しているか残っていなければ、決定の後のステップが行われたかを確認してください。', approvalReturnedTitle: '修正のため差し戻されました', approvalReturnedBody: 'あなたの{{object}} {{record}} は、承認を受ける前に修正が必要です。', @@ -485,7 +485,7 @@ export const esESMessages: ApprovalMessages = { approvalAutoRejectedBody: 'Su {{object}} {{record}} superó el límite de revisiones ({{limit}}) y se ha rechazado.', approvalAbandonedTitle: 'La aprobación no terminó', approvalAbandonedBody: 'La aprobación de su {{object}} {{record}} se detuvo entre dos de sus pasos, así que no terminó y el registro volvió a un estado abierto. Envíelo de nuevo cuando esté listo.', - approvalFlowNotContinuedTitle: 'El flujo de la aprobación no continuó', + approvalFlowNotContinuedTitle: 'No se pudo comprobar que el flujo de la aprobación llegara al final', approvalFlowNotContinuedBody: 'La aprobación de {{object}} {{record}} se decidió en su último paso y la decisión se escribió, pero no se pudo comprobar que su flujo continuara hasta el final después de ese paso, así que es posible que los pasos siguientes no se hayan ejecutado. Revise la ejecución del flujo de la aprobación: si sigue en pausa, continúela o cancélela; si ya terminó o no queda ninguna ejecución, compruebe que se hicieron los pasos posteriores a la decisión.', approvalReturnedTitle: 'Devuelto para revisión', approvalReturnedBody: 'Su {{object}} {{record}} necesita cambios antes de poder aprobarse.', @@ -574,7 +574,7 @@ export const zhHantMessages: ApprovalMessages = { approvalAutoRejectedBody: '你的{{object}} {{record}} 已超過退回修改次數上限({{limit}}),因此被駁回。', approvalAbandonedTitle: '核准未能完成', approvalAbandonedBody: '你的{{object}} {{record}} 的核准在兩個步驟之間停止,未能完成,記錄已恢復為未關閉的狀態。準備好後請重新送出。', - approvalFlowNotContinuedTitle: '核准流程未繼續', + approvalFlowNotContinuedTitle: '無法確認核准流程已執行到結束', approvalFlowNotContinuedBody: '{{object}} {{record}} 的核准已在最後一步作出決定,決定也已寫入,但無法確認其流程在該步之後已執行到結束,之後的步驟可能沒有執行。請檢查該核准的流程執行:若仍處於暫停,請繼續或取消它;若執行已結束或已無執行記錄,請核對該決定之後的步驟是否已完成。', approvalReturnedTitle: '已退回修改', approvalReturnedBody: '你的{{object}} {{record}} 需要修改後才能獲得核准。', @@ -663,7 +663,7 @@ export const arMessages: ApprovalMessages = { approvalAutoRejectedBody: 'تجاوز طلبك بشأن {{object}} {{record}} حد المراجعات ({{limit}}) فرُفض.', approvalAbandonedTitle: 'لم تكتمل الموافقة', approvalAbandonedBody: 'توقفت الموافقة على {{object}} {{record}} بين خطوتين من خطواتها، فلم تكتمل وأُعيد السجل إلى حالة مفتوحة. أعد إرساله عندما يكون جاهزًا.', - approvalFlowNotContinuedTitle: 'لم يستمر مسار الموافقة', + approvalFlowNotContinuedTitle: 'تعذّر التأكد من أن مسار الموافقة استمر حتى نهايته', approvalFlowNotContinuedBody: 'تم البت في الموافقة على {{object}} {{record}} في خطوتها الأخيرة وكُتب القرار، لكن تعذّر التأكد من أن مسارها استمر حتى نهايته بعد تلك الخطوة، لذا ربما لم تُنفَّذ الخطوات التي تليها. راجع تشغيل مسار الموافقة: إن كان لا يزال متوقفًا مؤقتًا فتابعه أو ألغِه، وإن كان قد انتهى أو لم يبقَ له تشغيل فتحقّق من أن الخطوات التي تلي القرار قد نُفّذت.', approvalReturnedTitle: 'أُعيد للمراجعة', approvalReturnedBody: 'يحتاج طلبك بشأن {{object}} {{record}} إلى تعديل قبل أن تمكن الموافقة عليه.', @@ -752,7 +752,7 @@ export const frMessages: ApprovalMessages = { approvalAutoRejectedBody: 'Votre demande sur {{object}} {{record}} a dépassé la limite de révisions ({{limit}}) et a été rejetée.', approvalAbandonedTitle: 'L’approbation n’a pas abouti', approvalAbandonedBody: 'L’approbation de votre {{object}} {{record}} s’est arrêtée entre deux de ses étapes : elle n’a pas abouti et l’enregistrement est revenu à un statut ouvert. Soumettez-le à nouveau lorsqu’il est prêt.', - approvalFlowNotContinuedTitle: 'Le flux de l’approbation n’a pas continué', + approvalFlowNotContinuedTitle: 'Le flux de l’approbation n’a pas pu être vérifié jusqu’à son terme', approvalFlowNotContinuedBody: 'L’approbation de {{object}} {{record}} a été décidée à sa dernière étape et la décision a été écrite, mais il n’a pas pu être vérifié que son flux s’est poursuivi jusqu’à son terme après cette étape : les étapes suivantes n’ont peut-être pas été exécutées. Vérifiez l’exécution du flux de l’approbation : si elle est encore en pause, poursuivez-la ou annulez-la ; si elle est terminée ou s’il n’en reste aucune, vérifiez que les étapes qui suivent la décision ont été faites.', approvalReturnedTitle: 'Renvoyé pour révision', approvalReturnedBody: 'Votre demande sur {{object}} {{record}} doit être retravaillée avant de pouvoir être approuvée.', @@ -841,7 +841,7 @@ export const ptBRMessages: ApprovalMessages = { approvalAutoRejectedBody: 'Sua solicitação sobre {{object}} {{record}} excedeu o limite de revisões ({{limit}}) e foi rejeitada.', approvalAbandonedTitle: 'A aprovação não foi concluída', approvalAbandonedBody: 'A aprovação de {{object}} {{record}} parou entre duas de suas etapas, por isso não foi concluída e o registro voltou a um status aberto. Envie-o novamente quando estiver pronto.', - approvalFlowNotContinuedTitle: 'O fluxo da aprovação não continuou', + approvalFlowNotContinuedTitle: 'Não foi possível confirmar que o fluxo da aprovação foi até o fim', approvalFlowNotContinuedBody: 'A aprovação de {{object}} {{record}} foi decidida em sua última etapa e a decisão foi gravada, mas não foi possível confirmar que o fluxo continuou até o fim depois dessa etapa, então as etapas seguintes podem não ter sido executadas. Verifique a execução do fluxo da aprovação: se ainda estiver pausada, continue-a ou cancele-a; se já tiver terminado ou não restar nenhuma execução, confira se as etapas após a decisão foram feitas.', approvalReturnedTitle: 'Devolvido para revisão', approvalReturnedBody: 'Sua solicitação sobre {{object}} {{record}} precisa de ajustes antes de poder ser aprovada.', @@ -930,7 +930,7 @@ export const ruMessages: ApprovalMessages = { approvalAutoRejectedBody: 'Ваш запрос по {{object}} {{record}} превысил лимит доработок ({{limit}}) и был отклонён.', approvalAbandonedTitle: 'Согласование не завершено', approvalAbandonedBody: 'Согласование {{object}} {{record}} остановилось между двумя шагами, поэтому не завершилось, и запись возвращена в открытый статус. Отправьте её снова, когда она будет готова.', - approvalFlowNotContinuedTitle: 'Процесс согласования не продолжился', + approvalFlowNotContinuedTitle: 'Не удалось убедиться, что процесс согласования дошёл до конца', approvalFlowNotContinuedBody: 'Согласование {{object}} {{record}} было решено на последнем шаге, и решение записано, но не удалось убедиться, что процесс после этого шага дошёл до конца, поэтому следующие шаги могли не выполниться. Проверьте запуск процесса согласования: если он ещё приостановлен, продолжите или отмените его; если он завершился или запуска уже нет, проверьте, что шаги после решения выполнены.', approvalReturnedTitle: 'Возвращено на доработку', approvalReturnedBody: 'Ваш запрос по {{object}} {{record}} нужно доработать, прежде чем его можно будет одобрить.', @@ -1019,7 +1019,7 @@ export const deMessages: ApprovalMessages = { approvalAutoRejectedBody: 'Ihre Anfrage zu {{object}} {{record}} hat das Überarbeitungslimit ({{limit}}) überschritten und wurde abgelehnt.', approvalAbandonedTitle: 'Genehmigung nicht abgeschlossen', approvalAbandonedBody: 'Die Genehmigung zu {{object}} {{record}} hat zwischen zwei ihrer Schritte angehalten. Sie wurde nicht abgeschlossen, und der Datensatz wurde auf einen offenen Status zurückgesetzt. Reichen Sie ihn erneut ein, wenn er bereit ist.', - approvalFlowNotContinuedTitle: 'Der Ablauf der Genehmigung wurde nicht fortgesetzt', + approvalFlowNotContinuedTitle: 'Der Ablauf der Genehmigung ließ sich nicht bis zum Ende nachvollziehen', approvalFlowNotContinuedBody: 'Die Genehmigung zu {{object}} {{record}} wurde in ihrem letzten Schritt entschieden und die Entscheidung geschrieben, aber es ließ sich nicht feststellen, dass ihr Ablauf nach diesem Schritt bis zum Ende fortgesetzt wurde, sodass die folgenden Schritte möglicherweise nicht ausgeführt wurden. Prüfen Sie den Ablauf der Genehmigung: Ist er noch pausiert, setzen Sie ihn fort oder brechen Sie ihn ab; ist er beendet oder kein Lauf mehr vorhanden, prüfen Sie, ob die Schritte nach der Entscheidung erledigt wurden.', approvalReturnedTitle: 'Zur Überarbeitung zurückgesendet', approvalReturnedBody: 'Ihre Anfrage zu {{object}} {{record}} muss überarbeitet werden, bevor sie genehmigt werden kann.', @@ -1108,7 +1108,7 @@ export const koMessages: ApprovalMessages = { approvalAutoRejectedBody: '{{object}} {{record}}이(가) 수정 횟수 한도({{limit}})를 넘어 반려되었습니다.', approvalAbandonedTitle: '승인이 완료되지 않았습니다', approvalAbandonedBody: '{{object}} {{record}}의 승인이 두 단계 사이에서 멈춰 완료되지 않았고, 레코드는 열린 상태로 되돌아갔습니다. 준비가 되면 다시 제출하세요.', - approvalFlowNotContinuedTitle: '승인 흐름이 계속되지 않았습니다', + approvalFlowNotContinuedTitle: '승인 흐름이 끝까지 진행되었는지 확인할 수 없습니다', approvalFlowNotContinuedBody: '{{object}} {{record}}의 승인은 마지막 단계에서 결정되었고 결정도 기록되었지만, 그 단계 이후 흐름이 끝까지 진행되었는지 확인할 수 없어 이후 단계가 실행되지 않았을 수 있습니다. 승인의 흐름 실행을 확인하세요. 아직 일시 중지되어 있으면 계속하거나 취소하고, 실행이 끝났거나 남은 실행이 없으면 결정 이후의 단계가 수행되었는지 확인하세요.', approvalReturnedTitle: '수정 요청됨', approvalReturnedBody: '{{object}} {{record}}을(를) 승인받으려면 먼저 수정해야 합니다.', From 3c80901761c8cd2c8d56b4bc79a31d879a646734 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 05:26:49 +0000 Subject: [PATCH 22/23] docs(approvals): the bound places on two readings in a row, and the two costs of reading on are stated (ADR-0162 item 8) The changeset and the approvals guide say what the tree does after S14 of delta review 7269135624: past the hour a run is placed once two judgements in a row read it in the same state, why (the hour is counted from the marks, and a run the engine is resuming reads as paused with its pause gone or with no row), and what it costs (one pass more where the judgement before did not read the same). They also state the two costs the seat accepted with the rule for a tree of more runs than one judgement reads (L1 7269166540; N26 and N27 of that review): a tree of about 399 runs can be one no judgement finishes, and it is placed without being finished; and an approval submitted again on the same flow can meet the same end. Reading on can take up to 200 further passes of the sweep clock. The sentence on a run another process is advancing now names the statuses it is about, which the engine reports for no flow run today. Claude-Session: https://claude.ai/code/session_01JQwxbaoxpe1tyHuqnsAUFB Co-authored-by: Claude --- .changeset/37767-reconciler.md | 8 ++++---- content/docs/automation/approvals.mdx | 27 ++++++++++++++++++++++----- 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/.changeset/37767-reconciler.md b/.changeset/37767-reconciler.md index 8d57563d33b..395e4029a2b 100644 --- a/.changeset/37767-reconciler.md +++ b/.changeset/37767-reconciler.md @@ -12,14 +12,14 @@ Widened: `ApprovalService` gains `reconcileMarkedApprovals(options?)`, which the Only for an approval the check stamped when it opened (one with a step that can act on an object that declares `closedStates`): -- **The door reads every run of the approval.** Where it read the run that carries the record and the latest request's own run, it now walks the tree from the run that carries the record, following the child runs each delegating step records: every `subflow` child, and every `map` item run that does not carry another record (an item that is a record carries an approval of its own). It reads the whole tree before it answers, and one run decides for the whole approval: one that another process is advancing, or that the store could not answer for, makes it cannot tell; otherwise one parked at a node a step can follow, in progress; otherwise one that ended between two steps, abandoned. A run parked at such a node on a child run says what its child says, so the walk reads the child, at any depth. So a sibling child whose failure the flow routed, a middle run two levels down that failed, an item run that failed before its step, and a run between two others that is being advanced are no longer read as finished. A failure routed to a pause no step follows is read as abandoned, as on the base. A stop is answered where a request of the approval opened after it. One judgement reads at most 200 runs beside those it kept as ended: past them it is cannot tell, keeps what it read, and the next judgement reads on. That has an end: once the approval's marks have stood for the hour of the age bound, a judgement reads on only while it keeps a run the approval had not kept (the kept list holds 200 runs), and the judgement that keeps none places the approval by the step last decided, below. A run parked on a child run that such a judgement did not get to says nothing of its own, and the child a parked run waits on is read next, before the runs beside it. -- **The plugin keeps what it read.** At every door, one that leaves the next request pending included, and as each request opens, the approval's latest request keeps, in its config snapshot (`__runsRead`): the runs that are not read again (`ended`), the runs read to their end over a child run that was not (`open`), and a failure between two steps found in a run that ended. A run is kept as ended only once it was read to an end and every child run its steps name is kept as ended too. So a child whose read failed, a child with no row, and the runs past the 200 one judgement reads are read on the next pass, which starts from the open runs as well. A run that a stored step names and that a pass did not read is never left out without a word: it is read on a later pass, it counts as passed by the rule below, or the approval is cannot tell and then placed. A run that no stored step names any more is not covered by that: see the limit of this release, below. A run the plugin read before the automation engine trimmed its history is not needed again, so an approval whose refused outcome is tried again after its run's history went is judged as it would have been. +- **The door reads every run of the approval.** Where it read the run that carries the record and the latest request's own run, it now walks the tree from the run that carries the record, following the child runs each delegating step records: every `subflow` child, and every `map` item run that does not carry another record (an item that is a record carries an approval of its own). It reads the whole tree before it answers, and one run decides for the whole approval: one that the store could not answer for, or that reports a status of a run in motion (`pending`, `running`, `retrying`), makes it cannot tell; otherwise one parked at a node a step can follow, in progress; otherwise one that ended between two steps, abandoned. A run parked at such a node on a child run says what its child says, so the walk reads the child, at any depth. The automation engine reports none of those three statuses for a flow run today: a run it is advancing reads as paused with its pause gone, or as a run with no row, and is held by the rule for a run that stopped, below. So a sibling child whose failure the flow routed, a middle run two levels down that failed, an item run that failed before its step, and a run between two others that is being advanced are no longer read as finished. A failure routed to a pause no step follows is read as abandoned, as on the base. A stop is answered where a request of the approval opened after it. One judgement reads at most 200 runs beside those it kept as ended: past them it is cannot tell, keeps what it read, and the next judgement reads on. That has an end: once the approval's marks have stood for the hour of the age bound, a judgement reads on only while it keeps a run the approval had not kept (the kept list holds 200 runs), and the judgement that keeps none places the approval by the step last decided, below. Two costs come with that rule. A tree the judgements cannot finish is placed without being finished, and from about 399 runs a tree can be one no judgement finishes: the walk reads the runs it starts from before the runs below them, so for a `map` of 199 items that each call a `subflow`, every judgement reads the run and its 199 items and none of the runs below them. And the placement follows from the shape of the flow, so an approval submitted again on the same flow can meet the same end: the remedy is the flow's, not the submitter's. Reading on can take up to 200 further passes of the sweep clock (5 minutes) after the hour. A run parked on a child run that such a judgement did not get to says nothing of its own, and the child a parked run waits on is read next, before the runs beside it. +- **The plugin keeps what it read.** At every door, one that leaves the next request pending included, and as each request opens, the approval's latest request keeps, in its config snapshot (`__runsRead`): the runs that are not read again (`ended`), the runs read to their end over a child run that was not (`open`), a failure between two steps found in a run that ended, and the states the last judgement read that say a run has stopped (`stood`), which the rule for a run that stopped uses, below. A run is kept as ended only once it was read to an end and every child run its steps name is kept as ended too. So a child whose read failed, a child with no row, and the runs past the 200 one judgement reads are read on the next pass, which starts from the open runs as well. A run that a stored step names and that a pass did not read is never left out without a word: it is read on a later pass, it counts as passed by the rule below, or the approval is cannot tell and then placed. A run that no stored step names any more is not covered by that: see the limit of this release, below. A run the plugin read before the automation engine trimmed its history is not needed again, so an approval whose refused outcome is tried again after its run's history went is judged as it would have been. - **A run with no row, under a run that went on past it, is passed.** A run the engine has no row for counts as passed, and is kept as ended, where a run the plugin read went on past the step that names it: that step succeeded, and the run reached an end of its flow, or logged a later step and is not parked at that step. So an early child run trimmed before the plugin read it does not hold the approval back. A step that failed is never passed, also where the flow routed the failure and went on. A run the plugin had read to its end over an unread child, and whose own row is gone since, is not passed either: nothing names that child any more. - **A step log the engine marked, or the history row cut, is cannot tell.** Two logs are read as cut, and are not judged from as they stand: one with a step that carries the engine's mark `childRunIdsTruncated` (its execution started more child runs than the 200 a step names, or the history row shed the step's list to fit its size), and the log of a run that ended whose history row keeps fewer steps than the run logged (the row bounds the log by bytes, to a tail of it or to none, while the run's summary still counts every step). Within the age bound nothing is written; past it the approval is placed by the step last decided, as for a run with no row, below. A run whose log is cut is not kept as ended, the child runs it does name are still read, and it speaks for none of them: no run it names counts as passed. A summary that is absent or dropped its per-node detail gives nothing to compare, and reads as cut. - **The limit of this release: a log that loses whole steps carries no mark (ruling 7268216330 on #37767).** The engine marks one thing: a step whose child-run links were shed carries `childRunIdsTruncated`, above. A log that loses whole steps carries no mark, whichever way it loses them: the engine's compaction of a log of more than 200 steps, the history row's halving of a log over its 64 KB cap, a row stored as null. The plugin reads what the log kept, and a child run named only by a dropped step reads as one the run went past: it is not read. For a halved row and a null row the plugin can still tell that steps are missing, from the run's summary, which counts every step: that is the second log read as cut, above, and the approval is held and then placed. For a compacted log it cannot tell. A run that logged more than 200 steps is stored with 200 of them: every top-level step and every failed step, then the most recent of the rest (the most recent 200 of the top-level and failed steps, where those alone pass 200), and it is judged from those, as before this change. What an operator gets in that case: a `subflow` or `map` step the compaction dropped (one that succeeded inside a `loop`, `parallel` or `try_catch` region, or an early step of a very long run) no longer names the child runs it started; a failure the flow routed inside such a child run, between two steps, is not seen; and the approval can be written as finished, with no notice and no line in the log. A process that still holds the run in memory reads its whole log, so this is a judgement made once that process is gone. No approval is judged worse than before this change, whose door read no child run. - **The kept reading is its own key.** It is written onto the snapshot read again just before the write, and only while the column still reads the same, at most three times. It cannot write a stale snapshot over a note another writer left there (`__laterStepNotOpened`, `__strandedContinuation`). The judgement reads the note that a later step could not open once it has read the runs, so a note that lands while they are read is judged with. -- **A run that stopped, placed by the step last decided.** A run the engine has no row for and that no run the plugin read speaks for (its history is gone, or a process stopped while advancing it), a run whose step log is cut, above, a tree of more runs than the judgements can read in full, above, and the latest request's own run still parked at the step its decision was recorded on (a process stopped before the run was resumed), in the run that carries the record or in a child run any number of levels below it, are cannot tell for an hour from the approval's marks (the age bound). Past it, they have stopped at the step last decided. Whether a later step can follow that step is asked in the flow its request records, so a node of another flow that carries the step's id does not answer for it. Where one can, the approval is abandoned: the record is put back, the submitter is told and submits again, the decisions already made stay on their requests, and a run still parked there is cancelled, with the runs that wait on it up to the run that carries the record, through a `map` whose items are not records as through a `subflow`. The cancel follows the put-back, and is not tried again once the put-back has landed: where it fails, or the process stops between the two, the run stays parked, the approval stays abandoned, and the door that continues a restored run refuses it. At the last step, the outcome is written and, once that write has landed, the administrators are told that the flow did not go on after that step; the run's pause is left for an operator. A refused write sends no such notice, and the pass on which the write lands sends it. The notice says what to do in each case: continue or cancel a run that is still paused, and where the run has ended or no run is left, check that the steps after the decision were done. An approval placed for a cut log or a tree too large to read can be one whose flow did go on, which the plugin could not read in full: at its last step the administrators get the notice for a flow that ran, and where a later step can follow, the submitter submits again. -- **The reconciler.** Each pass reads two windows of at most 200 marked requests (`unjudged_since`): the oldest marks, and the next page of a walk over every marked request by id, so that marks which stay cannot keep the newer ones from being read. It judges each approval among them once, as the door would have: it writes the outcome in the name of the request's recorded decider, abandons the approval, or, where nothing was held back, clears the mark and writes nothing (where it concluded that a run had stopped, a line in the log says so). It ends what no door saw: a run that was cancelled, a parent run cancelled while its child's request was pending, and the stopped runs above. Past the age bound it also reads as stopped where it stood a run that reports paused while its pause is gone, and a run parked at a `subflow` or a `map` whose child run has ended or has no row. The item run of a `map` whose items are records is such a child once it is in a terminal status: its steps are an approval of the item's own record and are not read, only whether it has ended, and it is kept as ended only once it has. +- **A run that stopped, placed by the step last decided.** A run the engine has no row for and that no run the plugin read speaks for (its history is gone, or a process stopped while advancing it), a run whose step log is cut, above, a tree of more runs than the judgements can read in full, above, and the latest request's own run still parked at the step its decision was recorded on (a process stopped before the run was resumed), in the run that carries the record or in a child run any number of levels below it, are cannot tell for an hour from the approval's marks (the age bound). Past it, each has stopped at the step last decided once two judgements in a row read it in the same state, for the same run. The hour is counted from the marks and not from the run's last movement, and a run the engine is resuming reads as paused with its pause gone or as a run with no row; so an approval whose flow waits longer than the hour between two steps by design (a `wait` node, a batch over records whose items are approved one by one, a child run parked outside the approval's steps) is past the bound whenever it resumes. The judgement that reads a run in such a state first therefore does not place it (it cannot tell, and a run parked on a child that has ended is in progress), and keeps the state it read (`stood` in `__runsRead`); the next judgement places the run if it reads the same, and reads it anew if it does not. A judgement within the hour keeps what it read as well, a door's included, so an approval read in that state within the hour is placed by the first pass past it, and one that was not takes one pass more. A reading that could not be kept leaves the next judgement nothing to stand on. Two passes that each fall inside a resume of the same run still read it as stopped. Whether a later step can follow that step is asked in the flow its request records, so a node of another flow that carries the step's id does not answer for it. Where one can, the approval is abandoned: the record is put back, the submitter is told and submits again, the decisions already made stay on their requests, and a run still parked there is cancelled, with the runs that wait on it up to the run that carries the record, through a `map` whose items are not records as through a `subflow`. The cancel follows the put-back, and is not tried again once the put-back has landed: where it fails, or the process stops between the two, the run stays parked, the approval stays abandoned, and the door that continues a restored run refuses it. At the last step, the outcome is written and, once that write has landed, the administrators are told that the flow could not be seen through to its end after that step; the run's pause is left for an operator. A refused write sends no such notice, and the pass on which the write lands sends it. The notice says what to do in each case: continue or cancel a run that is still paused, and where the run has ended or no run is left, check that the steps after the decision were done. An approval placed for a cut log or a tree too large to read can be one whose flow did go on, which the plugin could not read in full: at its last step the administrators get the notice for a flow that ran, and where a later step can follow, the submitter submits again. +- **The reconciler.** Each pass reads two windows of at most 200 marked requests (`unjudged_since`): the oldest marks, and the next page of a walk over every marked request by id, so that marks which stay cannot keep the newer ones from being read. It judges each approval among them once, as the door would have: it writes the outcome in the name of the request's recorded decider, abandons the approval, or, where nothing was held back, clears the mark and writes nothing (where it concluded that a run had stopped, a line in the log says so). It ends what no door saw: a run that was cancelled, a parent run cancelled while its child's request was pending, and the stopped runs above. Past the age bound it also reads as stopped where it stood a run that reports paused while its pause is gone, and a run parked at a `subflow` or a `map` whose child run has ended or has no row, each once two judgements in a row read it so, as above. The item run of a `map` whose items are records is such a child once it is in a terminal status: its steps are an approval of the item's own record and are not read, only whether it has ended, and it is kept as ended only once it has. - **A refused write is tried again.** A refused outcome or put-back leaves the marks, and the next pass tries it again. The timeline line and the administrators' notice (keyed per request and status) are left once for one refusal; the same holds for the line an abandoned approval leaves. - **A deleted record.** Where the approval's record was deleted, the reconciler clears the marks of its requests and writes nothing: no retry and no notice. - **The stranded-request report** (`inspectStrandedRequests`) leaves a decided request the check stamped to the door and the reconciler, and still reports a returned one. diff --git a/content/docs/automation/approvals.mdx b/content/docs/automation/approvals.mdx index dd2ad7ab885..c7a8061867a 100644 --- a/content/docs/automation/approvals.mdx +++ b/content/docs/automation/approvals.mdx @@ -1672,7 +1672,14 @@ not read again; a larger tree cannot tell on that reading and is read on at the next. That has an end: once the approval's marks have stood for an hour, the platform reads on only while a reading adds to the runs it does not read again (it keeps at most 200 of them), and the reading that adds none places the -approval by the step last decided, below. +approval by the step last decided, below. Two costs come with that. An approval +whose runs the platform cannot finish reading is placed without having been +read to its end, and that can begin at about 399 runs: for a `map` step of 199 +items that each call a `subflow`, every reading takes the run and its 199 item +runs, and never the runs below them. And the cause is the shape of the flow, so +the same approval submitted again can meet the same end: give one approval +fewer runs to read, because submitting again does not help. Reading on can take +up to 200 further sweeps, five minutes apart, after the hour. The platform trims every flow's run history in time. A run it read before that is not needed again. A run it never read counts as passed where the history of @@ -1691,7 +1698,16 @@ can read in full, above; and a decided request whose run is still parked at that request's own step (a process stopped before the run was resumed), in the run that carries the record or in a `subflow` or `map` run below it. An hour after the approval's marks -were set, each has stopped at the step last decided. Where a later step could +were set, each has stopped at the step last decided, once two checks in a row +find it in the same state. The hour is counted from the marks, not from when +the run last moved, and a run the platform is resuming at that moment looks +like one a stopped process left: a run with no history to read, or a paused run +with nothing to resume it. An approval that waits longer than an hour between +two steps by design (a `wait` node, a batch of records approved one by one) is +past the hour whenever it resumes. So the check that first finds a run in such +a state only notes it, and the next check places the run if it finds the same. +A check made within the hour counts as the first, so this adds a sweep (five +minutes) only where the check before did not find the same. Where a later step could follow that step, the approval is abandoned, above, and a run still parked there is cancelled, with the runs that wait on it, so nothing resumes it; the decisions already made stay on their requests, and the submitter submits again. @@ -1699,8 +1715,8 @@ The cancel is not tried again once the record is put back: where it fails, the run stays parked, the approval stays abandoned, and continuing that run is refused. Where the step was the last, its decision is written and, once it is on the record, the organization's -administrators are told that the flow did not go on after that step (the notice -`approval.flow_not_continued`). The run's pause is left: where the run is still +administrators are told that the flow could not be seen through to its end +after that step (the notice `approval.flow_not_continued`). The run's pause is left: where the run is still paused, an operator can continue the flow's remaining nodes or cancel the run; where it has ended or no run is left, check that the steps after the decision were done. A write that a rule or a hook refuses sends no such notice; the @@ -1739,7 +1755,8 @@ next page of a walk over every marked request, so that approvals that stay in progress do not keep the newer ones from being judged. Once the mark has stood for an hour, it also reads as stopped where it stood a run that reports paused while its pause is gone, and a run parked at a `subflow` or a `map` whose child -run has ended or has no history left. That holds for a `map` over records too: +run has ended or has no history left, each once two sweeps in a row find it +so. That holds for a `map` over records too: the platform does not read such an item run's steps, which belong to the item's own approval, only whether the run has ended. Where nothing was held back it clears the mark and writes nothing; where it From b0480581866a0e4a9c42253445eed0715729e12a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 06:30:23 +0000 Subject: [PATCH 23/23] docs(approvals): a reading that is never kept holds an approval with no end, and the waits by design are scoped (ADR-0162 item 8) Prose only: two docblocks, the changeset and the approvals guide. No code line changes; `approval-service.ts` transpiled with its comments removed is byte-identical before and after. N29 of delta review 7270552441. Three sentences said more than the tree does. A reading that is not kept leaves on the request the reading kept before it, so the next judgement stands on that earlier one: a state kept earlier can still count, and where none was kept nothing is placed. An approval whose reading is never kept is therefore held with no end. The changeset and the docblocks of `keepRunsRead` and `reconcileMarkedApprovals` now say so; the second no longer says that none of the held states is without an end. N31 of the same review. A `wait` node and a batch of records approved one by one were given as approvals that wait between two steps by design, with no word that the opening check refuses both for an approval on a field its object closes on. The guide, the changeset and the docblock of `RECONCILER_AGE_BOUND_MS` now scope them to an approval that holds nothing back, where a placement ends the hold and writes nothing. Five minutes is named as the default sweep interval (`escalationScanIntervalMs`), and the visit more as one sweep, or one turn of the reconciler's walk where more requests are marked than one sweep reads. Claude-Session: https://claude.ai/code/session_01JQwxbaoxpe1tyHuqnsAUFB Co-authored-by: Claude --- .changeset/37767-reconciler.md | 4 +- content/docs/automation/approvals.mdx | 21 ++++++---- .../plugin-approvals/src/approval-service.ts | 42 ++++++++++++------- 3 files changed, 44 insertions(+), 23 deletions(-) diff --git a/.changeset/37767-reconciler.md b/.changeset/37767-reconciler.md index 395e4029a2b..8c77832acc2 100644 --- a/.changeset/37767-reconciler.md +++ b/.changeset/37767-reconciler.md @@ -12,13 +12,13 @@ Widened: `ApprovalService` gains `reconcileMarkedApprovals(options?)`, which the Only for an approval the check stamped when it opened (one with a step that can act on an object that declares `closedStates`): -- **The door reads every run of the approval.** Where it read the run that carries the record and the latest request's own run, it now walks the tree from the run that carries the record, following the child runs each delegating step records: every `subflow` child, and every `map` item run that does not carry another record (an item that is a record carries an approval of its own). It reads the whole tree before it answers, and one run decides for the whole approval: one that the store could not answer for, or that reports a status of a run in motion (`pending`, `running`, `retrying`), makes it cannot tell; otherwise one parked at a node a step can follow, in progress; otherwise one that ended between two steps, abandoned. A run parked at such a node on a child run says what its child says, so the walk reads the child, at any depth. The automation engine reports none of those three statuses for a flow run today: a run it is advancing reads as paused with its pause gone, or as a run with no row, and is held by the rule for a run that stopped, below. So a sibling child whose failure the flow routed, a middle run two levels down that failed, an item run that failed before its step, and a run between two others that is being advanced are no longer read as finished. A failure routed to a pause no step follows is read as abandoned, as on the base. A stop is answered where a request of the approval opened after it. One judgement reads at most 200 runs beside those it kept as ended: past them it is cannot tell, keeps what it read, and the next judgement reads on. That has an end: once the approval's marks have stood for the hour of the age bound, a judgement reads on only while it keeps a run the approval had not kept (the kept list holds 200 runs), and the judgement that keeps none places the approval by the step last decided, below. Two costs come with that rule. A tree the judgements cannot finish is placed without being finished, and from about 399 runs a tree can be one no judgement finishes: the walk reads the runs it starts from before the runs below them, so for a `map` of 199 items that each call a `subflow`, every judgement reads the run and its 199 items and none of the runs below them. And the placement follows from the shape of the flow, so an approval submitted again on the same flow can meet the same end: the remedy is the flow's, not the submitter's. Reading on can take up to 200 further passes of the sweep clock (5 minutes) after the hour. A run parked on a child run that such a judgement did not get to says nothing of its own, and the child a parked run waits on is read next, before the runs beside it. +- **The door reads every run of the approval.** Where it read the run that carries the record and the latest request's own run, it now walks the tree from the run that carries the record, following the child runs each delegating step records: every `subflow` child, and every `map` item run that does not carry another record (an item that is a record carries an approval of its own). It reads the whole tree before it answers, and one run decides for the whole approval: one that the store could not answer for, or that reports a status of a run in motion (`pending`, `running`, `retrying`), makes it cannot tell; otherwise one parked at a node a step can follow, in progress; otherwise one that ended between two steps, abandoned. A run parked at such a node on a child run says what its child says, so the walk reads the child, at any depth. The automation engine reports none of those three statuses for a flow run today: a run it is advancing reads as paused with its pause gone, or as a run with no row, and is held by the rule for a run that stopped, below. So a sibling child whose failure the flow routed, a middle run two levels down that failed, an item run that failed before its step, and a run between two others that is being advanced are no longer read as finished. A failure routed to a pause no step follows is read as abandoned, as on the base. A stop is answered where a request of the approval opened after it. One judgement reads at most 200 runs beside those it kept as ended: past them it is cannot tell, keeps what it read, and the next judgement reads on. That has an end: once the approval's marks have stood for the hour of the age bound, a judgement reads on only while it keeps a run the approval had not kept (the kept list holds 200 runs), and the judgement that keeps none places the approval by the step last decided, below. Two costs come with that rule. A tree the judgements cannot finish is placed without being finished, and from about 399 runs a tree can be one no judgement finishes: the walk reads the runs it starts from before the runs below them, so for a `map` of 199 items that each call a `subflow`, every judgement reads the run and its 199 items and none of the runs below them. And the placement follows from the shape of the flow, so an approval submitted again on the same flow can meet the same end: the remedy is the flow's, not the submitter's. Reading on can take up to 200 further visits of the reconciler after the hour: one each sweep (every 5 minutes by default, the plugin's `escalationScanIntervalMs`), or one each turn of its walk where more requests are marked than one sweep reads. A run parked on a child run that such a judgement did not get to says nothing of its own, and the child a parked run waits on is read next, before the runs beside it. - **The plugin keeps what it read.** At every door, one that leaves the next request pending included, and as each request opens, the approval's latest request keeps, in its config snapshot (`__runsRead`): the runs that are not read again (`ended`), the runs read to their end over a child run that was not (`open`), a failure between two steps found in a run that ended, and the states the last judgement read that say a run has stopped (`stood`), which the rule for a run that stopped uses, below. A run is kept as ended only once it was read to an end and every child run its steps name is kept as ended too. So a child whose read failed, a child with no row, and the runs past the 200 one judgement reads are read on the next pass, which starts from the open runs as well. A run that a stored step names and that a pass did not read is never left out without a word: it is read on a later pass, it counts as passed by the rule below, or the approval is cannot tell and then placed. A run that no stored step names any more is not covered by that: see the limit of this release, below. A run the plugin read before the automation engine trimmed its history is not needed again, so an approval whose refused outcome is tried again after its run's history went is judged as it would have been. - **A run with no row, under a run that went on past it, is passed.** A run the engine has no row for counts as passed, and is kept as ended, where a run the plugin read went on past the step that names it: that step succeeded, and the run reached an end of its flow, or logged a later step and is not parked at that step. So an early child run trimmed before the plugin read it does not hold the approval back. A step that failed is never passed, also where the flow routed the failure and went on. A run the plugin had read to its end over an unread child, and whose own row is gone since, is not passed either: nothing names that child any more. - **A step log the engine marked, or the history row cut, is cannot tell.** Two logs are read as cut, and are not judged from as they stand: one with a step that carries the engine's mark `childRunIdsTruncated` (its execution started more child runs than the 200 a step names, or the history row shed the step's list to fit its size), and the log of a run that ended whose history row keeps fewer steps than the run logged (the row bounds the log by bytes, to a tail of it or to none, while the run's summary still counts every step). Within the age bound nothing is written; past it the approval is placed by the step last decided, as for a run with no row, below. A run whose log is cut is not kept as ended, the child runs it does name are still read, and it speaks for none of them: no run it names counts as passed. A summary that is absent or dropped its per-node detail gives nothing to compare, and reads as cut. - **The limit of this release: a log that loses whole steps carries no mark (ruling 7268216330 on #37767).** The engine marks one thing: a step whose child-run links were shed carries `childRunIdsTruncated`, above. A log that loses whole steps carries no mark, whichever way it loses them: the engine's compaction of a log of more than 200 steps, the history row's halving of a log over its 64 KB cap, a row stored as null. The plugin reads what the log kept, and a child run named only by a dropped step reads as one the run went past: it is not read. For a halved row and a null row the plugin can still tell that steps are missing, from the run's summary, which counts every step: that is the second log read as cut, above, and the approval is held and then placed. For a compacted log it cannot tell. A run that logged more than 200 steps is stored with 200 of them: every top-level step and every failed step, then the most recent of the rest (the most recent 200 of the top-level and failed steps, where those alone pass 200), and it is judged from those, as before this change. What an operator gets in that case: a `subflow` or `map` step the compaction dropped (one that succeeded inside a `loop`, `parallel` or `try_catch` region, or an early step of a very long run) no longer names the child runs it started; a failure the flow routed inside such a child run, between two steps, is not seen; and the approval can be written as finished, with no notice and no line in the log. A process that still holds the run in memory reads its whole log, so this is a judgement made once that process is gone. No approval is judged worse than before this change, whose door read no child run. - **The kept reading is its own key.** It is written onto the snapshot read again just before the write, and only while the column still reads the same, at most three times. It cannot write a stale snapshot over a note another writer left there (`__laterStepNotOpened`, `__strandedContinuation`). The judgement reads the note that a later step could not open once it has read the runs, so a note that lands while they are read is judged with. -- **A run that stopped, placed by the step last decided.** A run the engine has no row for and that no run the plugin read speaks for (its history is gone, or a process stopped while advancing it), a run whose step log is cut, above, a tree of more runs than the judgements can read in full, above, and the latest request's own run still parked at the step its decision was recorded on (a process stopped before the run was resumed), in the run that carries the record or in a child run any number of levels below it, are cannot tell for an hour from the approval's marks (the age bound). Past it, each has stopped at the step last decided once two judgements in a row read it in the same state, for the same run. The hour is counted from the marks and not from the run's last movement, and a run the engine is resuming reads as paused with its pause gone or as a run with no row; so an approval whose flow waits longer than the hour between two steps by design (a `wait` node, a batch over records whose items are approved one by one, a child run parked outside the approval's steps) is past the bound whenever it resumes. The judgement that reads a run in such a state first therefore does not place it (it cannot tell, and a run parked on a child that has ended is in progress), and keeps the state it read (`stood` in `__runsRead`); the next judgement places the run if it reads the same, and reads it anew if it does not. A judgement within the hour keeps what it read as well, a door's included, so an approval read in that state within the hour is placed by the first pass past it, and one that was not takes one pass more. A reading that could not be kept leaves the next judgement nothing to stand on. Two passes that each fall inside a resume of the same run still read it as stopped. Whether a later step can follow that step is asked in the flow its request records, so a node of another flow that carries the step's id does not answer for it. Where one can, the approval is abandoned: the record is put back, the submitter is told and submits again, the decisions already made stay on their requests, and a run still parked there is cancelled, with the runs that wait on it up to the run that carries the record, through a `map` whose items are not records as through a `subflow`. The cancel follows the put-back, and is not tried again once the put-back has landed: where it fails, or the process stops between the two, the run stays parked, the approval stays abandoned, and the door that continues a restored run refuses it. At the last step, the outcome is written and, once that write has landed, the administrators are told that the flow could not be seen through to its end after that step; the run's pause is left for an operator. A refused write sends no such notice, and the pass on which the write lands sends it. The notice says what to do in each case: continue or cancel a run that is still paused, and where the run has ended or no run is left, check that the steps after the decision were done. An approval placed for a cut log or a tree too large to read can be one whose flow did go on, which the plugin could not read in full: at its last step the administrators get the notice for a flow that ran, and where a later step can follow, the submitter submits again. +- **A run that stopped, placed by the step last decided.** A run the engine has no row for and that no run the plugin read speaks for (its history is gone, or a process stopped while advancing it), a run whose step log is cut, above, a tree of more runs than the judgements can read in full, above, and the latest request's own run still parked at the step its decision was recorded on (a process stopped before the run was resumed), in the run that carries the record or in a child run any number of levels below it, are cannot tell for an hour from the approval's marks (the age bound). Past it, each has stopped at the step last decided once two judgements in a row read it in the same state, for the same run. The hour is counted from the marks and not from the run's last movement, and a run the engine is resuming reads as paused with its pause gone or as a run with no row; so an approval whose flow waits longer than the hour between two steps by design (a `wait` node, a batch over records whose items are approved one by one, a child run parked outside the approval's steps) is past the bound whenever it resumes. Only an approval that holds nothing back can wait so: the check at its opening refuses each of the three between two steps of an approval on a field its object closes on. There a placement ends the hold and writes nothing. The judgement that reads a run in such a state first therefore does not place it (it cannot tell, and a run parked on a child that has ended is in progress), and keeps the state it read (`stood` in `__runsRead`); the next judgement places the run if it reads the same, and reads it anew if it does not. A judgement within the hour keeps what it read as well, a door's included, so an approval read in that state within the hour is placed by the first visit past it, and one that was not takes one visit more. A reading that could not be kept leaves on the request the reading kept before it: the next judgement stands on that earlier one, so a state kept earlier can still count, and where none was kept nothing is placed. An approval whose reading is never kept is therefore held with no end. Two passes that each fall inside a resume of the same run still read it as stopped. Whether a later step can follow that step is asked in the flow its request records, so a node of another flow that carries the step's id does not answer for it. Where one can, the approval is abandoned: the record is put back, the submitter is told and submits again, the decisions already made stay on their requests, and a run still parked there is cancelled, with the runs that wait on it up to the run that carries the record, through a `map` whose items are not records as through a `subflow`. The cancel follows the put-back, and is not tried again once the put-back has landed: where it fails, or the process stops between the two, the run stays parked, the approval stays abandoned, and the door that continues a restored run refuses it. At the last step, the outcome is written and, once that write has landed, the administrators are told that the flow could not be seen through to its end after that step; the run's pause is left for an operator. A refused write sends no such notice, and the pass on which the write lands sends it. The notice says what to do in each case: continue or cancel a run that is still paused, and where the run has ended or no run is left, check that the steps after the decision were done. An approval placed for a cut log or a tree too large to read can be one whose flow did go on, which the plugin could not read in full: at its last step the administrators get the notice for a flow that ran, and where a later step can follow, the submitter submits again. - **The reconciler.** Each pass reads two windows of at most 200 marked requests (`unjudged_since`): the oldest marks, and the next page of a walk over every marked request by id, so that marks which stay cannot keep the newer ones from being read. It judges each approval among them once, as the door would have: it writes the outcome in the name of the request's recorded decider, abandons the approval, or, where nothing was held back, clears the mark and writes nothing (where it concluded that a run had stopped, a line in the log says so). It ends what no door saw: a run that was cancelled, a parent run cancelled while its child's request was pending, and the stopped runs above. Past the age bound it also reads as stopped where it stood a run that reports paused while its pause is gone, and a run parked at a `subflow` or a `map` whose child run has ended or has no row, each once two judgements in a row read it so, as above. The item run of a `map` whose items are records is such a child once it is in a terminal status: its steps are an approval of the item's own record and are not read, only whether it has ended, and it is kept as ended only once it has. - **A refused write is tried again.** A refused outcome or put-back leaves the marks, and the next pass tries it again. The timeline line and the administrators' notice (keyed per request and status) are left once for one refusal; the same holds for the line an abandoned approval leaves. - **A deleted record.** Where the approval's record was deleted, the reconciler clears the marks of its requests and writes nothing: no retry and no notice. diff --git a/content/docs/automation/approvals.mdx b/content/docs/automation/approvals.mdx index c7a8061867a..6a653c29d05 100644 --- a/content/docs/automation/approvals.mdx +++ b/content/docs/automation/approvals.mdx @@ -1679,7 +1679,10 @@ items that each call a `subflow`, every reading takes the run and its 199 item runs, and never the runs below them. And the cause is the shape of the flow, so the same approval submitted again can meet the same end: give one approval fewer runs to read, because submitting again does not help. Reading on can take -up to 200 further sweeps, five minutes apart, after the hour. +up to 200 further visits after the hour. The reconciler visits an approval once +a sweep, every five minutes by default (the plugin's `escalationScanIntervalMs`), +or once a turn of its walk where more requests are marked than one sweep reads, +below. The platform trims every flow's run history in time. A run it read before that is not needed again. A run it never read counts as passed where the history of @@ -1702,12 +1705,16 @@ were set, each has stopped at the step last decided, once two checks in a row find it in the same state. The hour is counted from the marks, not from when the run last moved, and a run the platform is resuming at that moment looks like one a stopped process left: a run with no history to read, or a paused run -with nothing to resume it. An approval that waits longer than an hour between -two steps by design (a `wait` node, a batch of records approved one by one) is -past the hour whenever it resumes. So the check that first finds a run in such -a state only notes it, and the next check places the run if it finds the same. -A check made within the hour counts as the first, so this adds a sweep (five -minutes) only where the check before did not find the same. Where a later step could +with nothing to resume it. An approval can wait longer than an hour between two +steps by design (a `wait` node, a batch of records approved one by one) only +where none of its steps is concerned: the flow conditions above refuse both for +one that is. Such an approval holds nothing back, and it is past the hour +whenever it resumes. So the check that first finds a run in such a state only +notes it, and the next check places the run if it finds the same. A check made +within the hour counts as the first, so this adds one visit of the reconciler, +and only where the check before did not find the same: one sweep, five minutes +at the default interval, or one turn of the walk where more requests are marked +than one sweep reads. Where a later step could follow that step, the approval is abandoned, above, and a run still parked there is cancelled, with the runs that wait on it, so nothing resumes it; the decisions already made stay on their requests, and the submitter submits again. diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index cc626e56d0c..b22ec20ce47 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -1982,11 +1982,16 @@ export const MAX_RUNS_READ_PER_APPROVAL = 200; * items are approved one by one, a child parked outside the set) is past * the bound from the first instant of every later resume; and a run the * engine is resuming reads as paused with its pause gone, or as a run with - * no row. That state clears within the passage, and the one a dead process - * left is read again by the next judgement. The judgement that reads a - * state for the first time answers that it cannot tell, and keeps what it - * read; a judgement within the bound keeps it too, so an approval that was - * read within the hour is placed by the first judgement past it. The six: + * no row. Only an approval that holds nothing back can wait so: the check + * at its opening refuses each of the three between two steps of an approval + * whose object closes on the step's field (ADR-0162 D5, condition 5), so a + * placement inside such a passage ends a hold early and writes nothing + * (N31 of delta review 7270552441). That state clears within the passage, + * and the one a dead process left is read again by the next judgement. The + * judgement that reads a state for the first time answers that it cannot + * tell, and keeps what it read; a judgement within the bound keeps it too, + * so an approval that was read within the hour is placed by the first + * judgement past it. The six: * * - a run that reports paused while its pause is gone has stopped at the * last step it logged; @@ -6500,11 +6505,17 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * stale snapshot over another writer's note, whenever that note lands. * * Best-effort: a reading that is not kept leaves the runs to be read - * again, and leaves the next judgement no state to stand on: past the age - * bound nothing is placed until a reading is kept ({@link stoodState}). It - * answers whether `kept` is on the approval's rows now, which a judgement - * that relies on the next one reading on from it asks - * ({@link readCarryingRun}). + * again, and leaves on the request the reading kept before it, its states + * included ({@link stoodState}). The next judgement stands on that + * earlier reading, which is not the one before it: where it holds the + * same state for the same run, the run is placed on it; where it holds + * none, nothing is placed. So an approval whose reading is never kept is + * held with no end (N29 of delta review 7270552441). The condition of the + * write is the column as read just before it, so of two judgements at + * once the one that read first can write last. It answers whether `kept` + * is on the approval's rows now, which a judgement that relies on the + * next one reading on from it asks ({@link readCarryingRun}); the + * judgement that places a state does not ask. */ private async keepRunsRead(latest: any, approval: readonly any[], kept: RunsRead | undefined): Promise { if (!kept || !latest?.id) return false; @@ -12363,10 +12374,13 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * again; the mirror's notice to the administrators is keyed per request and * status, so it is sent once. For a record that was deleted, the marks of * its approval are cleared and nothing is written: no retry and no notice. - * An approval it cannot tell about keeps its marks for the next pass. Of - * the states it holds within the age bound, none is without an end: each - * is placed past it. What stays cannot tell at any age is a run that - * cannot be read (a store that does not answer, a run that reports a + * An approval it cannot tell about keeps its marks for the next pass. + * Each of the states it holds within the age bound is placed past it, + * once a reading of that state is kept and the next one reads the same. + * That has an end where the kept write lands; an approval whose reading + * is never kept, and that kept no such state before, is held with no end + * ({@link keepRunsRead}). What also stays cannot tell at any age is a run + * that cannot be read (a store that does not answer, a run that reports a * status the plugin does not place or that another process is advancing): * it is read again on the next pass. *