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/.changeset/37767-step-child-runs.md b/.changeset/37767-step-child-runs.md new file mode 100644 index 00000000000..b6d5285a8df --- /dev/null +++ b/.changeset/37767-step-child-runs.md @@ -0,0 +1,16 @@ +--- +'@objectstack/service-automation': patch +--- + +feat(automation): a delegating step records the child runs it started (ADR-0162 Execution item 8) + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened: `AutomationEngine` gains the public read `runStartedFor(context)` and an optional second argument to `getRun(runId, { strict })`; a node executor's result (`NodeExecutionResult`) and the exported step type (`StepLogEntry`) gain the optional `childRunIds`, which the engine copies onto the step's log entry (`ExecutionStepLogSchema.childRunIds`, in `@objectstack/spec`). + +- **`childRunIds` on a step.** A `subflow` step names the one run it started, on every exit: paused on its child, completed, failed or refused. A `map` step names the item runs that execution of the step started. Absent on a step that started none, and on a child that paused with no run id. A log of more than 200 steps is compacted for history and can drop a region-body step with its link; a top-level step keeps it. `getRun` serves it with the rest of the step log, so a reader can walk a run's tree from its root; before this, a parent's link to its child lived only on the parent's pause (`correlation: 'subflow:'`), and only while the parent was parked. +- **`runStartedFor(context)`.** A run that ends inside `execute` answers no `runId` (the contract sets it on a paused run only). The engine now answers the id of the run the last `execute` call started for that very context object, whatever it ended in. A run is named once it is past the gates that skip it and leaves a history row, or where it fails before its first node and is recorded as failed; `undefined` where no run started (the flow was missing, disabled, had no start node, or its start condition or the re-entry guard skipped it). Under `errorHandling.strategy: 'retry'` it is the last attempt that started a run. The `subflow` and `map` nodes read it for a child that ended inside the call. +- **`getRun(runId, { strict: true })`.** A store that fails is still logged and read as `null` by default. With `strict`, its failure is thrown instead, so a caller that decides on a missing run can tell a run with no row from a store that did not answer. + +Unchanged: what a run does, the `runId` the contract returns, and every existing step field. diff --git a/.changeset/37767-step-log-child-runs-spec.md b/.changeset/37767-step-log-child-runs-spec.md new file mode 100644 index 00000000000..f374bafc8ea --- /dev/null +++ b/.changeset/37767-step-log-child-runs-spec.md @@ -0,0 +1,11 @@ +--- +'@objectstack/spec': minor +--- + +feat(spec): a run's step log names the child runs a step started (`ExecutionStepLogSchema.childRunIds`, ADR-0162 Execution item 8) + +Clause-②: yes (widening) +Metadata-protocol: added +Skills-docs: none — `skills/` names none of `ExecutionStepLog`, `childRunIds`, `runStartedFor` or `unjudged_since` (git grep, 0 hits): the step log is a runtime record no skill teaches an author to write + +Widened: `ExecutionStepLogSchema` gains the optional `childRunIds: string[]`: the run ids of the child runs the step started, the one run of a `subflow` and, for a `map`, the item runs that execution of the step started. Absent for a step that started none. The engine writes it (`@objectstack/service-automation`); a reader of `getRun` can walk a run's tree from its root with it. Nothing an author writes in a flow changes. 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/content/docs/references/automation/execution.mdx b/content/docs/references/automation/execution.mdx index 610c160b022..d9353cc41f5 100644 --- a/content/docs/references/automation/execution.mdx +++ b/content/docs/references/automation/execution.mdx @@ -150,6 +150,7 @@ const result = CheckpointSchema.parse(data); | **skippedBy** | `{ nodeId: string; edgeId?: string; label?: string }` | optional | The gate that closed, when `status` is `skipped` | | **warnings** | `string[]` | optional | Advisory warnings from the node executor. A `success` step may carry them — e.g. a write whose requested fields the data engine legally stripped — so a step that partially did not land never reads as a clean success. Absent when the executor raised none | | **droppedFields** | `{ object: string; fields: string[]; reason: Enum<'readonly' \| 'readonly_when' \| 'primary_key' \| 'computed' \| 'stored_expression'> }[]` | optional | The data engine's own drop events behind those warnings: which caller-supplied fields of which object the write did not store, and why. Absent when the step dropped nothing | +| **childRunIds** | `string[]` | optional | Run ids of the child runs this step started: the one run of a `subflow`, and for a `map` the item runs this execution of the step started. Absent for a step that started none | ### Nested Shape: `ExecutionLog.summary` @@ -210,6 +211,7 @@ const result = CheckpointSchema.parse(data); | **skippedBy** | `{ nodeId: string; edgeId?: string; label?: string }` | optional | The gate that closed, when `status` is `skipped` | | **warnings** | `string[]` | optional | Advisory warnings from the node executor. A `success` step may carry them — e.g. a write whose requested fields the data engine legally stripped — so a step that partially did not land never reads as a clean success. Absent when the executor raised none | | **droppedFields** | `{ object: string; fields: string[]; reason: Enum<'readonly' \| 'readonly_when' \| 'primary_key' \| 'computed' \| 'stored_expression'> }[]` | optional | The data engine's own drop events behind those warnings: which caller-supplied fields of which object the write did not store, and why. Absent when the step dropped nothing | +| **childRunIds** | `string[]` | optional | Run ids of the child runs this step started: the one run of a `subflow`, and for a `map` the item runs this execution of the step started. Absent for a step that started none | ### Nested Shape: `ExecutionStepLog.error` 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-automation/src/builtin/map-node.ts b/packages/services/service-automation/src/builtin/map-node.ts index a6ab215e4c8..ea2fa6ae5f3 100644 --- a/packages/services/service-automation/src/builtin/map-node.ts +++ b/packages/services/service-automation/src/builtin/map-node.ts @@ -216,6 +216,13 @@ export function registerMapNode(engine: AutomationEngine, ctx: PluginContext): v // (AutomationEngine.creditChildRun). A failed or refused item's answer // carries none. const itemDrops: unknown[] = []; + // [ADR-0162 Execution item 8] The item runs THIS entry started, in order, + // on every exit: the engine copies them onto this entry's step + // (`childRunIds`), where a reader of the parent's log finds each one. + // An item that started no run, and an item paused with no run id, add + // none. + const startedRuns: string[] = []; + const rolledRuns = (): { childRunIds?: string[] } => (startedRuns.length > 0 ? { childRunIds: [...startedRuns] } : {}); const rolledDrops = () => { const droppedFields = foldDropEvents(itemDrops); return droppedFields ? { droppedFields } : {}; @@ -260,6 +267,10 @@ export function registerMapNode(engine: AutomationEngine, ctx: PluginContext): v delete childContext.saveNotice; const child = await engine.execute(flowName, childContext); + // A child that ended inside the call answers no `runId`: the engine + // names the run it started for this context. + const childRunId = child.runId ?? engine.runStartedFor(childContext); + if (childRunId) startedRuns.push(String(childRunId)); if (child.status === 'paused') { if (!child.runId) { @@ -276,6 +287,7 @@ export function registerMapNode(engine: AutomationEngine, ctx: PluginContext): v // back (AutomationEngine.creditChildRun). metrics: { selected, acted, ...(unmeasured ? { unmeasuredEffect: true } : {}), ...rolledFailures() }, ...rolledDrops(), + ...rolledRuns(), }; } if (!child.success) { @@ -306,6 +318,7 @@ export function registerMapNode(engine: AutomationEngine, ctx: PluginContext): v // `try_catch` or `fault` edge that contains this failure lets the // run complete, and its answer folds this step. ...rolledDrops(), + ...rolledRuns(), }; } if (child.status === 'refused') { @@ -350,6 +363,7 @@ export function registerMapNode(engine: AutomationEngine, ctx: PluginContext): v : rolledFailures()), }, ...rolledDrops(), + ...rolledRuns(), }; } // Synchronous completion — record and advance. @@ -401,6 +415,7 @@ export function registerMapNode(engine: AutomationEngine, ctx: PluginContext): v output: { results: state.results, count: state.results.filter(r => !isMapItemCancelledMarker(r)).length }, metrics: { selected, acted, ...(unmeasured ? { unmeasuredEffect: true } : {}), ...rolledFailures() }, ...rolledDrops(), + ...rolledRuns(), }; }, }); diff --git a/packages/services/service-automation/src/builtin/subflow-node.ts b/packages/services/service-automation/src/builtin/subflow-node.ts index f74fd9c219e..26c93b7612d 100644 --- a/packages/services/service-automation/src/builtin/subflow-node.ts +++ b/packages/services/service-automation/src/builtin/subflow-node.ts @@ -123,6 +123,14 @@ export function registerSubflowNode(engine: AutomationEngine, ctx: PluginContext delete childContext.saveNotice; const child = await engine.execute(flowName, childContext); + // [ADR-0162 Execution item 8] The child run, on every exit below that + // has one: the engine copies it onto this node's step (`childRunIds`). + // A child that ended inside the call answers no `runId`: the engine + // names the run it started for this context. A child that started no + // run (missing, disabled, skipped by its start condition) and a pause + // with no run id name none. + const childRunId = child.runId ?? engine.runStartedFor(childContext); + const childRuns = childRunId ? { childRunIds: [String(childRunId)] } : {}; if (child.status === 'paused') { // Nested durable pause: the child's continuation is persisted under its @@ -138,6 +146,7 @@ export function registerSubflowNode(engine: AutomationEngine, ctx: PluginContext suspend: true, correlation: `subflow:${child.runId}`, screen: child.screen, + ...childRuns, }; } // #4354 — roll the child's totals up into this node's step. The child's @@ -177,6 +186,7 @@ export function registerSubflowNode(engine: AutomationEngine, ctx: PluginContext // (`inner-refusal.ts`); `{}` for a child that met none. ...carriedRefusalOfResult(child), ...(rolled ? { metrics: rolled } : {}), + ...childRuns, }; } @@ -209,6 +219,7 @@ export function registerSubflowNode(engine: AutomationEngine, ctx: PluginContext success: true as const, output: { output: child.output ?? null }, ...(metrics ? { metrics } : {}), + ...childRuns, // #32861 — the values the child's write steps did not store ride up // onto this step, so the parent's answer (`AutomationResult.droppedFields`) // tells the caller about a drop its delegated write met. Set by the diff --git a/packages/services/service-automation/src/dag-traversal.ts b/packages/services/service-automation/src/dag-traversal.ts index 8e41a0b59a4..143fe0f7d54 100644 --- a/packages/services/service-automation/src/dag-traversal.ts +++ b/packages/services/service-automation/src/dag-traversal.ts @@ -103,6 +103,19 @@ export function runUserOf(context: AutomationContext | undefined): EvalUserParse }); } +/** + * [ADR-0162 Execution item 8] The child runs a step started + * (`NodeExecutionResult.childRunIds`), copied onto the step: the non-empty + * strings only, the member omitted where none is left. Total, never throwing, + * for the reason {@link stepAdvisoriesOf} gives. + */ +function stepChildRunsOf(result: NodeExecutionResult): { childRunIds?: string[] } { + const raw: unknown = result.childRunIds; + if (!Array.isArray(raw)) return {}; + const ids = raw.filter((id): id is string => typeof id === 'string' && id.length > 0); + return ids.length > 0 ? { childRunIds: ids } : {}; +} + /** * The step-log copy of an executor's advisory members, in exactly the shape * `ExecutionStepLogSchema` declares for them. The step is persisted with the @@ -179,6 +192,7 @@ export interface DagTraversalHost { readonly isFlowEnabled: AutomationEngine['isFlowEnabled']; readonly describeDisabledFlow: AutomationEngine['describeDisabledFlow']; readonly nextRunId: AutomationEngine['nextRunId']; + readonly noteRunStarted: AutomationEngine['noteRunStarted']; readonly seedRunVariables: AutomationEngine['seedRunVariables']; readonly resolveRunContext: AutomationEngine['resolveRunContext']; readonly validateNodeInputSchemas: AutomationEngine['validateNodeInputSchemas']; @@ -496,6 +510,7 @@ export async function executeNode( error: { code: 'NODE_FAILURE', message: errMsg }, // In the declared step-log shape only (`stepAdvisoriesOf`). ...stepAdvisoriesOf(result), + ...stepChildRunsOf(result), // #4354 — a node that failed PART WAY may still have written // rows; dropping its counts would understate what the run did. ...(result.metrics ? { metrics: result.metrics } : {}), @@ -571,6 +586,7 @@ export async function executeNode( // (`dropEventsOf`). Both members are copied in the declared // step-log shape only (`stepAdvisoriesOf`). ...stepAdvisoriesOf(result), + ...stepChildRunsOf(result), ...(result.metrics ? { metrics: result.metrics } : {}), }); @@ -1355,7 +1371,7 @@ export function startConditionHolds( /** The body of {@link AutomationEngine.executeWithoutRetry}, moved unedited; that method's docblock is its contract. */ export async function executeWithoutRetry( - this: Pick, + this: Pick, flowName: string, context?: AutomationContext, dispatched?: { errorMessage: string | undefined }, @@ -1437,6 +1453,10 @@ export async function executeWithoutRetry( this.logger.debug(`Flow '${flowName}' skipped: start condition not met`); return { success: true, output: { skipped: true, reason: 'condition_not_met' }, flowLabel: flow.label }; } + // [ADR-0162 Execution item 8] Past the gate this attempt is a run + // that leaves a history row; the skip above records none, so it + // names no run ({@link AutomationEngine.runStartedFor}). + this.noteRunStarted(context, runId); // [#9889] The SAME definition-level guard attempt 1 runs under — // the sixth instance of this method drifting from `execute()` diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index 32d6bba6bdc..ada34a2628b 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -471,6 +471,17 @@ export interface NodeExecutionResult { * approval request id). For observability / lookup; not required to resume. */ correlation?: string; + /** + * [ADR-0162 Execution item 8] The child runs this execution of the node + * started — a `subflow`'s one run, the item runs of a `map` — on every exit, + * paused, failed, refused or completed, where a run started and has an id + * (a child that paused with no run id names none). The engine copies them + * onto the step's {@link StepLogEntry} (`childRunIds`), so a reader of the + * run's log reaches each child run without the parent's context. A log of + * more than 200 steps is compacted for history and can drop a region-body + * step with its link; a top-level step keeps it. + */ + childRunIds?: string[]; /** * Screen to render — set by a `screen` node that suspends to collect input. * Surfaced on the paused {@link AutomationResult} so a UI runner can render @@ -1174,6 +1185,13 @@ export interface StepLogEntry { * (`dropEventsOf`). */ droppedFields?: DroppedFieldsEvent[]; + /** + * [ADR-0162 Execution item 8] The child runs this step started + * ({@link NodeExecutionResult.childRunIds}), as `ExecutionStepLogSchema` + * declares the member: a `subflow`'s one run, the item runs of a `map`. + * Absent where the step started none. + */ + childRunIds?: string[]; /** * #1479: structured-region grouping. When a step ran inside a `loop` / * `parallel` / `try_catch` body region, these tag it with its **immediate** @@ -3812,6 +3830,36 @@ export class AutomationEngine implements IAutomationService { return nextRunId(); } + /** + * [ADR-0162 Execution item 8] The run each context object handed to + * {@link execute} last started, keyed by that object. A run that completes, + * fails or refuses inside the call answers no `runId` (the contract sets it + * on a paused run only), so a delegating node that must record the child + * run it started asks {@link runStartedFor} with the context it passed. + * Weakly held: an entry lives as long as the caller keeps its context. + */ + private readonly runsStartedByContext = new WeakMap(); + + /** Note that `runId` was started for the caller's `context` ({@link runsStartedByContext}). */ + private noteRunStarted(context: AutomationContext | undefined, runId: string): void { + if (context && typeof context === 'object') this.runsStartedByContext.set(context, runId); + } + + /** + * [ADR-0162 Execution item 8] The id of the run the last {@link execute} + * call handed this very `context` object started, whatever it ended in; + * `undefined` where no run started (the flow was missing, disabled, had no + * start node, its start condition skipped it, or the re-entry guard did): + * a run is noted once it is past those gates, where it leaves a history + * row, or where it fails before its first node and is recorded as failed. + * Under `errorHandling.strategy: 'retry'` it is the last attempt that + * started a run. Read by the `subflow` and `map` nodes, which pass each + * child a context of its own. + */ + runStartedFor(context: AutomationContext): string | undefined { + return this.runsStartedByContext.get(context); + } + /** * Persist a suspended run to the in-memory cache and (best-effort) the * durable store. A store failure does not fail the run — the in-memory copy @@ -8019,7 +8067,15 @@ export class AutomationEngine implements IAutomationService { return suspendedRunToLogEntry(run); } - getRun(runId: string): Promise { + /** + * One run's log entry: the in-memory entry, else its terminal history row, + * else its suspension row; `null` where none answers. A store that fails + * is logged and read as `null` too, unless `options.strict` is set + * ([ADR-0162 Execution item 8]): then the store's failure is thrown, so a + * caller that decides on a missing run (the approvals plugin's reconciler) + * can tell a run with no row from a store that did not answer. + */ + getRun(runId: string, options?: { strict?: boolean }): Promise { // The body lives in ./run-history.ts (#25222). const readStore = () => this.store; const host: ThisParameterType = { @@ -8029,7 +8085,7 @@ export class AutomationEngine implements IAutomationService { logger: this.logger, suspendedRunToLogEntry: (...a) => this.suspendedRunToLogEntry(...a), }; - return getRun.call(host, runId); + return getRun.call(host, runId, options); } /** @@ -8393,6 +8449,9 @@ export class AutomationEngine implements IAutomationService { // and recorded as such, never a throw out of `execute()`. Any // other throw is unchanged. if (!(err instanceof HeldValueCycleError)) throw err; + // [ADR-0162 Execution item 8] A run that fails before its first + // node is recorded as a failed run: it started. + this.noteRunStarted(context, runId); return this.failRunBeforeFirstNode({ runId, flowName, flow, startedAt, startTime, context, error: err.message }); } stampFlowRunSlot(runContext, flowName, runPackage); @@ -8483,6 +8542,10 @@ export class AutomationEngine implements IAutomationService { this.activeRecordFlows.add(reentryKey); reentryHeld = true; } + // [ADR-0162 Execution item 8] Past both gates the run is dispatched + // and leaves a history row whatever it ends in. Neither skip above + // records one, so neither names a run here ({@link runStartedFor}). + this.noteRunStarted(context, runId); // Validate node input schemas before execution. [#9889] The same // call sits in `executeWithoutRetry` — every retry attempt must be @@ -12280,6 +12343,7 @@ export class AutomationEngine implements IAutomationService { isFlowEnabled: (...a) => this.isFlowEnabled(...a), describeDisabledFlow: (...a) => this.describeDisabledFlow(...a), nextRunId: (...a) => this.nextRunId(...a), + noteRunStarted: (...a) => this.noteRunStarted(...a), seedRunVariables: (...a) => this.seedRunVariables(...a), resolveRunContext: (...a) => this.resolveRunContext(...a), evaluateCondition: (...a) => this.evaluateCondition(...a), diff --git a/packages/services/service-automation/src/run-history.ts b/packages/services/service-automation/src/run-history.ts index b60e2baaf0e..0b9a1d43e79 100644 --- a/packages/services/service-automation/src/run-history.ts +++ b/packages/services/service-automation/src/run-history.ts @@ -317,7 +317,7 @@ export function suspendedRunToLogEntry(run: SuspendedRun): ExecutionLogEntry { } /** The body of {@link AutomationEngine.getRun}, moved unedited; that method's docblock is its contract. */ -export async function getRun(this: Pick, runId: string): Promise { +export async function getRun(this: Pick, runId: string, options?: { strict?: boolean }): Promise { // LAST entry wins, not the first: a run that pauses and later finishes // records TWO entries under the same run id ('paused', then // 'completed'/'failed'/'cancelled'). Scanning forwards returned the stale @@ -358,6 +358,9 @@ export async function getRun(this: Pick l; + return l; +} + +function rig() { + const engine = withLoaderSetFromPull(new AutomationEngine(createTestLogger())); + engine.setFlowActivationStore(new InMemoryFlowActivationStore()); + const ctx = { logger: createTestLogger(), getService: () => undefined } as any; + for (const register of [registerSubflowNode, registerMapNode, registerWaitNode, registerLogicNodes]) { + (register as (e: AutomationEngine, c: unknown) => void)(engine, ctx); + } + return engine; +} + +type Node = Record; +const START: Node = { id: 'start', type: 'start', label: 'Start', config: {} }; +const END: Node = { id: 'end', type: 'end', label: 'End' }; +const NOOP: Node = { id: 'noop', type: 'assignment', label: 'Nothing', config: {} }; +const WAIT: Node = { id: 'hold', type: 'wait', label: 'Hold', waitEventConfig: { eventType: 'timer', timerDuration: 'PT1H' } }; +function chain(name: string, nodes: Node[]) { + return { + name, label: name, type: 'autolaunched', + nodes: [START, ...nodes, END], + edges: [START, ...nodes, END].slice(1).map((n, i, rest) => ({ + id: `e${i}`, source: (i === 0 ? START : rest[i - 1]).id as string, target: n.id as string, + })), + }; +} +const sub = (flowName: string, id = 'call'): Node => ({ id, type: 'subflow', label: 'Call', config: { flowName } }); +const map = (flowName: string, items: unknown[], id = 'each'): Node => ({ id, type: 'map', label: 'Each', config: { flowName, collection: items } }); + +// Type-level pin: the engine's exported step type declares the member the +// spec's step log declares, with the same type, so `getRun`'s answer is typed +// as the schema says. Compiled by the package's typecheck, invisible to vitest. +type Eq = (() => G extends A ? 1 : 2) extends () => G extends B ? 1 : 2 ? true : false; +type Assert = T; +export type _ChildRunIdsInStep = Assert< + Eq, Pick> +>; + +const stepOf = async (engine: AutomationEngine, runId: string, nodeId: string) => + ((await engine.getRun(runId)) as any)?.steps?.filter((s: any) => s.nodeId === nodeId) ?? []; + +describe('[ADR-0162 item 8] a delegating step records the child runs it started', () => { + it('a subflow whose child completes inside the call: the step names the child run', async () => { + const engine = rig(); + engine.registerFlow('child', chain('child', [NOOP]) as any); + engine.registerFlow('parent', chain('parent', [sub('child')]) as any); + const context = {} as AutomationContext; + const out: any = await engine.execute('parent', context); + expect(out.success).toBe(true); + expect(out.runId, 'a completed run answers no runId').toBeUndefined(); + + const parentRun = engine.runStartedFor(context)!; + expect(parentRun).toBeTruthy(); + const [step] = await stepOf(engine, parentRun, 'call'); + expect(step.childRunIds).toHaveLength(1); + const child: any = await engine.getRun(step.childRunIds[0]); + expect(child?.flowName).toBe('child'); + expect(child?.status).toBe('completed'); + const [first] = await stepOf(engine, parentRun, 'start'); + expect(first.childRunIds, 'a step that started no run carries none').toBeUndefined(); + }); + + it('a subflow whose child pauses: the parked step names the run its pause correlates with', async () => { + const engine = rig(); + engine.registerFlow('child', chain('child', [WAIT]) as any); + engine.registerFlow('parent', chain('parent', [sub('child')]) as any); + const out: any = await engine.execute('parent', {} as AutomationContext); + expect(out.status).toBe('paused'); + const [step] = await stepOf(engine, out.runId, 'call'); + const parked: any = await (engine as any).suspensionOf(out.runId); + expect(parked.correlation).toBe(`subflow:${step.childRunIds[0]}`); + }); + + it('a map: the step names every item run it started, each a run of its own', async () => { + const engine = rig(); + engine.registerFlow('item', chain('item', [NOOP]) as any); + engine.registerFlow('batch', chain('batch', [map('item', [1, 2, 3])]) as any); + const context = {} as AutomationContext; + const out: any = await engine.execute('batch', context); + expect(out.success).toBe(true); + const steps = await stepOf(engine, engine.runStartedFor(context)!, 'each'); + const ids = steps.flatMap((s: any) => s.childRunIds ?? []); + expect(ids).toHaveLength(3); + expect(new Set(ids).size).toBe(3); + for (const id of ids) expect(((await engine.getRun(id)) as any)?.flowName).toBe('item'); + }); + + it('no run started: runStartedFor answers nothing for a flow that is not registered', async () => { + const engine = rig(); + const context = {} as AutomationContext; + const out: any = await engine.execute('missing', context); + expect(out.success).toBe(false); + expect(engine.runStartedFor(context)).toBeUndefined(); + }); + + it('no run started: a child its start condition skips is named by no step and by runStartedFor', async () => { + const engine = rig(); + const gated = chain('child', [NOOP]) as any; + gated.nodes = gated.nodes.map((n: Node) => (n.type === 'start' ? { ...n, config: { condition: '1 == 2' } } : n)); + engine.registerFlow('child', gated); + engine.registerFlow('parent', chain('parent', [sub('child')]) as any); + + const direct = {} as AutomationContext; + const skipped: any = await engine.execute('child', direct); + expect(skipped.output).toEqual({ skipped: true, reason: 'condition_not_met' }); + expect(engine.runStartedFor(direct), 'a skipped start leaves no history row, so it names no run').toBeUndefined(); + + const context = {} as AutomationContext; + const out: any = await engine.execute('parent', context); + expect(out.success).toBe(true); + const [step] = await stepOf(engine, engine.runStartedFor(context)!, 'call'); + expect(step.status).toBe('success'); + expect(step.childRunIds, 'the call started no run').toBeUndefined(); + }); +}); 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', diff --git a/packages/spec/authorable-surface/automation.json b/packages/spec/authorable-surface/automation.json index 6f2879d733f..d864d2b4c2e 100644 --- a/packages/spec/authorable-surface/automation.json +++ b/packages/spec/authorable-surface/automation.json @@ -161,6 +161,7 @@ "automation/ExecutionLog:variables", "automation/ExecutionLog:waitMs", "automation/ExecutionStepLog:branch", + "automation/ExecutionStepLog:childRunIds", "automation/ExecutionStepLog:completedAt", "automation/ExecutionStepLog:droppedFields", "automation/ExecutionStepLog:durationMs", diff --git a/packages/spec/src/automation/execution.zod.ts b/packages/spec/src/automation/execution.zod.ts index 2184cfca6af..128e0e42b90 100644 --- a/packages/spec/src/automation/execution.zod.ts +++ b/packages/spec/src/automation/execution.zod.ts @@ -216,6 +216,12 @@ export const ExecutionStepLogSchema = lazySchema(() => z.object({ .describe('Advisory warnings from the node executor. A `success` step may carry them — e.g. a write whose requested fields the data engine legally stripped — so a step that partially did not land never reads as a clean success. Absent when the executor raised none'), droppedFields: z.array(DroppedFieldsEventSchema).optional() .describe('The data engine\'s own drop events behind those warnings: which caller-supplied fields of which object the write did not store, and why. Absent when the step dropped nothing'), + // [ADR-0162 Execution item 8] The child runs a delegating step started, so a + // reader of one run can reach every run of its tree from the step log alone: + // a child's own log is a row of its own, and nothing else on the parent's + // log names it once the parent has moved past the step. + childRunIds: z.array(z.string()).optional() + .describe('Run ids of the child runs this step started: the one run of a `subflow`, and for a `map` the item runs this execution of the step started. Absent for a step that started none'), })); export type ExecutionStepLog = z.input;