From 313c0bb4435db34729d61dcc66af3fdb9640fc43 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 14:56:49 +0000 Subject: [PATCH 1/7] feat(automation): a delegating step records the child runs it started, and a strict run read tells a missing row from a store that did not answer The engine half of the approval reconciler work, taken unchanged from the reviewed head 46ca8ff561 (spec, service-automation, their changesets and generated outputs), plus the strict-read warning text: on a strict read getRun's two store-failure warnings say the failure is thrown to the caller, and the comment over the terminal probe no longer says the read never throws. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jR5js5DV1FHUxHyAb4 --- .changeset/37767-step-child-runs.md | 16 ++ .changeset/37767-step-log-child-runs-spec.md | 11 ++ .../docs/references/automation/execution.mdx | 2 + .../src/builtin/map-node.ts | 15 ++ .../src/builtin/subflow-node.ts | 11 ++ .../service-automation/src/dag-traversal.ts | 22 ++- .../services/service-automation/src/engine.ts | 68 ++++++++- .../service-automation/src/run-history.ts | 33 ++-- .../src/step-child-runs.test.ts | 143 ++++++++++++++++++ .../spec/authorable-surface/automation.json | 1 + packages/spec/src/automation/execution.zod.ts | 6 + 11 files changed, 315 insertions(+), 13 deletions(-) create mode 100644 .changeset/37767-step-child-runs.md create mode 100644 .changeset/37767-step-log-child-runs-spec.md create mode 100644 packages/services/service-automation/src/step-child-runs.test.ts 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/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/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..fd5d3b93930 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 @@ -331,7 +331,8 @@ 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/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; From bf9fb564aaa3defef7548c6f98bf4e5d1a9f9106 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 00:14:30 +0000 Subject: [PATCH 2/7] wip(automation): bound a step's child run links, shed them first at the history row (ADR-0162 item 8) --- .../service-automation/src/dag-traversal.ts | 14 +- .../src/engine-residual-log-cause.test.ts | 49 ++++++ .../services/service-automation/src/engine.ts | 44 ++++- .../service-automation/src/run-history.ts | 4 +- .../src/step-child-runs.test.ts | 154 +++++++++++++++++- .../src/suspended-run-store.ts | 25 +++ packages/spec/src/automation/execution.zod.ts | 7 +- 7 files changed, 275 insertions(+), 22 deletions(-) diff --git a/packages/services/service-automation/src/dag-traversal.ts b/packages/services/service-automation/src/dag-traversal.ts index 143fe0f7d54..a091a2b3d12 100644 --- a/packages/services/service-automation/src/dag-traversal.ts +++ b/packages/services/service-automation/src/dag-traversal.ts @@ -24,7 +24,7 @@ import { summarizeRun } from './run-summary.js'; import { withDroppedFields } from './run-dropped-fields.js'; import { describeThrownForLog } from './thrown-cause-diagnostics.js'; // The values below (`AutomationEngine` for its public static -// `MAX_NODE_REENTRIES`, and `activeMsAtPause`) are read only inside the function bodies, at call time, +// `MAX_NODE_REENTRIES`, `activeMsAtPause` and `MAX_STEP_CHILD_RUN_IDS`) are read only inside the function bodies, at call time, // never while a module is evaluating, so the import cycle with ./engine.js is // safe under ESM live bindings; the tsup bundle is one file and has no cycle. import { @@ -36,6 +36,7 @@ import { FlowSuspendSignal, isRefusalSignal, isSuspendSignal, + MAX_STEP_CHILD_RUN_IDS, nestedChildRunId, type ExecutionLogEntry, type NodeExecutionResult, @@ -108,12 +109,19 @@ export function runUserOf(context: AutomationContext | undefined): EvalUserParse * (`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. + * + * [seat ruling 7258590209 on #37767] Bounded here, for every executor: the + * step names at most {@link MAX_STEP_CHILD_RUN_IDS} runs, the first ones + * started, and carries `childRunIdsTruncated: true` where there were more. */ -function stepChildRunsOf(result: NodeExecutionResult): { childRunIds?: string[] } { +function stepChildRunsOf(result: NodeExecutionResult): { childRunIds?: string[]; childRunIdsTruncated?: true } { 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 } : {}; + if (ids.length === 0) return {}; + return ids.length > MAX_STEP_CHILD_RUN_IDS + ? { childRunIds: ids.slice(0, MAX_STEP_CHILD_RUN_IDS), childRunIdsTruncated: true } + : { childRunIds: ids }; } /** diff --git a/packages/services/service-automation/src/engine-residual-log-cause.test.ts b/packages/services/service-automation/src/engine-residual-log-cause.test.ts index 586167768bc..8fb8346939f 100644 --- a/packages/services/service-automation/src/engine-residual-log-cause.test.ts +++ b/packages/services/service-automation/src/engine-residual-log-cause.test.ts @@ -329,6 +329,55 @@ describe('#6499 sites 1–4 — SuspendedRunStore driver seams', () => { assertSilent(streams.stderr, 'durable run lookup failed', 'stderr'); }); + // [ADR-0162 Execution item 8] The strict read (`getRun(runId, { strict: true })`): + // the same two store reads, and the store's failure is the caller's answer + // instead of `null`. Each read rejects with the store's own error and logs + // its strict sentence once, as the default read logs its own above. + it('site 3, strict read: a throwing loadTerminal rejects, and the record says the failure is thrown', async () => { + const engine = new AutomationEngine(jsonLogger(), workingStore({ + async loadTerminal() { throw new Error(MULTILINE_DRIVER); }, + })); + + let thrown: unknown; + const streams = await captureBoth(async () => { + await engine.getRun('run_gone', { strict: true }).then( + () => { thrown = 'resolved'; }, + (err: unknown) => { thrown = err; }, + ); + }); + + expect(thrown, 'the store failure reaches the caller, not null').toBeInstanceOf(Error); + expect((thrown as Error).message).toBe(MULTILINE_DRIVER); + const record = soleRecordWith(streams.stdout, 'durable run lookup failed'); + expectOneLineWithCause(record, 'warn'); + expect(record.msg).toContain('this strict read throws the failure to its caller'); + expect(record.msg).not.toContain('DEGRADES to null'); + assertSilent(streams.stderr, 'durable run lookup failed', 'stderr'); + }); + + it('site 3, strict read: a throwing paused-run load rejects, and the record says the failure is thrown', async () => { + const engine = new AutomationEngine(jsonLogger(), workingStore({ + async loadTerminal() { return null; }, + async load(): Promise { throw new Error(MULTILINE_DRIVER); }, + })); + + let thrown: unknown; + const streams = await captureBoth(async () => { + await engine.getRun('run_gone', { strict: true }).then( + () => { thrown = 'resolved'; }, + (err: unknown) => { thrown = err; }, + ); + }); + + expect(thrown, 'the store failure reaches the caller, not null').toBeInstanceOf(Error); + expect((thrown as Error).message).toBe(MULTILINE_DRIVER); + const record = soleRecordWith(streams.stdout, 'durable paused-run lookup failed'); + expectOneLineWithCause(record, 'warn'); + expect(record.msg).toContain('this strict read throws the failure to its caller'); + expect(record.msg).not.toContain('DEGRADES to null'); + assertSilent(streams.stderr, 'durable paused-run lookup failed', 'stderr'); + }); + it("site 4: recordTerminal — #4632 DURABILITY, RAISED warn→error: the run reads healthy while its history row never landed", async () => { const engine = new AutomationEngine(jsonLogger(), workingStore({ async recordTerminal() { throw new Error(MULTILINE_DRIVER); }, diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index ada34a2628b..539d6a56941 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -477,9 +477,16 @@ export interface NodeExecutionResult { * 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. + * run's log reaches each child run without the parent's context: at most + * {@link MAX_STEP_CHILD_RUN_IDS} of them, the first ones started, and + * `childRunIdsTruncated` on the step where this execution started more. + * Two bounds of the durable history can still leave a reader without a + * link. A log of more than {@link MAX_PERSISTED_HISTORY_STEPS} steps is + * compacted ({@link compactStepLogForHistory}), which can drop a step + * with its link. And a step log over the history row's byte cap has its + * links shed before any step is dropped, each step that named child runs + * marked `childRunIdsTruncated` (`serializeStepsBounded` in + * `suspended-run-store.ts`). */ childRunIds?: string[]; /** @@ -1020,6 +1027,19 @@ export const DEFAULT_MAX_EXECUTION_LOG_SIZE = 1000; */ export const MAX_PERSISTED_HISTORY_STEPS = 200; +/** + * [ADR-0162 Execution item 8; seat ruling 7258590209 on #37767] Most child + * run ids one step names ({@link StepLogEntry.childRunIds}). A `map` starts + * up to its 10,000-item cap of item runs, and one run id is about 40 + * characters: named whole, one step could carry a run's step log past the + * history row's byte cap and cost the row the steps it keeps. A step whose + * execution started more names the first ones started and carries + * `childRunIdsTruncated: true`, so a reader never takes the list for all of + * them. The same number as the approvals plugin's cap on the runs it reads + * for one approval. + */ +export const MAX_STEP_CHILD_RUN_IDS = 200; + /** * Cap on the in-memory {@link AutomationEngine.consumedSuspensions} journal — * the hot half of the operator restore path (#13909). @@ -1188,10 +1208,20 @@ export interface StepLogEntry { /** * [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. + * declares the member: a `subflow`'s one run, the item runs of a `map`, + * at most {@link MAX_STEP_CHILD_RUN_IDS}. Absent where the step started + * none. */ childRunIds?: string[]; + /** + * [ADR-0162 Execution item 8; seat ruling 7258590209 on #37767] `true` + * where this step started more child runs than `childRunIds` names: its + * execution started more than {@link MAX_STEP_CHILD_RUN_IDS}, or the + * history row shed the step's links to fit its byte cap (`childRunIds` + * is then absent). Absent where the list names every child run the step + * started. + */ + childRunIdsTruncated?: true; /** * #1479: structured-region grouping. When a step ran inside a `loop` / * `parallel` / `try_catch` body region, these tag it with its **immediate** @@ -8072,8 +8102,8 @@ export class AutomationEngine implements IAutomationService { * 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. + * caller that decides on a missing run 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). diff --git a/packages/services/service-automation/src/run-history.ts b/packages/services/service-automation/src/run-history.ts index fd5d3b93930..79ee881efdb 100644 --- a/packages/services/service-automation/src/run-history.ts +++ b/packages/services/service-automation/src/run-history.ts @@ -355,7 +355,7 @@ export async function getRun(this: Pick[1]) { + const engine = withLoaderSetFromPull(new AutomationEngine(createTestLogger(), store)); engine.setFlowActivationStore(new InMemoryFlowActivationStore()); const ctx = { logger: createTestLogger(), getService: () => undefined } as any; for (const register of [registerSubflowNode, registerMapNode, registerWaitNode, registerLogicNodes]) { @@ -61,7 +65,7 @@ const map = (flowName: string, items: unknown[], id = 'each'): Node => ({ id, ty type Eq = (() => G extends A ? 1 : 2) extends () => G extends B ? 1 : 2 ? true : false; type Assert = T; export type _ChildRunIdsInStep = Assert< - Eq, Pick> + Eq, Pick> >; const stepOf = async (engine: AutomationEngine, runId: string, nodeId: string) => @@ -141,3 +145,135 @@ describe('[ADR-0162 item 8] a delegating step records the child runs it started' expect(step.childRunIds, 'the call started no run').toBeUndefined(); }); }); + +/** + * A stand-in for the `sys_automation_run` table, enough for + * {@link ObjectStoreSuspendedRunStore}'s terminal write and read: rows keyed + * by id, `where` by equality. No `delete`, so the write-time retention prune + * is off and every row stays. + */ +function rowTable(): SuspendedRunStoreEngine & { rows: Map } { + const rows = new Map(); + const matches = (row: any, where: Record | undefined) => + !where || Object.entries(where).every(([k, v]) => row[k] === v); + return { + rows, + async find(_object, options) { + const where = options?.where as Record | undefined; + if (where && Object.keys(where).length === 1 && typeof where.id === 'string') { + const row = rows.get(where.id); + return row ? [row] : []; + } + const out = [...rows.values()].filter((r) => matches(r, where)); + return typeof options?.limit === 'number' ? out.slice(0, options.limit) : out; + }, + async insert(_object, data) { + rows.set(String(data.id), { ...data }); + return data; + }, + async update(_object, data, options) { + const id = String(options?.where?.id ?? data.id); + rows.set(id, { ...(rows.get(id) ?? { id }), ...data }); + return rows.get(id); + }, + }; +} + +const flushWrites = () => new Promise((r) => setTimeout(r, 20)); +const runIdLike = (n: number) => `run_${String(n).padStart(8, '0')}-0000-4000-8000-000000000000`; + +describe('[ADR-0162 item 8] the links a step carries are bounded (seat ruling 7258590209)', () => { + it(`a map that starts more item runs than a step names: the first ${MAX_STEP_CHILD_RUN_IDS}, and the step says the list is cut`, async () => { + const engine = rig(); + engine.registerFlow('item', chain('item', [NOOP]) as any); + const items = Array.from({ length: MAX_STEP_CHILD_RUN_IDS + 5 }, (_, i) => ({ id: `rec_${i}` })); + engine.registerFlow('batch', chain('batch', [{ ...map('item', items), config: { flowName: 'item', collection: items, itemObject: 'thing' } }]) as any); + const context = {} as AutomationContext; + expect(((await engine.execute('batch', context)) as any).success).toBe(true); + + const [step] = await stepOf(engine, engine.runStartedFor(context)!, 'each'); + expect(step.childRunIds).toHaveLength(MAX_STEP_CHILD_RUN_IDS); + expect(new Set(step.childRunIds).size).toBe(MAX_STEP_CHILD_RUN_IDS); + expect(step.childRunIdsTruncated).toBe(true); + // The first ones started, in order: the ids name the runs of the first + // items, the first id the first item's run, the last the 200th's. + const first: any = await engine.getRun(step.childRunIds[0]); + const last: any = await engine.getRun(step.childRunIds[MAX_STEP_CHILD_RUN_IDS - 1]); + expect(first?.flowName).toBe('item'); + expect(first?.trigger?.recordId).toBe('rec_0'); + expect(last?.trigger?.recordId).toBe(`rec_${MAX_STEP_CHILD_RUN_IDS - 1}`); + }); + + it(`a map of exactly ${MAX_STEP_CHILD_RUN_IDS} items names them all and is not marked`, async () => { + const engine = rig(); + engine.registerFlow('item', chain('item', [NOOP]) as any); + const items = Array.from({ length: MAX_STEP_CHILD_RUN_IDS }, (_, i) => i); + engine.registerFlow('batch', chain('batch', [map('item', items)]) as any); + const context = {} as AutomationContext; + await engine.execute('batch', context); + const [step] = await stepOf(engine, engine.runStartedFor(context)!, 'each'); + expect(step.childRunIds).toHaveLength(MAX_STEP_CHILD_RUN_IDS); + expect(step.childRunIdsTruncated, 'a whole list carries no mark').toBeUndefined(); + }); + + it('a map of 1,600 items, stored and read back after a restart: the history row keeps every step the run logged', async () => { + // [M5 of review record 7258563513] 1,600 run ids named whole are more + // than the row's 64 KB alone: the row then kept only a tail of the log, + // `end` here, and lost the `map` step with its links. Bounded, the row + // keeps the four steps it kept before steps named their child runs. + const table = rowTable(); + const engine = rig(new ObjectStoreSuspendedRunStore(table, createTestLogger())); + engine.registerFlow('item', chain('item', [NOOP]) as any); + engine.registerFlow('batch', chain('batch', [{ ...NOOP, id: 'prepare' }, map('item', Array.from({ length: 1600 }, (_, i) => i))]) as any); + const context = {} as AutomationContext; + expect(((await engine.execute('batch', context)) as any).success).toBe(true); + const runId = engine.runStartedFor(context)!; + await flushWrites(); + + const restarted = rig(new ObjectStoreSuspendedRunStore(table, createTestLogger())); + const stored: any = await restarted.getRun(runId); + expect(stored?.status).toBe('completed'); + expect(stored.steps.map((s: any) => s.nodeId)).toEqual(['start', 'prepare', 'each', 'end']); + const each = stored.steps[2]; + expect(each.childRunIds).toHaveLength(MAX_STEP_CHILD_RUN_IDS); + expect(each.childRunIdsTruncated).toBe(true); + expect(table.rows.get(`run_${runId}`).steps_json.length).toBeLessThanOrEqual(64 * 1024); + }); +}); + +describe('[ADR-0162 item 8] the history row sheds the links before it drops a step (seat ruling 7258590209)', () => { + const delegating = (n: number): StepLogEntry => ({ + nodeId: `each_${n}`, nodeType: 'map', status: 'success', startedAt: '2026-01-01T00:00:01.000Z', + childRunIds: Array.from({ length: MAX_STEP_CHILD_RUN_IDS }, (_, i) => runIdLike(n * 1000 + i)), + childRunIdsTruncated: true, + }); + const plain = (nodeId: string): StepLogEntry => ({ nodeId, nodeType: 'assignment', status: 'success', startedAt: '2026-01-01T00:00:01.000Z' }); + const record = (steps: StepLogEntry[]): RunRecord => ({ + runId: 'r1', flowName: 'sweep', status: 'completed', startedAt: '2026-01-01T00:00:00.000Z', durationMs: 5, steps, + }); + + it('a log its links carry over the cap: every step is kept, each step that named child runs marked and without them', async () => { + const table = rowTable(); + const store = new ObjectStoreSuspendedRunStore(table, createTestLogger()); + const steps = [plain('start'), ...Array.from({ length: 8 }, (_, n) => delegating(n)), plain('end')]; + expect(JSON.stringify(steps).length, 'the fixture is over the row cap with its links').toBeGreaterThan(64 * 1024); + await store.recordTerminal(record(steps)); + + const kept = (await store.loadTerminal('r1'))!.steps!; + expect(kept.map((s) => s.nodeId), 'the steps a log without links keeps').toEqual(steps.map((s) => s.nodeId)); + for (const s of kept.slice(1, -1)) { + expect(s.childRunIds).toBeUndefined(); + expect(s.childRunIdsTruncated).toBe(true); + } + expect(kept[0].childRunIdsTruncated, 'a step that named no child run is not marked').toBeUndefined(); + expect(kept[kept.length - 1]).toEqual(plain('end')); + }); + + it('a log under the cap keeps its links as they were', async () => { + const table = rowTable(); + const store = new ObjectStoreSuspendedRunStore(table, createTestLogger()); + const steps = [plain('start'), delegating(0), plain('end')]; + await store.recordTerminal(record(steps)); + expect((await store.loadTerminal('r1'))!.steps).toEqual(steps); + }); +}); diff --git a/packages/services/service-automation/src/suspended-run-store.ts b/packages/services/service-automation/src/suspended-run-store.ts index d1743db3cc7..d925cc5eb86 100644 --- a/packages/services/service-automation/src/suspended-run-store.ts +++ b/packages/services/service-automation/src/suspended-run-store.ts @@ -1241,9 +1241,22 @@ function readConsumedSuspensionDropNotice(row: any): ConsumedSuspensionDropNotic * BYTES — a few huge step errors can still blow up a row. When over, the step * tail is halved until it fits (the newest steps carry the failure); an empty * result stores `null`. + * + * [ADR-0162 Execution item 8; seat ruling 7258590209 on #37767] Before any + * step goes, the links to child runs do ({@link shedChildRunIds}): a log + * over the cap is stored without every step's `childRunIds`, each step that + * named child runs marked `childRunIdsTruncated: true`, and only a log still + * over the cap without them is halved. The links are what the log gained + * when steps began to name their child runs, so shedding them first keeps + * the steps a log without them kept; the mark is what keeps a reader from + * taking a step that names no run for one that started none. A mark costs + * 28 bytes on each step it lands on, so a log that fits the cap without its + * links by less than its marks' bytes is halved, where a log that never + * named a child run was not. */ function serializeStepsBounded(steps: RunRecord['steps']): string | null { let tail = steps ?? []; + if (tail.length > 0 && JSON.stringify(tail).length > MAX_STEPS_JSON_BYTES) tail = tail.map(shedChildRunIds); while (tail.length > 0) { const json = JSON.stringify(tail); if (json.length <= MAX_STEPS_JSON_BYTES) return json; @@ -1252,6 +1265,18 @@ function serializeStepsBounded(steps: RunRecord['steps']): string | null { return null; } +/** + * [ADR-0162 Execution item 8] One step without its links to child runs, for + * {@link serializeStepsBounded}: a step that named any carries + * `childRunIdsTruncated: true` in their place; any other step is returned as + * it was. + */ +function shedChildRunIds(step: NonNullable[number]): NonNullable[number] { + if (!Array.isArray(step?.childRunIds) && step?.childRunIdsTruncated !== true) return step; + const { childRunIds: _shed, ...rest } = step; + return { ...rest, childRunIdsTruncated: true }; +} + /** * JSON-encode a run summary under {@link MAX_SUMMARY_JSON_BYTES} (#4354). * diff --git a/packages/spec/src/automation/execution.zod.ts b/packages/spec/src/automation/execution.zod.ts index 128e0e42b90..fa1aae8b0ed 100644 --- a/packages/spec/src/automation/execution.zod.ts +++ b/packages/spec/src/automation/execution.zod.ts @@ -221,7 +221,12 @@ export const ExecutionStepLogSchema = lazySchema(() => z.object({ // 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'), + .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, at most 200, the first ones started. Absent for a step that started none, and where `childRunIdsTruncated` says the links were shed'), + // [ADR-0162 Execution item 8] Seat ruling 7258590209 on #37767: the list is + // bounded, and a step whose list is not whole says so, so a reader never + // takes a cut list, or a missing one, for every child run the step started. + childRunIdsTruncated: z.literal(true).optional() + .describe('Set when this step started more child runs than `childRunIds` names: its execution started more than 200, or the run\'s history row shed the step\'s links to fit its size limit, leaving `childRunIds` absent. Absent when `childRunIds` names every child run the step started'), })); export type ExecutionStepLog = z.input; From 99f6e9a9faa670e1bab7086b3b1d07cb4decb263 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 00:19:13 +0000 Subject: [PATCH 3/7] test(automation): pin the bounded step links, the shed at the history row and the strict read (ADR-0162 item 8) Claude-Session: https://claude.ai/code/session_01JQwxbaoxpe1tyHuqnsAUFB Co-authored-by: Claude --- .../service-automation/src/step-child-runs.test.ts | 9 +++++---- packages/spec/authorable-surface/automation.json | 1 + 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/services/service-automation/src/step-child-runs.test.ts b/packages/services/service-automation/src/step-child-runs.test.ts index f36ed95b13e..9f91691be7f 100644 --- a/packages/services/service-automation/src/step-child-runs.test.ts +++ b/packages/services/service-automation/src/step-child-runs.test.ts @@ -218,9 +218,10 @@ describe('[ADR-0162 item 8] the links a step carries are bounded (seat ruling 72 it('a map of 1,600 items, stored and read back after a restart: the history row keeps every step the run logged', async () => { // [M5 of review record 7258563513] 1,600 run ids named whole are more - // than the row's 64 KB alone: the row then kept only a tail of the log, - // `end` here, and lost the `map` step with its links. Bounded, the row - // keeps the four steps it kept before steps named their child runs. + // than the row's 64 KB alone: halving the log from its head reached + // the `map` step, the last one logged, and the row stored no step at + // all. Bounded, the row keeps the three steps it kept before steps + // named their child runs (an `end` node logs no step). const table = rowTable(); const engine = rig(new ObjectStoreSuspendedRunStore(table, createTestLogger())); engine.registerFlow('item', chain('item', [NOOP]) as any); @@ -233,7 +234,7 @@ describe('[ADR-0162 item 8] the links a step carries are bounded (seat ruling 72 const restarted = rig(new ObjectStoreSuspendedRunStore(table, createTestLogger())); const stored: any = await restarted.getRun(runId); expect(stored?.status).toBe('completed'); - expect(stored.steps.map((s: any) => s.nodeId)).toEqual(['start', 'prepare', 'each', 'end']); + expect(stored.steps.map((s: any) => s.nodeId)).toEqual(['start', 'prepare', 'each']); const each = stored.steps[2]; expect(each.childRunIds).toHaveLength(MAX_STEP_CHILD_RUN_IDS); expect(each.childRunIdsTruncated).toBe(true); diff --git a/packages/spec/authorable-surface/automation.json b/packages/spec/authorable-surface/automation.json index d864d2b4c2e..0fc1f645e2b 100644 --- a/packages/spec/authorable-surface/automation.json +++ b/packages/spec/authorable-surface/automation.json @@ -162,6 +162,7 @@ "automation/ExecutionLog:waitMs", "automation/ExecutionStepLog:branch", "automation/ExecutionStepLog:childRunIds", + "automation/ExecutionStepLog:childRunIdsTruncated", "automation/ExecutionStepLog:completedAt", "automation/ExecutionStepLog:droppedFields", "automation/ExecutionStepLog:durationMs", From 57d21b78b7e2a226381a10a0ea19f9fb1f4042c7 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 00:23:47 +0000 Subject: [PATCH 4/7] docs(automation): the bound and the shed in the changesets and the reference page (ADR-0162 item 8) Claude-Session: https://claude.ai/code/session_01JQwxbaoxpe1tyHuqnsAUFB Co-authored-by: Claude --- .changeset/37767-step-child-runs.md | 8 +++++--- .changeset/37767-step-log-child-runs-spec.md | 6 +++--- content/docs/references/automation/execution.mdx | 6 ++++-- 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/.changeset/37767-step-child-runs.md b/.changeset/37767-step-child-runs.md index b6d5285a8df..fb072d0c442 100644 --- a/.changeset/37767-step-child-runs.md +++ b/.changeset/37767-step-child-runs.md @@ -7,10 +7,12 @@ feat(automation): a delegating step records the child runs it started (ADR-0162 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`). +Widened: `AutomationEngine` gains the public read `runStartedFor(context)` and an optional second argument to `getRun(runId, { strict })`; a node executor's result (`NodeExecutionResult`) gains the optional `childRunIds`, and the exported step type (`StepLogEntry`) gains the optional `childRunIds` and `childRunIdsTruncated`, which the engine writes onto the step's log entry (`ExecutionStepLogSchema`, 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. +- **`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. `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. +- **A step names at most 200 child runs.** A `map` can start up to 10,000 item runs. A step whose execution started more than 200 names the first 200 started and carries `childRunIdsTruncated: true`, so a reader never takes the list for all of them. +- **What the durable history keeps of the links.** A log of more than 200 steps is compacted for history: it keeps every top-level step and every failure while those number 200 or fewer, and otherwise the most recent 200 of them, so compaction can drop a step with its link. A terminal run's step log over the history row's 64 KB cap is stored without every step's `childRunIds`, each step that named child runs marked `childRunIdsTruncated: true`, before any step is dropped; only a log still over the cap without them is halved from its head, as before. A mark costs 28 bytes on each step it lands on, so a log that fits the cap without its links by less than its marks' bytes is halved where a log that never named a child run was not. - **`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. +Unchanged: what a run does, the `runId` the contract returns, every existing step field, and which steps a run's history row keeps, but for the marks' bytes above. diff --git a/.changeset/37767-step-log-child-runs-spec.md b/.changeset/37767-step-log-child-runs-spec.md index f374bafc8ea..1ed247148c4 100644 --- a/.changeset/37767-step-log-child-runs-spec.md +++ b/.changeset/37767-step-log-child-runs-spec.md @@ -2,10 +2,10 @@ '@objectstack/spec': minor --- -feat(spec): a run's step log names the child runs a step started (`ExecutionStepLogSchema.childRunIds`, ADR-0162 Execution item 8) +feat(spec): a run's step log names the child runs a step started (`ExecutionStepLogSchema.childRunIds`, `childRunIdsTruncated`, 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 +Skills-docs: none — `skills/` names none of `ExecutionStepLog`, `childRunIds`, `childRunIdsTruncated` or `runStartedFor` (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. +Widened: `ExecutionStepLogSchema` gains two optional keys. `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, at most 200, the first ones started. Absent for a step that started none. `childRunIdsTruncated: true`: the step started more child runs than `childRunIds` names, either more than 200, or the run's history row shed the step's links to fit its size limit, leaving `childRunIds` absent. The engine writes both (`@objectstack/service-automation`); a reader of `getRun` can walk a run's tree from its root with them. Nothing an author writes in a flow changes. diff --git a/content/docs/references/automation/execution.mdx b/content/docs/references/automation/execution.mdx index d9353cc41f5..8f402a0cbf2 100644 --- a/content/docs/references/automation/execution.mdx +++ b/content/docs/references/automation/execution.mdx @@ -150,7 +150,8 @@ 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 | +| **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, at most 200, the first ones started. Absent for a step that started none, and where `childRunIdsTruncated` says the links were shed | +| **childRunIdsTruncated** | `true` | optional | Set when this step started more child runs than `childRunIds` names: its execution started more than 200, or the run's history row shed the step's links to fit its size limit, leaving `childRunIds` absent. Absent when `childRunIds` names every child run the step started | ### Nested Shape: `ExecutionLog.summary` @@ -211,7 +212,8 @@ 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 | +| **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, at most 200, the first ones started. Absent for a step that started none, and where `childRunIdsTruncated` says the links were shed | +| **childRunIdsTruncated** | `true` | optional | Set when this step started more child runs than `childRunIds` names: its execution started more than 200, or the run's history row shed the step's links to fit its size limit, leaving `childRunIds` absent. Absent when `childRunIds` names every child run the step started | ### Nested Shape: `ExecutionStepLog.error` From 348f0945e4923282c5b6166f7c8043bd817a3c87 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 00:35:57 +0000 Subject: [PATCH 5/7] test(automation): the history-row double updates by id, as ObjectQL does, and the ledger records its pin (ADR-0162 item 8) Claude-Session: https://claude.ai/code/session_01JQwxbaoxpe1tyHuqnsAUFB Co-authored-by: Claude --- .../services/service-automation/src/step-child-runs.test.ts | 6 +++++- scripts/engine-double-contract.pinned.json | 5 +++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/packages/services/service-automation/src/step-child-runs.test.ts b/packages/services/service-automation/src/step-child-runs.test.ts index 9f91691be7f..e58c5437aa2 100644 --- a/packages/services/service-automation/src/step-child-runs.test.ts +++ b/packages/services/service-automation/src/step-child-runs.test.ts @@ -25,6 +25,7 @@ import type { AutomationContext } from '@objectstack/spec/contracts'; import type { ExecutionStepLog } from '@objectstack/spec/automation'; import type { RunRecord, StepLogEntry } from './engine.js'; import { withLoaderSetFromPull } from './loader-set.test-support.js'; +import { assertEngineUpdateDispatch } from '@objectstack/metadata-core'; function createTestLogger(): any { const l: any = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; @@ -172,7 +173,10 @@ function rowTable(): SuspendedRunStoreEngine & { rows: Map } { return data; }, async update(_object, data, options) { - const id = String(options?.where?.id ?? data.id); + // As strict as `ObjectQL.update`: the store updates its row by id. + const dispatch = assertEngineUpdateDispatch(data, options); + if (dispatch.kind !== 'by-id') throw new Error('rowTable: an update by id only'); + const id = String(dispatch.id); rows.set(id, { ...(rows.get(id) ?? { id }), ...data }); return rows.get(id); }, diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index 37a689920f6..e8bd532256c 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -5961,6 +5961,11 @@ "verb": "findOne", "pinned": 1 }, + { + "file": "packages/services/service-automation/src/step-child-runs.test.ts", + "verb": "update", + "pinned": 1 + }, { "file": "packages/services/service-automation/src/stranded-run-object-store.test.ts", "verb": "delete", From ee8203b011823e22cbfb721c89fa60b455a56689 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 01:06:14 +0000 Subject: [PATCH 6/7] test(automation): the history-row double refuses an operator it does not implement (ADR-0162 item 8) Claude-Session: https://claude.ai/code/session_01JQwxbaoxpe1tyHuqnsAUFB Co-authored-by: Claude --- .../service-automation/src/step-child-runs.test.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/packages/services/service-automation/src/step-child-runs.test.ts b/packages/services/service-automation/src/step-child-runs.test.ts index e58c5437aa2..6cae20b790f 100644 --- a/packages/services/service-automation/src/step-child-runs.test.ts +++ b/packages/services/service-automation/src/step-child-runs.test.ts @@ -155,8 +155,14 @@ describe('[ADR-0162 item 8] a delegating step records the child runs it started' */ function rowTable(): SuspendedRunStoreEngine & { rows: Map } { const rows = new Map(); + // Equality only: an operator or a combinator is refused, never read as a + // field name. const matches = (row: any, where: Record | undefined) => - !where || Object.entries(where).every(([k, v]) => row[k] === v); + !where || Object.entries(where).every(([k, v]) => { + if (k.startsWith('$')) throw new Error(`rowTable: unsupported combinator ${k}`); + if (v !== null && typeof v === 'object') throw new Error(`rowTable: unsupported operator on ${k}`); + return row[k] === v; + }); return { rows, async find(_object, options) { From 875b62d0c2ccdbfdf8be5a6e1d5082ff4df19967 Mon Sep 17 00:00:00 2001 From: "objectstack-fleet[bot]" <332303061+objectstack-fleet[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:15:54 +0800 Subject: [PATCH 7/7] fix(approvals): the reconciler keeps a run as ended only with every child read, and reaches a decision in a child run (ADR-0162 item 8) (#38634) --- .changeset/37767-reconciler.md | 29 + content/docs/automation/approvals.mdx | 156 +- .../plugins/plugin-approvals.md | 16 +- ...roval-reconciler-37767.integration.test.ts | 1748 +++++++++++++++++ .../plugin-approvals/src/approval-service.ts | 1680 ++++++++++++++-- .../plugin-approvals/src/approvals-plugin.ts | 4 + .../src/translations/messages.ts | 22 + .../src/preference-options.ts | 1 + 8 files changed, 3509 insertions(+), 147 deletions(-) create mode 100644 .changeset/37767-reconciler.md create mode 100644 packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts diff --git a/.changeset/37767-reconciler.md b/.changeset/37767-reconciler.md new file mode 100644 index 00000000000..8c77832acc2 --- /dev/null +++ b/.changeset/37767-reconciler.md @@ -0,0 +1,29 @@ +--- +'@objectstack/plugin-approvals': patch +'@objectstack/service-messaging': patch +--- + +feat(approvals): the reconciler, and the door reads every run of an approval (ADR-0162 Execution item 8) + +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` and `childRunIdsTruncated`, the run's `trigger`, `completedAt` and `summary`, and an optional `{ strict }` read; the plugin's message catalog gains `approvalFlowNotContinuedTitle` and `approvalFlowNotContinuedBody` in all 11 locale packs, sent to the organization's administrators on the topic `approval.flow_not_continued`; `PLATFORM_NOTIFICATION_TOPICS` of `@objectstack/service-messaging`, the topics a notification preference may name, gains that topic. + +Only for an approval the check stamped when it opened (one with a step that can act on an object that declares `closedStates`): + +- **The door reads every run of the approval.** Where it read the run that carries the record and the latest request's own run, it now walks the tree from the run that carries the record, following the child runs each delegating step records: every `subflow` child, and every `map` item run that does not carry another record (an item that is a record carries an approval of its own). It reads the whole tree before it answers, and one run decides for the whole approval: one that the store could not answer for, or that reports a status of a run in motion (`pending`, `running`, `retrying`), makes it cannot tell; otherwise one parked at a node a step can follow, in progress; otherwise one that ended between two steps, abandoned. A run parked at such a node on a child run says what its child says, so the walk reads the child, at any depth. The automation engine reports none of those three statuses for a flow run today: a run it is advancing reads as paused with its pause gone, or as a run with no row, and is held by the rule for a run that stopped, below. So a sibling child whose failure the flow routed, a middle run two levels down that failed, an item run that failed before its step, and a run between two others that is being advanced are no longer read as finished. A failure routed to a pause no step follows is read as abandoned, as on the base. A stop is answered where a request of the approval opened after it. One judgement reads at most 200 runs beside those it kept as ended: past them it is cannot tell, keeps what it read, and the next judgement reads on. That has an end: once the approval's marks have stood for the hour of the age bound, a judgement reads on only while it keeps a run the approval had not kept (the kept list holds 200 runs), and the judgement that keeps none places the approval by the step last decided, below. Two costs come with that rule. A tree the judgements cannot finish is placed without being finished, and from about 399 runs a tree can be one no judgement finishes: the walk reads the runs it starts from before the runs below them, so for a `map` of 199 items that each call a `subflow`, every judgement reads the run and its 199 items and none of the runs below them. And the placement follows from the shape of the flow, so an approval submitted again on the same flow can meet the same end: the remedy is the flow's, not the submitter's. Reading on can take up to 200 further visits of the reconciler after the hour: one each sweep (every 5 minutes by default, the plugin's `escalationScanIntervalMs`), or one each turn of its walk where more requests are marked than one sweep reads. A run parked on a child run that such a judgement did not get to says nothing of its own, and the child a parked run waits on is read next, before the runs beside it. +- **The plugin keeps what it read.** At every door, one that leaves the next request pending included, and as each request opens, the approval's latest request keeps, in its config snapshot (`__runsRead`): the runs that are not read again (`ended`), the runs read to their end over a child run that was not (`open`), a failure between two steps found in a run that ended, and the states the last judgement read that say a run has stopped (`stood`), which the rule for a run that stopped uses, below. A run is kept as ended only once it was read to an end and every child run its steps name is kept as ended too. So a child whose read failed, a child with no row, and the runs past the 200 one judgement reads are read on the next pass, which starts from the open runs as well. A run that a stored step names and that a pass did not read is never left out without a word: it is read on a later pass, it counts as passed by the rule below, or the approval is cannot tell and then placed. A run that no stored step names any more is not covered by that: see the limit of this release, below. A run the plugin read before the automation engine trimmed its history is not needed again, so an approval whose refused outcome is tried again after its run's history went is judged as it would have been. +- **A run with no row, under a run that went on past it, is passed.** A run the engine has no row for counts as passed, and is kept as ended, where a run the plugin read went on past the step that names it: that step succeeded, and the run reached an end of its flow, or logged a later step and is not parked at that step. So an early child run trimmed before the plugin read it does not hold the approval back. A step that failed is never passed, also where the flow routed the failure and went on. A run the plugin had read to its end over an unread child, and whose own row is gone since, is not passed either: nothing names that child any more. +- **A step log the engine marked, or the history row cut, is cannot tell.** Two logs are read as cut, and are not judged from as they stand: one with a step that carries the engine's mark `childRunIdsTruncated` (its execution started more child runs than the 200 a step names, or the history row shed the step's list to fit its size), and the log of a run that ended whose history row keeps fewer steps than the run logged (the row bounds the log by bytes, to a tail of it or to none, while the run's summary still counts every step). Within the age bound nothing is written; past it the approval is placed by the step last decided, as for a run with no row, below. A run whose log is cut is not kept as ended, the child runs it does name are still read, and it speaks for none of them: no run it names counts as passed. A summary that is absent or dropped its per-node detail gives nothing to compare, and reads as cut. +- **The limit of this release: a log that loses whole steps carries no mark (ruling 7268216330 on #37767).** The engine marks one thing: a step whose child-run links were shed carries `childRunIdsTruncated`, above. A log that loses whole steps carries no mark, whichever way it loses them: the engine's compaction of a log of more than 200 steps, the history row's halving of a log over its 64 KB cap, a row stored as null. The plugin reads what the log kept, and a child run named only by a dropped step reads as one the run went past: it is not read. For a halved row and a null row the plugin can still tell that steps are missing, from the run's summary, which counts every step: that is the second log read as cut, above, and the approval is held and then placed. For a compacted log it cannot tell. A run that logged more than 200 steps is stored with 200 of them: every top-level step and every failed step, then the most recent of the rest (the most recent 200 of the top-level and failed steps, where those alone pass 200), and it is judged from those, as before this change. What an operator gets in that case: a `subflow` or `map` step the compaction dropped (one that succeeded inside a `loop`, `parallel` or `try_catch` region, or an early step of a very long run) no longer names the child runs it started; a failure the flow routed inside such a child run, between two steps, is not seen; and the approval can be written as finished, with no notice and no line in the log. A process that still holds the run in memory reads its whole log, so this is a judgement made once that process is gone. No approval is judged worse than before this change, whose door read no child run. +- **The kept reading is its own key.** It is written onto the snapshot read again just before the write, and only while the column still reads the same, at most three times. It cannot write a stale snapshot over a note another writer left there (`__laterStepNotOpened`, `__strandedContinuation`). The judgement reads the note that a later step could not open once it has read the runs, so a note that lands while they are read is judged with. +- **A run that stopped, placed by the step last decided.** A run the engine has no row for and that no run the plugin read speaks for (its history is gone, or a process stopped while advancing it), a run whose step log is cut, above, a tree of more runs than the judgements can read in full, above, and the latest request's own run still parked at the step its decision was recorded on (a process stopped before the run was resumed), in the run that carries the record or in a child run any number of levels below it, are cannot tell for an hour from the approval's marks (the age bound). Past it, each has stopped at the step last decided once two judgements in a row read it in the same state, for the same run. The hour is counted from the marks and not from the run's last movement, and a run the engine is resuming reads as paused with its pause gone or as a run with no row; so an approval whose flow waits longer than the hour between two steps by design (a `wait` node, a batch over records whose items are approved one by one, a child run parked outside the approval's steps) is past the bound whenever it resumes. Only an approval that holds nothing back can wait so: the check at its opening refuses each of the three between two steps of an approval on a field its object closes on. There a placement ends the hold and writes nothing. The judgement that reads a run in such a state first therefore does not place it (it cannot tell, and a run parked on a child that has ended is in progress), and keeps the state it read (`stood` in `__runsRead`); the next judgement places the run if it reads the same, and reads it anew if it does not. A judgement within the hour keeps what it read as well, a door's included, so an approval read in that state within the hour is placed by the first visit past it, and one that was not takes one visit more. A reading that could not be kept leaves on the request the reading kept before it: the next judgement stands on that earlier one, so a state kept earlier can still count, and where none was kept nothing is placed. An approval whose reading is never kept is therefore held with no end. Two passes that each fall inside a resume of the same run still read it as stopped. Whether a later step can follow that step is asked in the flow its request records, so a node of another flow that carries the step's id does not answer for it. Where one can, the approval is abandoned: the record is put back, the submitter is told and submits again, the decisions already made stay on their requests, and a run still parked there is cancelled, with the runs that wait on it up to the run that carries the record, through a `map` whose items are not records as through a `subflow`. The cancel follows the put-back, and is not tried again once the put-back has landed: where it fails, or the process stops between the two, the run stays parked, the approval stays abandoned, and the door that continues a restored run refuses it. At the last step, the outcome is written and, once that write has landed, the administrators are told that the flow could not be seen through to its end after that step; the run's pause is left for an operator. A refused write sends no such notice, and the pass on which the write lands sends it. The notice says what to do in each case: continue or cancel a run that is still paused, and where the run has ended or no run is left, check that the steps after the decision were done. An approval placed for a cut log or a tree too large to read can be one whose flow did go on, which the plugin could not read in full: at its last step the administrators get the notice for a flow that ran, and where a later step can follow, the submitter submits again. +- **The reconciler.** Each pass reads two windows of at most 200 marked requests (`unjudged_since`): the oldest marks, and the next page of a walk over every marked request by id, so that marks which stay cannot keep the newer ones from being read. It judges each approval among them once, as the door would have: it writes the outcome in the name of the request's recorded decider, abandons the approval, or, where nothing was held back, clears the mark and writes nothing (where it concluded that a run had stopped, a line in the log says so). It ends what no door saw: a run that was cancelled, a parent run cancelled while its child's request was pending, and the stopped runs above. Past the age bound it also reads as stopped where it stood a run that reports paused while its pause is gone, and a run parked at a `subflow` or a `map` whose child run has ended or has no row, each once two judgements in a row read it so, as above. The item run of a `map` whose items are records is such a child once it is in a terminal status: its steps are an approval of the item's own record and are not read, only whether it has ended, and it is kept as ended only once it has. +- **A refused write is tried again.** A refused outcome or put-back leaves the marks, and the next pass tries it again. The timeline line and the administrators' notice (keyed per request and status) are left once for one refusal; the same holds for the line an abandoned approval leaves. +- **A deleted record.** Where the approval's record was deleted, the reconciler clears the marks of its requests and writes nothing: no retry and no notice. +- **The stranded-request report** (`inspectStrandedRequests`) leaves a decided request the check stamped to the door and the reconciler, and still reports a returned one. + +- **A refusing end is an end.** The door reads a run that reached an end of the flow as having ended there, a refusing end (`outcome: 'refused'`) included, as it already did for a completed run. + +Unchanged: an object that declares no `closedStates`; an approval that opened before its object declared the key. diff --git a/content/docs/automation/approvals.mdx b/content/docs/automation/approvals.mdx index 3639c51f278..6a653c29d05 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,148 @@ 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. A run parked there on a child run counts + as what its child run is. Nothing is written. +- **Ended between two steps.** A run stopped on a node a step could still follow + (it failed or was cancelled there), a failure the flow routed at the top level + of a run ended it, to an end or to a pause no step follows, or a later step + 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, one that leaves the next request pending included, and as each request +opens: the runs it read to their end, and a failure between two steps it found +in one. A run is not read again once it, and every run its steps started, were +read to their end. Until then it is read again at the next action or sweep, so +a run that a stored step lists, and that the platform could not read once, is +not passed over later. One reading takes at most 200 runs beside those it does +not read again; a larger tree cannot tell on that reading and is read on at the +next. That has an end: once the approval's marks have stood for an hour, the +platform reads on only while a reading adds to the runs it does not read again +(it keeps at most 200 of them), and the reading that adds none places the +approval by the step last decided, below. Two costs come with that. An approval +whose runs the platform cannot finish reading is placed without having been +read to its end, and that can begin at about 399 runs: for a `map` step of 199 +items that each call a `subflow`, every reading takes the run and its 199 item +runs, and never the runs below them. And the cause is the shape of the flow, so +the same approval submitted again can meet the same end: give one approval +fewer runs to read, because submitting again does not help. Reading on can take +up to 200 further visits after the hour. The reconciler visits an approval once +a sweep, every five minutes by default (the plugin's `escalationScanIntervalMs`), +or once a turn of its walk where more requests are marked than one sweep reads, +below. + +The platform trims every flow's run history in time. A run it read before that +is not needed again. A run it never read counts as passed where the history of +a run it did read shows that the flow went on past the step that started it: +that step succeeded, and the flow reached an end or went on to a later step. +Such a run does not hold the approval. A step that failed does not count, also +where the flow routed the failure and went on. + +Four more states cannot tell at first: a run with no history left to read, +which the platform never read and which no run it read went on past (a process +stopped while it was advancing it); a run whose history does not list every run +its steps started (a `map` step that started more than 200 item runs, or a step +history that lost steps, or the lists of the runs its steps started, to its +size limit when it was stored); an approval with more runs than the platform +can read in full, above; +and a decided request whose run is still parked at that request's own step (a +process stopped before the run was resumed), in the run that carries the record +or in a `subflow` or `map` run below it. An hour after the approval's marks +were set, each has stopped at the step last decided, once two checks in a row +find it in the same state. The hour is counted from the marks, not from when +the run last moved, and a run the platform is resuming at that moment looks +like one a stopped process left: a run with no history to read, or a paused run +with nothing to resume it. An approval can wait longer than an hour between two +steps by design (a `wait` node, a batch of records approved one by one) only +where none of its steps is concerned: the flow conditions above refuse both for +one that is. Such an approval holds nothing back, and it is past the hour +whenever it resumes. So the check that first finds a run in such a state only +notes it, and the next check places the run if it finds the same. A check made +within the hour counts as the first, so this adds one visit of the reconciler, +and only where the check before did not find the same: one sweep, five minutes +at the default interval, or one turn of the walk where more requests are marked +than one sweep reads. Where a later step could +follow that step, the approval is abandoned, above, and a run still parked +there is cancelled, with the runs that wait on it, so nothing resumes it; the +decisions already made stay on their requests, and the submitter submits again. +The cancel is not tried again once the record is put back: where it fails, the +run stays parked, the approval stays abandoned, and continuing that run is +refused. Where the step was the last, its decision is written and, once it is +on the record, the organization's +administrators are told that the flow could not be seen through to its end +after that step (the notice `approval.flow_not_continued`). The run's pause is left: where the run is still +paused, an operator can continue the flow's remaining nodes or cancel the run; +where it has ended or no run is left, check that the steps after the decision +were done. A write that a rule or a hook refuses sends no such notice; the +notice goes out with the write that lands. An approval placed for a history +that does not list every run, or for more runs than the platform can read, can +be one whose flow did go on: the platform could not read it in full, so the +notice asks for a check and does not state a failure. + +A step history that loses whole steps carries no mark of it; this is a limit +of this release (ruling 7268216330 on #37767). The platform marks one thing: a +step that lost the list of the runs it started. Whole steps are lost in three +ways: a run that logged more than 200 steps is stored with 200 of them (its +top-level steps and its failed steps first, then the most recent of the rest); +a history over its 64 KB limit is stored as its most recent steps; and one that +still does not fit is stored with none. The platform reads what the history +kept, and a run named only by a step that was dropped reads as one the flow +went past: it is not read. In the last two cases the platform can still tell, +from the run's count of its steps, that steps are missing, and treats the +history as one that does not list every run, above. In the first it cannot. A +`subflow` or `map` step that is not among the 200 (one that succeeded inside a +`loop`, `parallel` or `try_catch`, or an early step of a very long run) no +longer lists the runs it started: a failure the flow routed inside one of them +is not seen, and the approval can be written as finished, with no notice. A +process that still holds the run in memory reads all of its steps. For a flow +whose run can log more than 200 steps and that starts child flows inside such a +region, read the outcome of those child runs in the flow's run history as well. + +Every decision on an approval any step of which can act on an object that +declares `closedStates` leaves a mark on its request (`unjudged_since`), also +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, each once two sweeps in a row find it +so. That holds for a `map` over records too: +the platform does not read such an item run's steps, which belong to the item's +own approval, only whether the run has ended. +Where nothing was held back it clears the mark and writes nothing; where it +concluded that a run had stopped, a line in the server log says so. A write that +a rule or a hook refuses is reported as above, once, and tried again on each +sweep while the mark stands. Where the record was deleted, the reconciler clears +the mark and writes nothing. + ## Why Separating *who configures* from *who approves* from *as whom it runs* is the same capability/assignment/requirement decoupling as the rest of authorization (ADR-0066). The `runAs` default of `user` means an approval flow can't silently grant the submitter cross-tenant or cross-owner reach — elevation is opt-in and auditable. That is the safe-by-default posture: the common case respects RLS; the elevated case is explicit. diff --git a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-approvals.md b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-approvals.md index 607d59f8519..45b009061f5 100644 --- a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-approvals.md +++ b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-approvals.md @@ -14,24 +14,24 @@ a row or a number here — fix the code, or the census, and regenerate. | Measure | Value | |---|---:| -| Write call sites | 49 | -| Object name statically decidable | 47 | +| Write call sites | 50 | +| Object name statically decidable | 48 | | Object name chosen at run time | 2 | -| Object name spelled inline | 45 | +| Object name spelled inline | 46 | | Object name spelled through a `const` | 2 | | Object name is an `object: string` parameter | 1 | | Object name is some other run-time expression | 1 | -| Against a tenancy-enabled object | 47 | +| Against a tenancy-enabled object | 48 | | Against an object declaring tenancy off | 0 | -| Threading a tenant context | 49 | +| Threading a tenant context | 50 | | Provably carrying none (options read, no context key) | 0 | | …and decidably tenancy-enabled | 0 | | Options argument unreadable | 0 | | …and decidably tenancy-enabled | 0 | -| Threading a decidably elevated (`isSystem`) context | 47 | +| Threading a decidably elevated (`isSystem`) context | 48 | | Threading a decidably non-elevated context | 0 | | Threading a context of undecidable elevation | 2 | -| Receiver carried a readable engine type | 49 | +| Receiver carried a readable engine type | 50 | | Receiver erased, placed by the object NAME | 0 | | Receiver erased, placed by an `object: string` PARAMETER | 0 | | Receiver erased, placed by an `UNTYPED_RECEIVERS` row | 0 | @@ -54,7 +54,7 @@ a row or a number here — fix the code, or the census, and regenerate. | `packages/plugins/plugin-approvals/src/approval-service.ts` | `delete` | `sys_approval_approver` | enabled | elevated | 2 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_approver` | enabled | elevated | 2 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_request` | enabled | elevated | 1 | -| `packages/plugins/plugin-approvals/src/approval-service.ts` | `update` | `sys_approval_request` | enabled | elevated | 14 | +| `packages/plugins/plugin-approvals/src/approval-service.ts` | `update` | `sys_approval_request` | enabled | elevated | 15 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `insert` | `sys_approval_token` | enabled | elevated | 1 | | `packages/plugins/plugin-approvals/src/approval-service.ts` | `update` | `sys_approval_token` | enabled | elevated | 1 | | `packages/plugins/plugin-approvals/src/backfill-platform-row-organizations.ts` | `update` | `objectPlan.object` | undecidable | context, elevation undecidable | 1 | diff --git a/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts new file mode 100644 index 00000000000..7f4424c4dad --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts @@ -0,0 +1,1748 @@ +// 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, MAX_PERSISTED_HISTORY_STEPS, type AutomationEngine } from '@objectstack/service-automation'; +import { ApprovalService, HISTORY_STEPS_KEPT, MAX_RUNS_READ_PER_APPROVAL, RECONCILER_AGE_BOUND_MS } from './approval-service.js'; +import { registerApprovalNode } from './approval-node.js'; +import { SysApprovalRequest } from './sys-approval-request.object.js'; +import { SysApprovalAction } from './sys-approval-action.object.js'; +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')]), + // ── The fixtures of the rebuild on contract review 7257527251 ── + // A child that fails, unrouted. + flow('child_fail', [mark('boom')], [edge('start', 'boom'), edge('boom', 'end')]), + // The only step, then a child that fails: the run fails at `sub`, after its last step. + flow('fail_after_last', [step('only', 'approver'), { id: 'sub', type: 'subflow', label: 'Sub', config: { flowName: 'child_fail' } }, mark('after')], + [edge('start', 'only'), edge('only', 'sub', 'approve'), edge('only', 'end', 'reject'), edge('sub', 'after'), edge('after', 'end')]), + // The same, with the child's failure routed on: the run goes on along the fault edge and completes. + flow('fault_after_last', [step('only', 'approver'), { id: 'sub', type: 'subflow', label: 'Sub', config: { flowName: 'child_fail' } }, mark('after')], + [edge('start', 'only'), edge('only', 'sub', 'approve'), edge('only', 'end', 'reject'), edge('sub', 'after'), edge('sub', 'after', undefined, 'fault'), edge('after', 'end')]), + // A child between the two steps, which ends inside the passage. + flow('sub_between', [step('first', 'approver'), { id: 'mid', type: 'subflow', label: 'Mid', config: { flowName: 'child_noop' } }, step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'mid', 'approve'), edge('first', 'end', 'reject'), edge('mid', 'second'), ...decided('second', 'end')]), + // Two levels down: the root delegates to a middle run, which delegates the first step; the second step is the root's. + flow('mid_one_step', [{ id: 'inner', type: 'subflow', label: 'Inner', config: { flowName: 'child_one_step' } }], [edge('start', 'inner'), edge('inner', 'end')]), + flow('root_mid_then_second', [{ id: 'mid', type: 'subflow', label: 'Middle', config: { flowName: 'mid_one_step' } }, step('second', 'approver2')], + [edge('start', 'mid'), edge('mid', 'second'), ...decided('second', 'end')]), + // A root above the two sibling children: the middle run ends over a child the plugin may not have read. + flow('root_of_two_subs', [{ id: 'mid', type: 'subflow', label: 'Middle', config: { flowName: 'parent_two_subs' } }], [edge('start', 'mid'), edge('mid', 'end')]), + // A map whose two items are not records: each item's step is a step of the parent's record. + flow('first_then_two_items', [step('first', 'approver'), { id: 'each', type: 'map', label: 'Each', config: { flowName: 'child_boom_then_step', collection: [1, 2] } }], + [edge('start', 'first'), edge('first', 'each', 'approve'), edge('first', 'end', 'reject'), edge('each', 'end')]), + // ── The fixtures of the rework on contract review 7266979193 ── + // A map whose items are records, between two steps: each item's step is an approval of the item's own record. + flow('first_then_records', [step('first', 'approver'), + { id: 'each', type: 'map', label: 'Each', config: { flowName: 'child_one_step', collection: [{ id: 'm_line_1' }, { id: 'm_line_2' }], itemObject: 'crm_memo' } }, + step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'each', 'approve'), edge('first', 'end', 'reject'), edge('each', 'second'), ...decided('second', 'end')]), + // The only step, then a map of one item more than the engine names on a step; the items are not records. + flow('only_then_fan', [step('only', 'approver'), + { id: 'fan', type: 'map', label: 'Fan', config: { flowName: 'child_noop', collection: Array.from({ length: 201 }, (_, i) => i) } }], + [edge('start', 'only'), edge('only', 'fan', 'approve'), edge('only', 'end', 'reject'), edge('fan', 'end')]), + // A child between the two steps, one of whose nodes carries the id of the parent's last step. + flow('child_named_final', [mark('final')], [edge('start', 'final'), edge('final', 'end')]), + flow('gate_sub_final', [step('gate', 'approver'), { id: 'sub', type: 'subflow', label: 'Sub', config: { flowName: 'child_named_final' } }, step('final', 'approver2')], + [edge('start', 'gate'), edge('gate', 'sub', 'approve'), edge('gate', 'end', 'reject'), edge('sub', 'final'), ...decided('final', 'end')]), + // ── The fixture of the patch on delta review 7269135624 ── + // A wait between the two steps that outlasts the age bound by design, then a node before the second step. + flow('wait_between', [step('first', 'approver'), WAIT, mark('probe'), step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'hold', 'approve'), edge('first', 'end', 'reject'), edge('hold', 'probe'), edge('probe', 'second'), ...decided('second', 'end')]), +]; + +describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges what no door did', () => { + let kernel: ObjectKernel; + let ql: ObjectQL; + let automation: AutomationEngine; + let svc: ApprovalService; + /** Nodes of type `mark` that throw, by id. */ + let throwOn: Set; + /** What runs while a node of type `mark` executes, by id: inside the passage that reached it. */ + let during: Map Promise>; + /** What each `read` node saw on the record's field. */ + let seen: unknown[]; + let notices: Array<{ topic: string; audience: string[] }>; + let infos: string[]; + + afterEach(async () => { + try { await kernel?.shutdown(); } catch { /* noop */ } + }); + + beforeEach(async () => { + throwOn = new Set(); + during = new Map(); + 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`); + await during.get(node.id)?.(); + if (node.id === 'read') { + const id = context?.record?.id; + seen.push((await ql.find(context?.object ?? 'crm_invoice', { where: { id }, context: SYS }))[0]?.approval_status); + } + 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)); + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound: cannot tell').toEqual({ undetermined: 1 }); + await age('i_norow_mid'); + notices.length = 0; + expect((await svc.reconcileMarkedApprovals()).judged, 'past the bound, and the judgement before read the same').toEqual({ abandoned: 1 }); + expect(await steps('i_norow_mid'), 'the decision stays on its request').toEqual([['first', 'approved']]); + expect(await field('crm_invoice', 'i_norow_mid')).toBe('recalled'); + expect(notified('approval.abandoned')).toEqual([['owner']]); + 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'); + }); + + describe('the rebuild on contract review 7257527251: the kept reading is safe to judge from', () => { + /** Flows whose runs have no row from the start: trimmed before the plugin read them. */ + let trimmedFlows: Set; + /** Flows for whose runs the run store does not answer. */ + let downFlows: Set; + beforeEach(() => { + trimmedFlows = new Set(); + downFlows = new Set(); + const original = automation.getRun.bind(automation); + (automation as any).getRun = async (id: string, options?: { strict?: boolean }) => { + const run: any = await original(id, options); + const name = String(run?.flowName ?? ''); + if (run && downFlows.has(name)) { + if (options?.strict) throw new Error('the run store did not answer'); + return null; + } + return run && trimmedFlows.has(name) ? null : run; + }; + }); + const statusOf = async (runId: unknown) => (await automation.getRun(String(runId)))?.status; + const lastLine = async (requestId: unknown) => String((await timeline(String(requestId))).at(-1)![2]); + /** The summary the engine folds from a whole step log: one execution for each step. */ + const folded = (steps: any[]) => ({ + selected: 0, acted: 0, skipped: 0, + nodes: steps.map((s) => ({ nodeId: s.nodeId, nodeType: s.nodeType ?? 'script', status: 'success', runs: 1, failures: 0, skipped: 0 })), + }); + /** Refuse the mirror's write of `approved` on the invoice while `on()` holds. */ + const refuseApproved = (on: () => boolean) => { + const original = ql.update.bind(ql); + (ql as any).update = async (o: string, data: any, options?: any) => { + if (on() && o === 'crm_invoice' && data?.approval_status === 'approved') throw new Error('VALIDATION_FAILED: a rule of the app'); + return original(o, data, options); + }; + }; + + it('[M4] a sibling child whose read threw at the door is read on the next pass: abandoned, not finished', async () => { + await start('parent_two_subs', 'crm_invoice', 'i_m4_throw'); + throwOn.add('boom'); + downFlows.add('child_boom_then_step'); + await decide('i_m4_throw', 'approve', 'approver'); + const [first] = await requestsOn('i_m4_throw'); + expect(await statusOf(first.record_run_id), 'the carrying run completed').toBe('completed'); + expect(await field('crm_invoice', 'i_m4_throw'), 'the door cannot tell').toBe('pending'); + expect(await marks('i_m4_throw')).toEqual([true]); + + downFlows.clear(); + expect((await svc.reconcileMarkedApprovals()).judged, 'the store answers now: the sibling is read').toEqual({ abandoned: 1 }); + expect(await steps('i_m4_throw'), 'the second step was never asked').toEqual([['only', 'approved']]); + expect(await field('crm_invoice', 'i_m4_throw')).toBe('recalled'); + expect(await lastLine(first.id)).toMatch(/its node 'boom' failed between two steps/); + expect(await marks('i_m4_throw')).toEqual([false]); + }); + + it('[M4] a child with no row under a run that ended at its step: nothing is written within the bound on any pass; past it, the one rule and the notice', async () => { + await start('fail_after_last', 'crm_invoice', 'i_m4_norow'); + throwOn.add('boom'); + trimmedFlows.add('child_fail'); + await settle(decide('i_m4_norow', 'approve', 'approver')); + const [only] = await requestsOn('i_m4_norow'); + expect(await statusOf(only.record_run_id), 'the run failed at the child\'s step').toBe('failed'); + expect(await field('crm_invoice', 'i_m4_norow'), 'the door cannot tell').toBe('pending'); + notices.length = 0; + + for (const pass of ['the next pass', 'the pass after it']) { + expect((await svc.reconcileMarkedApprovals()).judged, `${pass}, within the bound`).toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_m4_norow'), pass).toBe('pending'); + expect(await marks('i_m4_norow'), pass).toEqual([true]); + } + expect(notified('approval.flow_not_continued')).toEqual([]); + + await age('i_m4_norow'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_m4_norow'), 'the last step: its decision stands').toBe('approved'); + expect(await marks('i_m4_norow')).toEqual([false]); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + }); + + it('[M4] past the 200 runs one judgement reads: cannot tell, and the next pass reads on to the failure the first never reached', async () => { + await start('two_step', 'crm_invoice', 'i_m4_cap'); + await decide('i_m4_cap', 'approve', 'approver'); + await withoutDoor(() => decide('i_m4_cap', 'approve', 'approver2')); + const [, last] = await requestsOn('i_m4_cap'); + const rootId = String(last.record_run_id); + // A double of the run store for a tree the engine does not build + // cheaply: the run that carries the record names 250 child runs, each + // completed, and the last holds a failure the flow routed between two + // steps (matched by its node id, as a run of an unknown flow is). + const fan = Array.from({ length: 250 }, (_, i) => `run_fan_${i}`); + const at = new Date().toISOString(); + const real = automation.getRun.bind(automation); + (automation as any).getRun = async (id: string, options?: { strict?: boolean }) => { + if (id === rootId) { + const run: any = await real(id, options); + return { ...run, steps: [...run.steps, { nodeId: 'fan', nodeType: 'subflow', status: 'success', startedAt: at, childRunIds: fan }] }; + } + const i = fan.indexOf(id); + if (i < 0) return real(id, options); + const steps = i === fan.length - 1 ? [{ nodeId: 'first', nodeType: 'mark', status: 'failure', startedAt: at }] : []; + return { + id, flowName: 'fan_child', status: 'completed', startedAt: at, completedAt: at, + trigger: { object: 'crm_invoice', recordId: 'i_m4_cap' }, steps, summary: folded(steps), + }; + }; + + expect((await svc.reconcileMarkedApprovals()).judged, 'the first 200 runs').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_m4_cap')).toBe('pending'); + expect(await marks('i_m4_cap')).toEqual([false, true]); + + expect((await svc.reconcileMarkedApprovals()).judged, 'the runs past them').toEqual({ abandoned: 1 }); + expect(await field('crm_invoice', 'i_m4_cap')).toBe('recalled'); + expect(await lastLine(last.id)).toMatch(/its node 'first' failed between two steps/); + }); + + it('[M4] a run in progress beside a sibling that failed: in progress, and once it has ended the sibling still counts', async () => { + await start('two_step', 'crm_invoice', 'i_m4_wait'); + await decide('i_m4_wait', 'approve', 'approver'); + await withoutDoor(() => decide('i_m4_wait', 'approve', 'approver2')); + const [, last] = await requestsOn('i_m4_wait'); + const rootId = String(last.record_run_id); + // A double of the run store, as in the case of the 200 runs: the run + // that carries the record names two child runs. The first is parked + // between two steps (matched by its node id, as a run of an unknown + // flow is); the second ended with a failure the flow routed there. + const at = new Date().toISOString(); + const child = { flowName: 'fan_child', startedAt: at, trigger: { object: 'crm_invoice', recordId: 'i_m4_wait' } }; + let waiting = true; + const real = automation.getRun.bind(automation); + (automation as any).getRun = async (id: string, options?: { strict?: boolean }) => { + if (id === rootId) { + const run: any = await real(id, options); + return { ...run, steps: [...run.steps, { nodeId: 'fan', nodeType: 'subflow', status: 'success', startedAt: at, childRunIds: ['run_wait', 'run_done'] }] }; + } + if (id === 'run_wait') { + return waiting ? { id, ...child, status: 'paused', steps: [] } : { id, ...child, status: 'completed', completedAt: at, steps: [], summary: folded([]) }; + } + if (id === 'run_done') { + const steps = [{ nodeId: 'first', nodeType: 'mark', status: 'failure', startedAt: at }]; + return { id, ...child, status: 'completed', completedAt: at, steps, summary: folded(steps) }; + } + return real(id, options); + }; + const parkedAt = automation.suspensionOf.bind(automation); + (automation as any).suspensionOf = async (id: string) => (id === 'run_wait' + ? (waiting ? { nodeId: 'first', flowName: 'fan_child' } : undefined) + : parkedAt(id)); + + expect((await svc.reconcileMarkedApprovals()).judged, 'a run is parked between two steps').toEqual({ in_progress: 1 }); + expect(await field('crm_invoice', 'i_m4_wait')).toBe('pending'); + + waiting = false; + expect((await svc.reconcileMarkedApprovals()).judged, 'it ended: the sibling that failed is not skipped').toEqual({ abandoned: 1 }); + expect(await field('crm_invoice', 'i_m4_wait')).toBe('recalled'); + expect(await lastLine(last.id)).toMatch(/its node 'first' failed between two steps/); + }); + + it('[M4] a run read to its end over a child not read yet, whose own row is gone by the next pass, is not taken as passed', async () => { + await start('root_of_two_subs', 'crm_invoice', 'i_m4_owed'); + throwOn.add('boom'); + downFlows.add('child_boom_then_step'); + await decide('i_m4_owed', 'approve', 'approver'); + const [first] = await requestsOn('i_m4_owed'); + expect(await statusOf(first.record_run_id), 'the root went on past the middle run and completed').toBe('completed'); + expect(await field('crm_invoice', 'i_m4_owed'), 'the door cannot tell').toBe('pending'); + + // The store answers again, and the middle run's row is gone: the + // root's log says it went on past it, but the plugin read that run + // and knows a child of it was never read. + downFlows.clear(); + trimmedFlows.add('parent_two_subs'); + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_m4_owed')).toBe('pending'); + expect(await marks('i_m4_owed')).toEqual([true]); + + await age('i_m4_owed'); + expect((await svc.reconcileMarkedApprovals()).judged, 'placed by the step last decided, which a step can follow').toEqual({ abandoned: 1 }); + expect(await field('crm_invoice', 'i_m4_owed')).toBe('recalled'); + }); + + it('[S1] a decision in a child run whose parent is parked at its subflow between two steps: held within the bound, past it abandoned, and both runs cancelled', async () => { + await start('sub_then_second', 'crm_invoice', 'i_s1'); + await settle(withoutResume(() => decide('i_s1', 'approve', 'approver'))); + const [child] = await requestsOn('i_s1'); + expect(String(child.flow_run_id)).not.toBe(String(child.record_run_id)); + expect(await statusOf(child.flow_run_id), 'the child is parked at its decided step').toBe('paused'); + expect(await statusOf(child.record_run_id), 'the parent is parked at its subflow').toBe('paused'); + expect(await field('crm_invoice', 'i_s1'), 'held at the door').toBe('pending'); + expect(await marks('i_s1')).toEqual([true]); + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound: the run may still be resumed').toEqual({ undetermined: 1 }); + expect(await marks('i_s1')).toEqual([true]); + + await age('i_s1'); + notices.length = 0; + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ abandoned: 1 }); + expect(await steps('i_s1'), 'the decision stays on its request').toEqual([['only', 'approved']]); + expect(await field('crm_invoice', 'i_s1')).toBe('recalled'); + expect(await marks('i_s1')).toEqual([false]); + expect(notified('approval.abandoned')).toEqual([['owner']]); + expect(await lastLine(child.id)).toMatch(/still parked at the step 'only' its decision was recorded on/); + expect(await statusOf(child.flow_run_id), 'nothing resumes the child').toBe('cancelled'); + expect(await statusOf(child.record_run_id), 'nor the parent that waited on it').toBe('cancelled'); + expect((await svc.reconcileMarkedApprovals()).scanned, 'nothing left to judge').toBe(0); + }); + + it('[S1] the same two levels down: the walk reaches the decided step through both parked runs', async () => { + await start('root_mid_then_second', 'crm_invoice', 'i_s1_deep'); + await settle(withoutResume(() => decide('i_s1_deep', 'approve', 'approver'))); + const [child] = await requestsOn('i_s1_deep'); + const root: any = await automation.getRun(String(child.record_run_id)); + const middle = String(root.steps.find((s: any) => s.nodeId === 'mid').childRunIds[0]); + expect(middle).not.toBe(String(child.flow_run_id)); + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound').toEqual({ undetermined: 1 }); + + await age('i_s1_deep'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ abandoned: 1 }); + expect(await field('crm_invoice', 'i_s1_deep')).toBe('recalled'); + expect(await marks('i_s1_deep')).toEqual([false]); + expect([await statusOf(child.flow_run_id), await statusOf(middle), await statusOf(child.record_run_id)]).toEqual(['cancelled', 'cancelled', 'cancelled']); + }); + + it('[S1, N8] the same under a map whose items are not records: the batch above the item run is cancelled with it, and no later item opens', async () => { + await start('first_then_two_items', 'crm_invoice', 'i_n8'); + await decide('i_n8', 'approve', 'approver'); + await settle(withoutResume(() => decide('i_n8', 'approve', 'approver2'))); + const [, item] = await requestsOn('i_n8'); + expect(String(item.flow_run_id)).not.toBe(String(item.record_run_id)); + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound').toEqual({ undetermined: 1 }); + + await age('i_n8'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ abandoned: 1 }); + expect(await field('crm_invoice', 'i_n8')).toBe('recalled'); + expect(await statusOf(item.flow_run_id), 'the item run').toBe('cancelled'); + expect(await statusOf(item.record_run_id), 'the batch that waited on it').toBe('cancelled'); + expect(await steps('i_n8'), 'the second item\'s step never opens on a record that was put back').toEqual([['first', 'approved'], ['second', 'approved']]); + }); + + it('[S7 point 1] a door that leaves the next request pending still reads the runs it can reach, and keeps them', async () => { + await start('sub_between', 'crm_invoice', 'i_s7_door'); + await decide('i_s7_door', 'approve', 'approver'); + const [first, second] = await requestsOn('i_s7_door'); + expect(second.status).toBe('pending'); + const root: any = await automation.getRun(String(first.record_run_id)); + const child = String(root.steps.find((s: any) => s.nodeId === 'mid').childRunIds[0]); + // The child ended inside the passage: no opening could read it (the + // run that was being advanced had not logged its step yet), and the + // door that left the second request pending did. + expect(kept(second)?.ended, 'kept at the door').toContain(child); + }); + + it('[S7 point 2] a child whose row is gone before any read, under a run that went on past its step, is passed: finished at the door, with no notice', async () => { + trimmedFlows.add('child_noop'); + await start('early_sub_two_step', 'crm_invoice', 'i_s7_passed'); + await decide('i_s7_passed', 'approve', 'approver'); + notices.length = 0; + await decide('i_s7_passed', 'approve', 'approver2'); + expect(await field('crm_invoice', 'i_s7_passed'), 'written at the door').toBe('approved'); + expect(await marks('i_s7_passed')).toEqual([false, false]); + expect(notified('approval.flow_not_continued')).toEqual([]); + expect((await svc.reconcileMarkedApprovals()).scanned, 'nothing left to judge').toBe(0); + }); + + it('[S7, the failure route] a run that went on along a fault edge did not go on past the step: its child with no row is held, then placed', async () => { + await start('fault_after_last', 'crm_invoice', 'i_s7_fault'); + throwOn.add('boom'); + trimmedFlows.add('child_fail'); + await decide('i_s7_fault', 'approve', 'approver'); + const [only] = await requestsOn('i_s7_fault'); + const root: any = await automation.getRun(String(only.record_run_id)); + expect(root.status, 'the failure was routed, and the run completed').toBe('completed'); + expect(root.steps.find((s: any) => s.nodeId === 'sub').status).toBe('failure'); + expect(await field('crm_invoice', 'i_s7_fault'), 'not passed: the door cannot tell').toBe('pending'); + expect(await marks('i_s7_fault')).toEqual([true]); + notices.length = 0; + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_s7_fault')).toBe('pending'); + + await age('i_s7_fault'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_s7_fault')).toBe('approved'); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + }); + + it('[S7 point 2, its edge] a run still parked at the step that names a child did not go on past it, whatever it logged after', async () => { + await start('two_step', 'crm_invoice', 'i_s7_parked'); + await decide('i_s7_parked', 'approve', 'approver'); + await withoutDoor(() => decide('i_s7_parked', 'approve', 'approver2')); + const [, last] = await requestsOn('i_s7_parked'); + const rootId = String(last.record_run_id); + // A double of the run store for a shape the engine logs in an order + // a fixture cannot fix: after the last step the run is parked at a + // `subflow` no step follows, on a child with no row, and a step on + // another branch of the flow was logged after the visit that parked it. + const at = new Date().toISOString(); + const real = automation.getRun.bind(automation); + (automation as any).getRun = async (id: string, options?: { strict?: boolean }) => { + if (id === 'run_tail_child') return null; + if (id !== rootId) return real(id, options); + const run: any = await real(id, options); + return { + ...run, status: 'paused', completedAt: undefined, + steps: [...run.steps, + { nodeId: 'tail_sub', nodeType: 'subflow', status: 'success', startedAt: at, childRunIds: ['run_tail_child'] }, + { nodeId: 'tail_note', nodeType: 'script', status: 'success', startedAt: at }], + }; + }; + const parkedAt = automation.suspensionOf.bind(automation); + (automation as any).suspensionOf = async (id: string) => (id === rootId + ? { nodeId: 'tail_sub', flowName: 'two_step', correlation: 'subflow:run_tail_child' } + : parkedAt(id)); + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound: no run speaks for the child').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_s7_parked')).toBe('pending'); + expect(await marks('i_s7_parked')).toEqual([false, true]); + + await age('i_s7_parked'); + notices.length = 0; + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_s7_parked')).toBe('approved'); + expect(notified('approval.flow_not_continued'), 'the one rule, with its notice').toEqual([['org_admin']]); + }); + + it('[M5] a map step that started more item runs than it names: cannot tell, held to the bound and then placed; its log speaks for no run it names', async () => { + await start('two_step', 'crm_invoice', 'i_m5_trunc'); + await decide('i_m5_trunc', 'approve', 'approver'); + await withoutDoor(() => decide('i_m5_trunc', 'approve', 'approver2')); + const [, last] = await requestsOn('i_m5_trunc'); + const rootId = String(last.record_run_id); + // A double of the run store: after the last step the run went through + // a `map` whose step carries the engine's mark that it started more + // item runs than it names (`childRunIdsTruncated`, ruling 7258590209), + // and on to its end. One of the two item runs it names has no row. + const at = new Date().toISOString(); + const real = automation.getRun.bind(automation); + (automation as any).getRun = async (id: string, options?: { strict?: boolean }) => { + if (id === 'run_item_gone') return null; + if (id === 'run_item_0') { + return { id, flowName: 'fan_child', status: 'completed', startedAt: at, completedAt: at, trigger: { object: 'crm_invoice', recordId: 'i_m5_trunc' }, steps: [], summary: folded([]) }; + } + if (id !== rootId) return real(id, options); + const run: any = await real(id, options); + const steps = [...run.steps, + { nodeId: 'fan', nodeType: 'map', status: 'success', startedAt: at, childRunIds: ['run_item_0', 'run_item_gone'], childRunIdsTruncated: true }, + { nodeId: 'tail', nodeType: 'script', status: 'success', startedAt: at }]; + return { ...run, steps, summary: folded(steps) }; + }; + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound: the item runs the step does not name cannot be read').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_m5_trunc')).toBe('pending'); + expect(await marks('i_m5_trunc')).toEqual([false, true]); + const read = kept((await requestsOn('i_m5_trunc')).at(-1)); + expect(read.ended, 'a truncated step does not speak for an item run with no row').not.toContain('run_item_gone'); + expect(read.ended, 'and its run is not done with').not.toContain(rootId); + expect(read.open).toContain(rootId); + + await age('i_m5_trunc'); + notices.length = 0; + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_m5_trunc')).toBe('approved'); + expect(notified('approval.flow_not_continued'), 'placed by the step last decided, with its notice').toEqual([['org_admin']]); + }); + + it.each([ + ['cut short', 'cut', (steps: any[]) => steps.slice(1)], + ['stored as null', 'null', () => [] as any[]], + ])('[M5] a step log the history row %s: cannot tell, held to the bound and then placed', async (_how, tag, stored) => { + const id = `i_m5_${tag}`; + await start('two_step', 'crm_invoice', id); + await decide(id, 'approve', 'approver'); + await withoutDoor(() => decide(id, 'approve', 'approver2')); + const [, last] = await requestsOn(id); + const rootId = String(last.record_run_id); + // The run's summary still counts every step it logged; the row keeps fewer. + const real = automation.getRun.bind(automation); + (automation as any).getRun = async (runId: string, options?: { strict?: boolean }) => { + const run: any = await real(runId, options); + return runId === rootId && run ? { ...run, steps: stored(run.steps), summary: folded(run.steps) } : run; + }; + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', id)).toBe('pending'); + expect(await marks(id)).toEqual([false, true]); + + await age(id); + notices.length = 0; + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', id)).toBe('approved'); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + }); + + it('[S6] a note another writer leaves on the request between the reading and the kept write survives it', async () => { + await start('parent_two_subs', 'crm_invoice', 'i_s6'); + throwOn.add('boom'); + downFlows.add('child_boom_then_step'); + const original = ql.update.bind(ql); + let landed = false; + (ql as any).update = async (o: string, data: any, options?: any) => { + if (!landed && o === 'sys_approval_request' && typeof data?.node_config_json === 'string' && data.node_config_json.includes('"__runsRead"')) { + landed = true; + // The kept reading is on its way to the row. Before it lands, + // another writer puts its notes on the same snapshot. + const [row] = await requestsOn('i_s6'); + await original('sys_approval_request', { + id: row.id, + node_config_json: JSON.stringify({ + ...JSON.parse(String(row.node_config_json)), + __laterStepNotOpened: { node: 'second', at: new Date().toISOString(), reason: 'no approver' }, + __strandedContinuation: { decision: 'approve' }, + }), + }, { context: SYS }); + } + return original(o, data, options); + }; + await decide('i_s6', 'approve', 'approver'); + expect(landed, 'the door kept what it read').toBe(true); + const [row] = await requestsOn('i_s6'); + const snapshot = JSON.parse(String(row.node_config_json)); + expect(snapshot.__laterStepNotOpened?.node, 'the note that a later step could not open').toBe('second'); + expect(snapshot.__strandedContinuation, 'the journal of a failed resume').toEqual({ decision: 'approve' }); + expect(snapshot.__runsRead?.ended, 'and the reading is kept beside them').toContain(String(row.flow_run_id)); + }); + + it('[S6] a note that lands while the runs are being read is the judgement\'s: abandoned, not finished', async () => { + await start('two_step', 'crm_invoice', 'i_s6_late'); + await decide('i_s6_late', 'approve', 'approver'); + const original = automation.getRun.bind(automation); + let landed = false; + (automation as any).getRun = async (id: string, options?: { strict?: boolean }) => { + if (!landed && options?.strict) { + landed = true; + // The judgement has read the request and is reading its runs. + // The passage of another process notes that the step after the + // last decision could not open, as `noteLaterStepNotOpened` does. + const row = (await requestsOn('i_s6_late')).at(-1)!; + await ql.update('sys_approval_request', { + id: row.id, + node_config_json: JSON.stringify({ + ...JSON.parse(String(row.node_config_json)), + __laterStepNotOpened: { node: 'third', at: new Date().toISOString(), reason: 'no approver' }, + }), + }, { context: SYS }); + } + return original(id, options); + }; + notices.length = 0; + await decide('i_s6_late', 'approve', 'approver2'); + expect(landed, 'the door read the runs').toBe(true); + expect(await steps('i_s6_late')).toEqual([['first', 'approved'], ['second', 'approved']]); + expect(await field('crm_invoice', 'i_s6_late'), 'a later step could not open: the record is not closed').toBe('recalled'); + expect(await marks('i_s6_late')).toEqual([false, false]); + expect(notified('approval.abandoned')).toEqual([['owner']]); + const last = (await requestsOn('i_s6_late')).at(-1)!; + expect(await lastLine(last.id)).toMatch(/its step 'third' could not open \(no approver\)/); + }); + + it('[S8] a refused outcome at a last step that was placed sends no notice that the flow did not go on; the pass on which the write lands sends it', async () => { + await start('two_step', 'crm_invoice', 'i_s8'); + await decide('i_s8', 'approve', 'approver'); + await settle(withoutResume(() => decide('i_s8', 'approve', 'approver2'))); + await age('i_s8'); + let refuse = true; + refuseApproved(() => refuse); + notices.length = 0; + + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_s8'), 'the write was refused').toBe('pending'); + expect(await marks('i_s8')).toEqual([false, true]); + expect(notified('approval.status_mirror_refused'), 'the refusal is told').toEqual([['org_admin']]); + expect(notified('approval.flow_not_continued'), 'no outcome, no notice').toEqual([]); + + refuse = false; + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_s8')).toBe('approved'); + expect(await marks('i_s8')).toEqual([false, false]); + expect(notified('approval.flow_not_continued'), 'with the outcome').toEqual([['org_admin']]); + }); + + it('[N9] where nothing was held back, a placed approval leaves a line in the log; nothing is written, told or cancelled', async () => { + await start('two_step', 'crm_ticket', 't_n9'); + await settle(withoutResume(() => decide('t_n9', 'approve', 'approver'))); + const [first] = await requestsOn('t_n9'); + await age('t_n9'); + infos.length = 0; + notices.length = 0; + const writes = recordWrites('crm_ticket'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ ended: 1 }); + expect(await marks('t_n9')).toEqual([false]); + expect(writes).toEqual([]); + expect(notices).toEqual([]); + expect(await statusOf(first.flow_run_id), 'the pause is left').toBe('paused'); + expect(infos.filter((m) => m.includes('crm_ticket/t_n9')), 'what the reconciler concluded is in the log').toHaveLength(1); + }); + + describe('the rework on contract review 7266979193: a tree one judgement cannot read has an end, and a map of records is placed', () => { + const at = new Date().toISOString(); + /** A run of a double that reached its end, on the record `record`. */ + const ended = (id: string, record: string, steps: any[] = []) => ({ + id, flowName: 'fan_child', status: 'completed', startedAt: at, completedAt: at, + trigger: { object: 'crm_invoice', recordId: record }, steps, summary: folded(steps), + }); + /** A `map` step that names the item runs `ids`. */ + const fan = (node: string, ids: string[]) => ({ nodeId: node, nodeType: 'map', status: 'success', startedAt: at, childRunIds: ids }); + const ids = (prefix: string) => Array.from({ length: 200 }, (_, i) => `${prefix}_${i}`); + /** + * A double of the run store over the real one, for trees the engine + * does not build cheaply: the run that carries the record logs + * `rootSteps` after its own (and reads as `root` says), and `runs` + * answers for the runs those steps name. + */ + const tree = (rootId: string, rootSteps: any[], runs: (id: string) => unknown, root: Record = {}) => { + const real = automation.getRun.bind(automation); + (automation as any).getRun = async (id: string, options?: { strict?: boolean }) => { + if (id === rootId) { + const run: any = await real(id, options); + return { ...run, ...root, steps: [...run.steps, ...rootSteps] }; + } + const run = runs(id); + return run === undefined ? real(id, options) : run; + }; + }; + /** An item run that is not a record's, and called a `subflow`; and the run that `subflow` started. */ + const itemsThatDelegate = (record: string) => (id: string) => { + const [, kind, i] = /^run_(item|below)_(\d+)$/.exec(id) ?? []; + if (kind === 'item') return ended(id, record, [{ nodeId: 'sub', nodeType: 'subflow', status: 'success', startedAt: at, childRunIds: [`run_below_${i}`] }]); + return kind === 'below' ? ended(id, record) : undefined; + }; + const keptOn = async (id: string) => kept((await requestsOn(id)).at(-1)); + /** The item run the batch of `first_then_records` waits on. */ + const itemOf = async (batch: string) => String((await automation.suspensionOf(batch))?.correlation ?? '').replace(/^map:/, ''); + const seedLines = async () => { for (const id of ['m_line_1', 'm_line_2']) await seed('crm_memo', id); }; + + it('[S11] a map of 200 items that are not records, each calling a subflow: no judgement can keep a run, so the approval is held within the bound and placed past it', async () => { + await start('two_step', 'crm_invoice', 'i_s11_deep'); + await decide('i_s11_deep', 'approve', 'approver'); + await withoutDoor(() => decide('i_s11_deep', 'approve', 'approver2')); + const [, last] = await requestsOn('i_s11_deep'); + // After the last step the run went through a `map` of 200 items + // that are not records, and on to its end; each item run called a + // `subflow`. One judgement reads the run and 199 item runs, and no + // run an item started: no run is read to its end with every run + // below it, so nothing is kept as ended, on any pass. + tree(String(last.record_run_id), [fan('fan', ids('run_item'))], itemsThatDelegate('i_s11_deep')); + notices.length = 0; + + for (const pass of ['the first pass', 'the pass after it']) { + expect((await svc.reconcileMarkedApprovals()).judged, `${pass}, within the bound`).toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_s11_deep'), pass).toBe('pending'); + expect(await marks('i_s11_deep'), pass).toEqual([false, true]); + } + expect((await keptOn('i_s11_deep')).ended, 'no run was read to its end with every run below it').toEqual([]); + + await age('i_s11_deep'); + expect((await svc.reconcileMarkedApprovals()).judged, 'past the bound: a tree the walk cannot finish is placed').toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_s11_deep'), 'the last step: its decision stands').toBe('approved'); + expect(await marks('i_s11_deep')).toEqual([false, false]); + expect(notified('approval.flow_not_continued'), 'placed by the step last decided, with its notice').toEqual([['org_admin']]); + expect((await svc.reconcileMarkedApprovals()).scanned, 'nothing left to judge').toBe(0); + }); + + it('[S11] two map steps of 200 record items after the decision: past the bound the judgements read on while each keeps more runs, and the one that can keep no more places the approval', async () => { + await start('two_step', 'crm_invoice', 'i_s11_wide'); + await decide('i_s11_wide', 'approve', 'approver'); + await withoutDoor(() => decide('i_s11_wide', 'approve', 'approver2')); + const [, last] = await requestsOn('i_s11_wide'); + // After the last step the run went through two `map` steps of 200 + // items each, every item a record of its own, and on to its end: + // 401 runs, where one judgement reads 200 and the kept list holds 200. + tree(String(last.record_run_id), [fan('fan_a', ids('run_a')), fan('fan_b', ids('run_b'))], + (id) => (/^run_[ab]_\d+$/.test(id) ? ended(id, `line_of_${id}`) : undefined)); + // No door judged, and the first judgement comes past the bound. + await age('i_s11_wide'); + notices.length = 0; + + expect((await svc.reconcileMarkedApprovals()).judged, 'it keeps 199 item runs, so the next judgement reads on').toEqual({ undetermined: 1 }); + expect((await keptOn('i_s11_wide')).ended).toHaveLength(199); + expect((await svc.reconcileMarkedApprovals()).judged, 'it keeps one more, and the kept list is full').toEqual({ undetermined: 1 }); + expect((await keptOn('i_s11_wide')).ended).toHaveLength(200); + expect(await field('crm_invoice', 'i_s11_wide')).toBe('pending'); + expect(notified('approval.flow_not_continued')).toEqual([]); + + expect((await svc.reconcileMarkedApprovals()).judged, 'it can keep no more: the tree cannot be finished, and is placed').toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_s11_wide')).toBe('approved'); + expect(await marks('i_s11_wide')).toEqual([false, false]); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + }); + + it('[S11] a parked run whose child the judgement did not get to says nothing: the tree is placed all the same', async () => { + await start('two_step', 'crm_invoice', 'i_s11_parked'); + await decide('i_s11_parked', 'approve', 'approver'); + await withoutDoor(() => decide('i_s11_parked', 'approve', 'approver2')); + const [, last] = await requestsOn('i_s11_parked'); + const rootId = String(last.record_run_id); + // The tree of the first case, still in flight: after its last step + // the run is parked at the `map` (a node no step follows) on item + // 198, and that item run is parked between two steps (matched by + // its node id, as a run of an unknown flow is) on a child run. One + // judgement reads the run and items 0 to 198, and not that child. + const delegating = itemsThatDelegate('i_s11_parked'); + tree(rootId, [fan('fan', ids('run_item'))], (id) => (id === 'run_item_198' + ? { id, flowName: 'fan_child', status: 'paused', startedAt: at, trigger: { object: 'crm_invoice', recordId: 'i_s11_parked' }, steps: [] } + : delegating(id)), { status: 'paused', completedAt: undefined }); + const parkedAt = automation.suspensionOf.bind(automation); + (automation as any).suspensionOf = async (id: string) => { + if (id === rootId) return { nodeId: 'fan', flowName: 'two_step', correlation: 'map:run_item_198' }; + return id === 'run_item_198' ? { nodeId: 'first', flowName: 'fan_child', correlation: 'subflow:run_waited_on' } : parkedAt(id); + }; + notices.length = 0; + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound').toEqual({ undetermined: 1 }); + expect(await marks('i_s11_parked')).toEqual([false, true]); + + await age('i_s11_parked'); + expect((await svc.reconcileMarkedApprovals()).judged, 'past the bound: placed, not in progress for good').toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_s11_parked')).toBe('approved'); + expect(await marks('i_s11_parked')).toEqual([false, false]); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + }); + + it('[S11] a reading that cannot be kept does not read on: past the bound the approval is placed at once', async () => { + await start('two_step', 'crm_invoice', 'i_s11_unkept'); + await decide('i_s11_unkept', 'approve', 'approver'); + await withoutDoor(() => decide('i_s11_unkept', 'approve', 'approver2')); + const [, last] = await requestsOn('i_s11_unkept'); + // The tree of two map steps, whose first reading keeps 199 item runs. + tree(String(last.record_run_id), [fan('fan_a', ids('run_a')), fan('fan_b', ids('run_b'))], + (id) => (/^run_[ab]_\d+$/.test(id) ? ended(id, `line_of_${id}`) : undefined)); + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound: the tree is too large to read, and what was read is kept').toEqual({ undetermined: 1 }); + expect((await keptOn('i_s11_unkept')).ended).toHaveLength(199); + await age('i_s11_unkept'); + // From here the store refuses the kept reading, on every try: a + // judgement that reads on would find the next one where it is itself. + const update = ql.update.bind(ql); + (ql as any).update = async (o: string, data: any, options?: any) => { + if (o === 'sys_approval_request' && String(data?.node_config_json ?? '').includes('__runsRead')) throw new Error('the store refused the write'); + return update(o, data, options); + }; + notices.length = 0; + + expect((await svc.reconcileMarkedApprovals()).judged, 'what it read is not on the request, so it does not wait for a next reading').toEqual({ finished: 1 }); + expect((await keptOn('i_s11_unkept')).ended, 'the one run more it read to its end was not kept').toHaveLength(199); + expect(await field('crm_invoice', 'i_s11_unkept')).toBe('approved'); + expect(await marks('i_s11_unkept')).toEqual([false, false]); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + }); + + it('[S11] the child a parked run waits on is read before the runs beside it: in a tree too large to read, a child that is in progress still says so', async () => { + await start('two_step', 'crm_invoice', 'i_s11_live'); + await decide('i_s11_live', 'approve', 'approver'); + await withoutDoor(() => decide('i_s11_live', 'approve', 'approver2')); + const [, last] = await requestsOn('i_s11_live'); + const rootId = String(last.record_run_id); + // The run that carries the record is parked between two steps on a + // child run, after a `map` of 200 items that each called a + // `subflow`; the child it waits on is parked between two steps in + // its own right (matched by its node id, as a run of an unknown + // flow is). No step names that child, so the walk learns of it + // from the pause alone. + const delegating = itemsThatDelegate('i_s11_live'); + tree(rootId, [fan('fan', ids('run_item'))], (id) => (id === 'run_waited_on' + ? { id, flowName: 'fan_child', status: 'paused', startedAt: at, trigger: { object: 'crm_invoice', recordId: 'i_s11_live' }, steps: [] } + : delegating(id)), { status: 'paused', completedAt: undefined }); + const parkedAt = automation.suspensionOf.bind(automation); + (automation as any).suspensionOf = async (id: string) => { + if (id === rootId) return { nodeId: 'first', flowName: 'two_step', correlation: 'subflow:run_waited_on' }; + return id === 'run_waited_on' ? { nodeId: 'first', flowName: 'fan_child' } : parkedAt(id); + }; + await age('i_s11_live'); + notices.length = 0; + + for (const pass of ['the first pass', 'the pass after it']) { + expect((await svc.reconcileMarkedApprovals()).judged, `${pass}, past the bound`).toEqual({ in_progress: 1 }); + expect(await field('crm_invoice', 'i_s11_live'), pass).toBe('pending'); + expect(await marks('i_s11_live'), pass).toEqual([false, true]); + } + expect(notified('approval.flow_not_continued')).toEqual([]); + }); + + it('[S12] a run parked at a map whose items are records, on an item run that has ended: past the bound nothing will resume it, and the approval is over', async () => { + await seedLines(); + await start('first_then_records', 'crm_ticket', 't_s12'); + // The first step is decided, and the batch starts its first item, + // whose step is an approval of the item's own record. No door + // judges: the process stops there. + await withoutDoor(() => decide('t_s12', 'approve', 'approver')); + const [first] = await requestsOn('t_s12'); + const batch = String(first.record_run_id); + const item = await itemOf(batch); + expect((await automation.getRun(item) as any)?.trigger, 'the item run carries a record of its own').toMatchObject({ object: 'crm_memo', recordId: 'm_line_1' }); + // The item run ends, and nothing resumes the batch. + await automation.cancelRun(item); + expect([await statusOf(item), await statusOf(batch)]).toEqual(['cancelled', 'paused']); + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound: the engine may still be resuming the batch').toEqual({ in_progress: 1 }); + expect(await marks('t_s12')).toEqual([true]); + + await age('t_s12'); + expect((await svc.reconcileMarkedApprovals()).judged, 'the batch is parked between two steps on a run that has ended, as the judgement before read it').toEqual({ ended: 1 }); + expect(await marks('t_s12'), 'the ticket closes on another field, so nothing was held back: the hold ends').toEqual([false]); + expect(await steps('t_s12'), 'the decision stays on its request').toEqual([['first', 'approved']]); + expect((await svc.reconcileMarkedApprovals()).scanned, 'nothing left to judge').toBe(0); + }); + + it('[S12] an item run that has not ended is not kept as ended: the batch waits on it past the bound, and goes on when the item is decided', async () => { + await seedLines(); + await start('first_then_records', 'crm_ticket', 't_s12_live'); + await decide('t_s12_live', 'approve', 'approver'); + const [first] = await requestsOn('t_s12_live'); + const item = await itemOf(String(first.record_run_id)); + expect(await statusOf(item), 'the item waits for its own approval').toBe('paused'); + // The door read the item run: it carries another record, and it has not ended. + expect(kept(first)?.ended ?? [], 'not kept as ended').not.toContain(item); + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound').toEqual({ in_progress: 1 }); + + await age('t_s12_live'); + expect((await svc.reconcileMarkedApprovals()).judged, 'past the bound, the item is still being approved').toEqual({ in_progress: 1 }); + expect(await marks('t_s12_live')).toEqual([true]); + + // Each item's own approval is decided: the batch goes on to the next item, and after the last to the second step. + await decide('m_line_1', 'approve', 'approver'); + await decide('m_line_2', 'approve', 'approver'); + expect(await steps('t_s12_live')).toEqual([['first', 'approved'], ['second', 'pending']]); + expect(kept((await requestsOn('t_s12_live')).at(-1))?.ended, 'an item run that ended is kept').toContain(item); + }); + + it('[S12] as a request opens, an item run of another record that has not ended is not kept as ended either', async () => { + await start('two_step', 'crm_invoice', 'i_s12_open'); + const [first] = await requestsOn('i_s12_open'); + // A double of the run store: before its second step the run went + // through a `map` whose one item is a record of its own, and that + // item run has not ended. + tree(String(first.record_run_id), [fan('each', ['run_of_a_line'])], (id) => (id === 'run_of_a_line' + ? { id, flowName: 'fan_child', status: 'paused', startedAt: at, trigger: { object: 'crm_memo', recordId: 'm_line_9' }, steps: [] } + : undefined)); + + // The second step opens, and its request keeps what the plugin can read; the door then reads again. + await decide('i_s12_open', 'approve', 'approver'); + const [, second] = await requestsOn('i_s12_open'); + expect(second.status).toBe('pending'); + expect(kept(second)?.ended ?? [], 'neither the opening nor the door kept it').not.toContain('run_of_a_line'); + }); + + it('[N20] the step last decided is placed in its own flow: a node of another flow of the set that carries its id does not answer for it', async () => { + await start('gate_sub_final', 'crm_invoice', 'i_n20'); + await decide('i_n20', 'approve', 'approver'); + await withoutDoor(() => decide('i_n20', 'approve', 'approver2')); + const [, last] = await requestsOn('i_n20'); + expect(await statusOf(last.record_run_id), 'the run went on to its end').toBe('completed'); + // The set names the child's node `final`, which stands between the + // two steps, and not the parent's step of that id, which is the last. + const stamp = JSON.parse(String(last.between_steps_json)); + expect(stamp).toContainEqual({ flow: 'child_named_final', node: 'final' }); + expect(stamp).not.toContainEqual({ flow: 'gate_sub_final', node: 'final' }); + expect(last.process_name, 'the request records the flow its step stands in').toBe('flow:gate_sub_final'); + + // No door judged, and the run that carries the record has no row any more. + trimmed.add(String(last.record_run_id)); + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound: cannot tell').toEqual({ undetermined: 1 }); + await age('i_n20'); + notices.length = 0; + expect((await svc.reconcileMarkedApprovals()).judged, 'placed by its last step: no step can follow it').toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_n20')).toBe('approved'); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + }); + + it('[N21] the number of steps the plugin takes the engine to keep of a long log is the engine\'s', () => { + expect(HISTORY_STEPS_KEPT).toBe(MAX_PERSISTED_HISTORY_STEPS); + }); + + it('[N22] the runs kept as open seed the next reading: a failure below one is found though the run above it has no row left', async () => { + await start('root_of_two_subs', 'crm_invoice', 'i_n22_seed'); + throwOn.add('boom'); + downFlows.add('child_boom_then_step'); + await decide('i_n22_seed', 'approve', 'approver'); + const [first] = await requestsOn('i_n22_seed'); + const root: any = await automation.getRun(String(first.record_run_id)); + const middle = String(root.steps.find((s: any) => s.nodeId === 'mid').childRunIds[0]); + expect(await field('crm_invoice', 'i_n22_seed'), 'the door cannot tell').toBe('pending'); + expect([...kept(first).open].sort(), 'the root and the middle run ended over a child that was not read').toEqual([String(first.record_run_id), middle].sort()); + + // The store answers again, and the root's row is gone: only the + // kept reading still leads to the middle run and the child below it. + downFlows.clear(); + trimmedFlows.add('root_of_two_subs'); + expect((await svc.reconcileMarkedApprovals()).judged, 'the middle run is read from the kept reading').toEqual({ abandoned: 1 }); + expect(await field('crm_invoice', 'i_n22_seed')).toBe('recalled'); + expect(await marks('i_n22_seed')).toEqual([false]); + }); + + it('[M5, N22] a marked step that carries no list, as a history row whose links were shed: cannot tell, held to the bound and then placed', async () => { + await start('two_step', 'crm_invoice', 'i_m5_shed'); + await decide('i_m5_shed', 'approve', 'approver'); + await withoutDoor(() => decide('i_m5_shed', 'approve', 'approver2')); + const [, last] = await requestsOn('i_m5_shed'); + const rootId = String(last.record_run_id); + // A double of the run store: after the last step the run went + // through a `map` whose step carries the engine's mark and no list. + const real = automation.getRun.bind(automation); + (automation as any).getRun = async (id: string, options?: { strict?: boolean }) => { + const run: any = await real(id, options); + if (id !== rootId || !run) return run; + const all = [...run.steps, { nodeId: 'fan', nodeType: 'map', status: 'success', startedAt: at, childRunIdsTruncated: true }]; + return { ...run, steps: all, summary: folded(all) }; + }; + notices.length = 0; + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_m5_shed')).toBe('pending'); + expect((await keptOn('i_m5_shed')).ended, 'its run is not done with').not.toContain(rootId); + + await age('i_m5_shed'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_m5_shed')).toBe('approved'); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + }); + + it('[M5, N21, N22] on the real engine, a map of 201 items: its step names as many item runs as one judgement reads and is marked, so the approval is held and then placed', async () => { + await start('only_then_fan', 'crm_invoice', 'i_m5_real'); + await decide('i_m5_real', 'approve', 'approver'); + const [only] = await requestsOn('i_m5_real'); + const rootId = String(only.record_run_id); + const root: any = await automation.getRun(rootId); + expect(root.status, 'the run went through the map to its end').toBe('completed'); + const fanStep = root.steps.find((s: any) => s.nodeId === 'fan'); + expect(fanStep.childRunIds, 'the engine names on one step as many child runs as one judgement reads').toHaveLength(MAX_RUNS_READ_PER_APPROVAL); + expect(fanStep.childRunIdsTruncated, 'and marks the step that started more').toBe(true); + expect(await field('crm_invoice', 'i_m5_real'), 'the door cannot tell').toBe('pending'); + expect(await marks('i_m5_real')).toEqual([true]); + notices.length = 0; + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound').toEqual({ undetermined: 1 }); + const read = await keptOn('i_m5_real'); + expect(read.ended, 'every item run the step names was read to its end').toEqual(expect.arrayContaining(fanStep.childRunIds)); + expect(read.ended, 'the run that carries the record is not done with: the item run its step does not name was never read').not.toContain(rootId); + expect(await field('crm_invoice', 'i_m5_real')).toBe('pending'); + + await age('i_m5_real'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_m5_real'), 'the last step: its decision stands').toBe('approved'); + expect(await marks('i_m5_real')).toEqual([false]); + expect(notified('approval.flow_not_continued'), 'placed by the step last decided, with its notice').toEqual([['org_admin']]); + // 201 runs of the child flow through the real engine and its store: + // well over the default timeout on a loaded runner (12 s measured in CI). + }, 60_000); + + describe('the patch on delta review 7269135624: past the bound, a run is placed only once two judgements in a row read it the same', () => { + // An object that closes on its approval field admits no pause + // between two steps (the opening check refuses the flow), so the + // approvals that wait there by design are those that hold nothing + // back: a ticket, which closes on another field. + it('[S14] a run the engine is resuming past the bound is not placed: its approval waited longer than the bound between two steps, by design', async () => { + await start('wait_between', 'crm_ticket', 't_s14_live'); + await decide('t_s14_live', 'approve', 'approver'); + const [first] = await requestsOn('t_s14_live'); + const runId = String(first.record_run_id); + expect((await automation.suspensionOf(runId))?.nodeId, 'parked at the wait, between the two steps').toBe('hold'); + expect(await marks('t_s14_live')).toEqual([true]); + // The wait outlasts the bound, and a sweep in that time reads the run as in progress. + await age('t_s14_live'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ in_progress: 1 }); + + // The wait ends and the engine resumes the run. The sweep of + // another process reads the run inside that passage: its pause is + // consumed, and it has not parked again. + let inside: unknown; + during.set('probe', async () => { + const readAs = [(await automation.getRun(runId))?.status, (await automation.suspensionOf(runId))?.nodeId]; + const judged = (await svc.reconcileMarkedApprovals()).judged; + inside = { readAs, judged, marks: await marks('t_s14_live') }; + }); + await automation.resume(runId); + expect(inside, 'inside the passage the run reports paused with its pause gone, and the first judgement to read it so cannot tell').toEqual({ + readAs: ['paused', undefined], judged: { undetermined: 1 }, marks: [true], + }); + expect(await steps('t_s14_live'), 'the run went on to its second step').toEqual([['first', 'approved'], ['second', 'pending']]); + expect(await marks('t_s14_live'), 'the opening of the second step answers the mark of the first, as any opening does').toEqual([false, false]); + expect((await svc.reconcileMarkedApprovals()).scanned, 'the approval is in its second step: nothing is left to judge').toBe(0); + }); + + it('[S14] a run with no row on one judgement and back on the next is not placed; one that stays without a row is placed by the judgement after', async () => { + await start('wait_between', 'crm_ticket', 't_s14_norow'); + await decide('t_s14_norow', 'approve', 'approver'); + const [first] = await requestsOn('t_s14_norow'); + const runId = String(first.record_run_id); + await age('t_s14_norow'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ in_progress: 1 }); + + // A process that does not hold the run reads no row for it while another advances it. + trimmed.add(runId); + expect((await svc.reconcileMarkedApprovals()).judged, 'the first judgement to read no row cannot tell').toEqual({ undetermined: 1 }); + expect(await marks('t_s14_norow')).toEqual([true]); + trimmed.delete(runId); + expect((await svc.reconcileMarkedApprovals()).judged, 'the run is back, parked between two steps').toEqual({ in_progress: 1 }); + + // The row goes again and stays gone: the judgement that reads it + // so starts over, and the one after it places the run. + trimmed.add(runId); + expect((await svc.reconcileMarkedApprovals()).judged, 'read so anew: the earlier reading does not count').toEqual({ undetermined: 1 }); + expect(await marks('t_s14_norow')).toEqual([true]); + expect((await svc.reconcileMarkedApprovals()).judged, 'read the same twice in a row: the hold ends').toEqual({ ended: 1 }); + expect(await marks('t_s14_norow')).toEqual([false]); + }); + + it('[S14] where the approval holds a decision back, the judgement that first reads a run as stopped past the bound writes nothing, and the next one puts the record back', async () => { + await start('two_step', 'crm_invoice', 'i_s14_held'); + const [first] = await requestsOn('i_s14_held'); + // Decided, marked, and a run that reports paused with no pause; + // no judgement read it before the bound passed. + await ql.update('sys_approval_request', { id: first.id, status: 'approved', unjudged_since: new Date().toISOString() }, { context: SYS }); + const runId = String(first.flow_run_id); + const suspensionOf = (automation as any).suspensionOf.bind(automation); + (automation as any).suspensionOf = async (id: string) => (id === runId ? undefined : suspensionOf(id)); + await age('i_s14_held'); + notices.length = 0; + + expect((await svc.reconcileMarkedApprovals()).judged, 'the first judgement to read it so').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_s14_held'), 'nothing is put back').toBe('pending'); + expect(await marks('i_s14_held')).toEqual([true]); + expect(notified('approval.abandoned'), 'and nobody is told to submit again').toEqual([]); + + expect((await svc.reconcileMarkedApprovals()).judged, 'read the same twice in a row').toEqual({ abandoned: 1 }); + expect(await field('crm_invoice', 'i_s14_held')).toBe('recalled'); + expect(await marks('i_s14_held')).toEqual([false]); + }); + + it('[S14] a judgement whose reading cannot be kept leaves nothing for the next to stand on: the approval is held until one is kept, and placed by the judgement after', async () => { + await start('two_step', 'crm_invoice', 'i_s14_unkept'); + await decide('i_s14_unkept', 'approve', 'approver'); + await withoutDoor(() => decide('i_s14_unkept', 'approve', 'approver2')); + const [, last] = await requestsOn('i_s14_unkept'); + trimmed.add(String(last.record_run_id)); + await age('i_s14_unkept'); + const update = ql.update.bind(ql); + let refuse = true; + (ql as any).update = async (o: string, data: any, options?: any) => { + if (refuse && o === 'sys_approval_request' && String(data?.node_config_json ?? '').includes('__runsRead')) throw new Error('the store refused the write'); + return update(o, data, options); + }; + notices.length = 0; + + for (const pass of ['the first judgement', 'the one after it']) { + expect((await svc.reconcileMarkedApprovals()).judged, `${pass}: what it read is not on the request`).toEqual({ undetermined: 1 }); + expect(await keptOn('i_s14_unkept'), pass).toBeUndefined(); + expect(await field('crm_invoice', 'i_s14_unkept'), pass).toBe('pending'); + } + refuse = false; + expect((await svc.reconcileMarkedApprovals()).judged, 'the reading is kept').toEqual({ undetermined: 1 }); + expect((await keptOn('i_s14_unkept')).stood, 'with the state it read, and the run').toEqual([`no_row ${String(last.record_run_id)}`]); + expect((await svc.reconcileMarkedApprovals()).judged, 'read the same twice in a row').toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_s14_unkept')).toBe('approved'); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + }); + + it('[S14] a batch over records parked on an item that has just ended is not placed by the first judgement that reads it so, and goes on when the engine resumes it', async () => { + await seedLines(); + await start('first_then_records', 'crm_ticket', 't_s14'); + await withoutDoor(() => decide('t_s14', 'approve', 'approver')); + const [first] = await requestsOn('t_s14'); + const batch = String(first.record_run_id); + const item = await itemOf(batch); + // The item waits for its own approval longer than the bound. + await age('t_s14'); + expect((await svc.reconcileMarkedApprovals()).judged, 'the item has not ended').toEqual({ in_progress: 1 }); + + // The item's run ends, and the engine has not resumed the batch yet. + await automation.cancelRun(item); + expect([await statusOf(item), await statusOf(batch)]).toEqual(['cancelled', 'paused']); + expect((await svc.reconcileMarkedApprovals()).judged, 'the first judgement to read the item as ended does not place the batch').toEqual({ in_progress: 1 }); + expect(await marks('t_s14')).toEqual([true]); + + // The engine resumes the batch, which goes on to its next item. + await automation.resume(batch); + const next = await itemOf(batch); + expect(next, 'the batch waits on another item').not.toBe(item); + expect(await statusOf(next)).toBe('paused'); + expect(await marks('t_s14'), 'the approval is still held').toEqual([true]); + + // That item ends in turn before a judgement comes. The batch is + // parked on a run that has ended, as the judgement before read + // it; but on another run, so it is read anew. + await automation.cancelRun(next); + expect((await svc.reconcileMarkedApprovals()).judged, 'parked on another item that has ended: not the state read before').toEqual({ in_progress: 1 }); + expect(await marks('t_s14')).toEqual([true]); + // Nothing resumes the batch this time, and the judgement after reads the same. + expect((await svc.reconcileMarkedApprovals()).judged, 'read the same twice in a row: the hold ends').toEqual({ ended: 1 }); + expect(await marks('t_s14')).toEqual([false]); + }); + + it('[S14] a run parked at the step of a request that is still open has not stopped there: what is read while the request is open does not stand once it is decided', async () => { + await start('two_step', 'crm_invoice', 'i_s14_open'); + // The door after the first decision reads the runs with the second request open. + await decide('i_s14_open', 'approve', 'approver'); + const [, open] = await requestsOn('i_s14_open'); + expect([open.status, kept(open)?.stood], 'read with the request open: no state is kept').toEqual(['pending', undefined]); + // The second step is decided, and the process stops before its + // run is resumed and before the door judges. + await withoutDoor(() => settle(withoutResume(() => decide('i_s14_open', 'approve', 'approver2')))); + const [, last] = await requestsOn('i_s14_open'); + expect([last.status, (await automation.suspensionOf(String(last.flow_run_id)))?.nodeId], 'decided, and its run still parked at its step').toEqual(['approved', 'second']); + expect(kept(last)?.stood, 'nothing read while it was open is kept as a state').toBeUndefined(); + await age('i_s14_open'); + notices.length = 0; + + expect((await svc.reconcileMarkedApprovals()).judged, 'the first judgement to read the run as stopped at its own step').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_s14_open')).toBe('pending'); + expect((await svc.reconcileMarkedApprovals()).judged, 'read the same twice in a row: placed by its last step').toEqual({ finished: 1 }); + expect(await field('crm_invoice', 'i_s14_open')).toBe('approved'); + expect(notified('approval.flow_not_continued')).toEqual([['org_admin']]); + }); + + it('[S14] a state read before a later request opened does not stand for the judgement after it', async () => { + await start('wait_between', 'crm_ticket', 't_s14_later'); + await decide('t_s14_later', 'approve', 'approver'); + const [first] = await requestsOn('t_s14_later'); + const runId = String(first.record_run_id); + // A judgement reads no row for the run, and keeps that on the first request. + trimmed.add(runId); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ undetermined: 1 }); + expect(kept((await requestsOn('t_s14_later'))[0]).stood).toEqual([`no_row ${runId}`]); + trimmed.delete(runId); + // The run goes on: the second request opens and is decided, with + // no door judging, and the run reaches its end. + await automation.resume(runId); + await withoutDoor(() => decide('t_s14_later', 'approve', 'approver2')); + expect(await statusOf(runId)).toBe('completed'); + expect(await marks('t_s14_later')).toEqual([false, true]); + + // Its row is gone again when the first judgement after comes, past the bound. + trimmed.add(runId); + await age('t_s14_later'); + expect((await svc.reconcileMarkedApprovals()).judged, 'what was read before the second request opened does not stand').toEqual({ undetermined: 1 }); + expect(await marks('t_s14_later')).toEqual([false, true]); + expect((await svc.reconcileMarkedApprovals()).judged, 'read the same twice in a row').toEqual({ finished: 1 }); + expect(await marks('t_s14_later')).toEqual([false, false]); + }); + }); + }); + }); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index b089f84ad54..b22ec20ce47 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -370,13 +370,35 @@ 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[]; + /** + * [seat ruling 7258590209 on #37767] The engine names at most 200 child + * runs on a step, and sets this where the step's execution started + * more. The door reads such a step as cannot tell ({@link stepLogCut}). + */ + childRunIdsTruncated?: boolean; + }>; + /** + * The run's summary (`ExecutionLog.summary`), folded from every step the + * run logged before its history row bounds the step log: how the door + * tells a step log its row cut short ({@link stepLogCut}). + */ + summary?: { nodes?: ReadonlyArray<{ runs?: number; skipped?: number }>; detailOmitted?: boolean }; } | null>; /** * Whether a suspension still exists for `runId` — the pre-flight that keeps @@ -1857,6 +1879,15 @@ 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 could not be seen through + * to its end after that step: it did not go on, or the plugin could not read + * all of it. + */ +const FLOW_NOT_CONTINUED_TOPIC = 'approval.flow_not_continued'; + /** * [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 +1917,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 +1930,471 @@ 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; + childRunIdsTruncated?: unknown; +}; + +/** + * [ADR-0162 Execution item 8] How many runs one judgement of an approval + * reads, at most, beside those it kept as ended and does not read again. It + * is also how many runs each list of the kept reading holds + * ({@link RunsRead}). + * + * A tree of more runs is read over several judgements, each reading on from + * what the approval kept. Within the age bound such a judgement answers that + * it cannot tell, and the approval keeps its mark. Past the bound it answers + * so only while it keeps a run the approval had not kept; the judgement that + * keeps none cannot finish the tree, and the approval is placed by the step + * last decided, as a tree the judgement before it met too + * ({@link RECONCILER_AGE_BOUND_MS}; S11 of contract review 7266979193). The + * kept list only grows and holds this many runs, so the judgements that + * read on are numbered: at most this many passes of the reconciler. + * + * The tree it does not finish is placed without being finished, which is + * the cost the seat accepted with that rule (L1 7269166540). It is not only + * a tree of more runs than the two kept lists hold: the walk reads the runs + * it starts from before the runs below them, so a `map` of 199 items that + * each call a `subflow`, about 399 runs, is already one no reading finishes + * (N26 of delta review 7269135624). And the placement follows from the + * flow's shape, so an approval submitted again on the same flow meets the + * same end (N27 of that review). + * + * It is also how many child runs the engine names on one step before it + * marks the step (`childRunIdsTruncated`); the suite ties the two on a real + * run (N21 of that review), for which it is exported from this module. + */ +export const MAX_RUNS_READ_PER_APPROVAL = 200; + +/** + * [ADR-0162 Execution item 8] How long an approval's marks stand before the + * reconciler reads a run in one of six states as stopped. It is measured + * from the marks: every mark of the approval has stood this long. Within it + * nothing is written for any of the six states it governs, at the + * approval's last step as at any other (ruling 3 on #37767). + * + * Past it, a state says the run has stopped only where two judgements in a + * row read it, for the same run (S14 of delta review 7269135624; + * {@link stoodState}). The hour is counted from the marks and not from the + * run's last movement, so an approval that waits longer than the hour + * between two steps by design (a `wait` node, a batch over records whose + * items are approved one by one, a child parked outside the set) is past + * the bound from the first instant of every later resume; and a run the + * engine is resuming reads as paused with its pause gone, or as a run with + * no row. Only an approval that holds nothing back can wait so: the check + * at its opening refuses each of the three between two steps of an approval + * whose object closes on the step's field (ADR-0162 D5, condition 5), so a + * placement inside such a passage ends a hold early and writes nothing + * (N31 of delta review 7270552441). That state clears within the passage, + * and the one a dead process left is read again by the next judgement. The + * judgement that reads a state for the first time answers that it cannot + * tell, and keeps what it read; a judgement within the bound keeps it too, + * so an approval that was read within the hour is placed by the first + * judgement past it. The six: + * + * - a run that reports paused while its pause is gone has stopped at the + * last step it logged; + * - a run parked at a `subflow` or a `map` whose child run has ended, has + * no row, or will not go on itself, has stopped at that node. An item + * run of a `map` that carries another record is such a child once it is + * in a terminal status (S12 of contract review 7266979193); + * - a run with no row that no run the plugin read speaks for, + * - a run whose step log does not name every child run it started + * ({@link stepLogCut}; seat ruling 7258590209), + * - a tree of more runs than one judgement reads, once a judgement keeps + * no run the approval had not kept ({@link MAX_RUNS_READ_PER_APPROVAL}; + * S11 of that review: the runs it does not get to are runs the plugin + * never read, and the cost is the one ruling 7258590209 accepted for a + * truncated step), and + * - the latest request's own run still parked at the step its decision was + * recorded on, have each stopped at the step last decided (rulings A3 and + * B2 on #37767, one rule). + * + * 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. A passage that begins after the hour is what the second + * reading is for. Two judgements in a row that each fall inside a passage + * of the same run, one passage or two, still read it as stopped: the sweep + * clock sets how far apart two passes of one process are, and nothing sets + * it for two processes or for a pass at boot. + */ +export const RECONCILER_AGE_BOUND_MS = 60 * 60 * 1000; + +/** + * How many steps the engine keeps of a terminal run's log before the history + * row bounds it by bytes (its `MAX_PERSISTED_HISTORY_STEPS`). Only read by + * {@link stepLogCut}: were the engine to keep fewer, more logs would read as + * cut, which is the safe side. Were it to keep more, a row cut to a length + * between the two numbers would compare as whole, so the suite pins this + * number to the engine's (N21 of contract review 7266979193), for which it + * is exported from this module. + */ +export const HISTORY_STEPS_KEPT = 200; + +/** + * [ADR-0162 Execution item 8; seat ruling 7258590209 on M5 of review record + * 7258563513] Why a run's step log does not name every child run its steps + * started, or `undefined` where it does. Such a log cannot be judged from: + * the runs it leaves out are not read, and it does not speak for the runs + * it does name. + * + * - A step carries `childRunIdsTruncated`: its links to child runs were + * shed. Its execution started more child runs than the 200 the engine + * names on a step, or the history row shed the step's list to fit its + * size. + * - The history row of a run in a terminal status keeps fewer steps than + * the run logged. The row bounds the log by bytes: over the bound it + * keeps a tail of it, or stores none. The run's summary is folded before + * that, and counts one execution or one skip for every step logged, so + * the two are compared. A log of more steps than the engine keeps + * ({@link HISTORY_STEPS_KEPT}) is compared with that number: the engine's + * own compaction of a long log is not a cut of the row. A summary that + * is absent, or that dropped its per-node detail, gives nothing to + * compare, and the log is read as cut. + * + * [Ruling 7268216330 on #37767, its question q1: as built] The mark is the + * only one the engine leaves. A log that loses whole steps carries none: + * the engine's compaction of a log of more than {@link HISTORY_STEPS_KEPT} + * steps, the row's halving over its size cap, a row stored as null. The + * plugin reads what the log kept. The second case above tells a halved row + * and a null row from the summary; a compacted log gives nothing to tell it + * by, and a child run named only by a step the compaction dropped reads as + * one the run went past. That is a stated limit of this release. + * + * A run that has not ended is read from its pause, whose step log is not + * bounded, so only the mark applies to it. + */ +function stepLogCut( + run: { summary?: { nodes?: ReadonlyArray<{ runs?: unknown; skipped?: unknown }>; detailOmitted?: unknown } | null }, + steps: readonly RunStepRead[], + terminal: boolean, +): string | undefined { + const marked = steps.find((s) => s?.childRunIdsTruncated === true); + if (marked) return `its step '${String(marked.nodeId)}' started more child runs than it names`; + if (!terminal) return undefined; + const nodes = run.summary?.detailOmitted ? undefined : run.summary?.nodes; + if (!Array.isArray(nodes)) return 'its summary does not say how many steps it logged'; + let logged = 0; + for (const n of nodes) logged += (Number(n?.runs) || 0) + (Number(n?.skipped) || 0); + return steps.length < Math.min(logged, HISTORY_STEPS_KEPT) + ? `its history keeps ${steps.length} of the ${logged} steps it logged` + : undefined; +} + +/** + * [ADR-0162 Execution item 8] A child run a step names, whether a `map` step + * started it, and whether the run that names it went on past that step + * (`passed`, {@link childRunsOf}). + */ +interface ChildRunRef { + readonly id: string; + readonly item: boolean; + readonly passed: 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). + * + * `passed` (the seat's reading 7257555103 of ruling A3): the run went on + * past the step that names the child. The step succeeded, and the run + * reached an end of its flow (`reachedAnEnd`) or logged a later step. The + * engine logs one step for each visit of a node, a visit that paused and + * was resumed included, and a run stands at the last step it logged (as + * {@link stopOf} reads it), so a later step says the visit is over and + * every child of it has ended. Two things are never passed: + * + * - the latest visit of the node a paused run is parked at (`parkedAt`), + * whatever was logged after it: a step on another branch of the flow can + * be logged after the visit that parked the run; + * - a step that failed, also where the flow routed its failure and went on + * (the maintainer's pin on that reading): what such a run did after the + * step says nothing of the child. + * + * And a log that is cut ({@link stepLogCut}, `speaks` false) passes none: + * it does not speak for the runs it names. + */ +function childRunsOf(steps: readonly RunStepRead[], reachedAnEnd: boolean, parkedAt?: string, speaks = true): ChildRunRef[] { + const out: ChildRunRef[] = []; + const parkedVisit = parkedAt === undefined ? -1 : steps.map((s) => s?.nodeId).lastIndexOf(parkedAt); + steps.forEach((s, i) => { + if (!Array.isArray(s?.childRunIds)) return; + const passed = speaks && s.status === 'success' && i !== parkedVisit && (reachedAnEnd || i < steps.length - 1); + for (const id of s.childRunIds) { + if (typeof id !== 'string' || !id) continue; + out.push({ id, item: s.nodeType === 'map', passed }); + } + }); + 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'; + +/** How many times {@link ApprovalService.keepRunsRead} tries its conditional write. */ +const KEEP_RUNS_READ_ATTEMPTS = 3; + +/** + * [ADR-0162 Execution item 8, ruling A3 on #37767] What the plugin kept of + * an approval's runs, in the thin form: + * + * - `ended`: the runs a later judgement does not read again. A run enters + * it only once it was read to an end and every child run its steps name + * is in it too ({@link keptAsEnded}), so a run kept here never hides a + * run that was not read. An end is a terminal status, also for an item + * run of a `map` that carries another record, whose steps are not read; + * and a run with no row that a run the plugin read went on past + * ({@link childRunsOf}); + * - `open`: the runs read in a terminal status that are not in `ended` + * yet, because a child they name was not read to such an end. The next + * judgement starts from them as well, so they are read again while their + * row lasts; and one whose row is gone by then is not taken as passed, + * since nothing can name its children any more; + * - `between`: a failure between two steps found in a run that ended, with + * its instant, which counts while no later request of the approval + * opened after it (an instant it could not read always counts); + * - `stood`: the states the last judgement read that say a run has stopped + * only once they stand ({@link stoodState}), each with its run. It is + * what that one judgement read and no more: the next judgement places a + * run only where its state is in this list, and writes its own list in + * its place (S14 of delta review 7269135624). It holds at most two + * states for each run one judgement reads, and one for the tree. + * + * A run that has not ended is not kept: the engine does not trim it, and + * the walk reaches it again from the runs above it. + */ +interface RunsRead { + readonly ended: readonly string[]; + readonly open: readonly string[]; + readonly between?: { readonly why: string; readonly at: string | null }; + readonly stood?: readonly string[]; +} + +/** + * [ADR-0162 Execution item 8, S14 of delta review 7269135624] A state of a + * run that says the run has stopped only once it stands: a judgement past + * the age bound places it only where the judgement before read the same + * state for the same run ({@link RunsRead}, `stood`). While the engine + * advances a run, the run has no pause and has not parked again or ended, + * so every reader sees it as paused with its pause gone, or as a run with + * no row; and between a child's end and the resume of the run parked on it, + * that run is parked on a child that has ended. Each of these is also what + * a dead process leaves. The first clears within the passage that causes + * it, and the second stands. + * + * - `pause_gone`: the run reports paused, and no pause of it can be found; + * - `on_ended`: the run is parked at a `subflow` or a `map` on the child + * `on`, which has ended or has no row; + * - `own_node`: the latest request's own run is still parked at the step + * its decision was recorded on; + * - `cut`: the run's step log does not name every child run it started; + * - `no_row`: the run has no row, and no run that was read speaks for it; + * - `tree`: the approval's runs number more than one judgement reads (on + * the run that carries the record). + * + * Spelled with spaces, kind first: it is compared as a whole and never + * parsed, and it is not of the `:` shape this package keeps for + * approver addresses. + */ +function stoodState(kind: 'pause_gone' | 'on_ended' | 'own_node' | 'cut' | 'no_row' | 'tree', runId: string, on?: string): string { + return on === undefined ? `${kind} ${runId}` : `${kind} ${runId} ${on}`; +} + +/** The instant of an ISO date, or `NaN`. */ +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}); `approval` is read oldest first. `stood` is not + * merged: it is the list on the approval's latest request, where every + * judgement keeps its reading, and no other. A request that opened since + * the last judgement carries none, so the states are read anew after it. + */ +function runsReadOf(approval: readonly any[]): RunsRead { + const ended = new Set(); + const open = new Set(); + let between: RunsRead['between']; + let stood: string[] = []; + const latest = approval[approval.length - 1]; + for (const r of approval) { + const kept = parseJson>(r?.node_config_json, {})[RUNS_READ_KEY] as Partial | undefined; + if (!kept || typeof kept !== 'object') continue; + if (r === latest && Array.isArray(kept.stood)) stood = kept.stood.filter((v): v is string => typeof v === 'string' && v !== ''); + for (const id of Array.isArray(kept.ended) ? kept.ended : []) if (typeof id === 'string' && id) ended.add(id); + for (const id of Array.isArray(kept.open) ? kept.open : []) if (typeof id === 'string' && id) open.add(id); + const b = kept.between; + 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 }; + } + } + // A run one request kept as open and a later one as ended has ended. + return { + ended: [...ended], open: [...open].filter((id) => !ended.has(id)), ...(between ? { between } : {}), + ...(stood.length > 0 ? { stood } : {}), + }; +} + +/** Whether two kept readings say the same, whatever the order of their lists. */ +function sameRunsRead(a: RunsRead, b: RunsRead): boolean { + const same = (x: readonly string[], y: readonly string[]) => x.length === y.length && [...x].sort().join('\n') === [...y].sort().join('\n'); + return same(a.ended, b.ended) && same(a.open, b.open) && same(a.stood ?? [], b.stood ?? []) + && JSON.stringify(a.between ?? null) === JSON.stringify(b.between ?? null); +} + +/** + * [ADR-0162 Execution item 8, M4 of contract review 7257527251] Of the runs + * one reading found at an end (`over`), those it may keep as ended. A run + * kept as ended is not read again, and so the child runs its steps name are + * never reached through it again: it is kept only where every child it + * names is kept as ended too, in this reading or an earlier one + * (`settled`). A child whose read threw, a child the reading did not get to + * (the cap), a child that has not ended and a child with no row that no run + * went on past each leave the runs above them to be read again. + */ +function keptAsEnded( + over: ReadonlySet, + childrenOf: ReadonlyMap, + settled: ReadonlySet, +): Set { + const keep = new Set(over); + for (let changed = true; changed;) { + changed = false; + for (const id of keep) { + const children = childrenOf.get(id); + if (!children || children.some((c) => !keep.has(c) && !settled.has(c))) { + keep.delete(id); + changed = true; + } + } + } + return keep; +} + +/** + * [ADR-0162 Execution item 8] What one reading of an approval's runs found, + * for {@link runsReadAfter}: the runs read in a terminal status + * (`terminal`), the item runs of another record that are in a terminal + * status (`foreign`), the runs with no row (`noRow`), the runs a run that + * was read went on past (`passed`), the child runs each run that was read + * names (`childrenOf`), and the states it read that say a run has stopped + * only once they stand (`stood`, {@link stoodState}). + */ +interface RunsFound { + readonly terminal: Set; + readonly foreign: Set; + readonly noRow: Set; + readonly passed: Set; + readonly childrenOf: Map; + readonly stood: Set; +} + +const noRunsFound = (): RunsFound => ({ + terminal: new Set(), foreign: new Set(), noRow: new Set(), passed: new Set(), childrenOf: new Map(), stood: new Set(), +}); + +/** + * [the seat's reading 7257555103 of ruling A3] The runs with no row that a + * run the plugin read speaks for: it went on past the step that names them, + * so they count as passed at that step. Not one the plugin kept as `open`: + * it read that run to its end over a child it could not read, and a row + * that is gone no longer names that child. + */ +function passedWithNoRow(prior: RunsRead, found: RunsFound): Set { + const open = new Set(prior.open); + return new Set([...found.noRow].filter((id) => found.passed.has(id) && !open.has(id))); +} + +/** + * [ADR-0162 Execution item 8, ruling A3 on #37767] The kept reading after + * one more reading: what was kept before (`prior`) with what this one found. + * `ended` only grows, by the runs {@link keptAsEnded} allows; `open` is the + * runs read in a terminal status, now or before, that are not ended. + * + * Each of the two lists holds at most {@link MAX_RUNS_READ_PER_APPROVAL} + * runs. A run left out of `ended` is read again, which costs a read and + * changes no answer. + * + * A reading whose `open` would not fit keeps both lists as they were (N25 + * of delta review 7269135624: this is what the rule does). The runs it read + * in a terminal status beyond them are then in neither list: they are not + * kept as open, so one of them whose row is gone by a later reading can be + * taken as passed where a run that was read went on past it + * ({@link passedWithNoRow}). The rule does not prevent that. It does not + * change the answer either, by two facts nothing pins: a list holds as many + * runs as one judgement reads, and the walk reads the runs it starts from, + * the `open` runs among them, before the runs below them (the child a + * parked run waits on excepted). So `open` passes the bound only where the + * approval already holds nearly that many open runs, and from then on every + * reading spends its reads on them and cannot finish the tree: the approval + * is cannot tell and, past the age bound, placed. + * + * `stood` is not merged: it is what this reading read ({@link RunsRead}). + */ +function runsReadAfter(prior: RunsRead, found: RunsFound, between: RunsRead['between']): RunsRead { + const settled = new Set(prior.ended); + const gone = passedWithNoRow(prior, found); + const childrenOf = new Map(found.childrenOf); + for (const id of [...found.foreign, ...gone]) childrenOf.set(id, []); + const now = keptAsEnded(new Set([...found.terminal, ...found.foreign, ...gone]), childrenOf, settled); + const open = [...new Set([...prior.open, ...found.terminal])].filter((id) => !settled.has(id) && !now.has(id)); + const rest = { ...(between ? { between } : {}), ...(found.stood.size > 0 ? { stood: [...found.stood] } : {}) }; + if (open.length > MAX_RUNS_READ_PER_APPROVAL) return { ended: prior.ended, open: prior.open, ...rest }; + const ended = [...prior.ended, ...[...now].filter((id) => !settled.has(id))].slice(0, MAX_RUNS_READ_PER_APPROVAL); + return { ended, open, ...rest }; +} + +/** + * [ADR-0162 Execution item 8] What one run of an approval's tree answered + * when the door read it (`ApprovalService.readApprovalRun`): + * + * - `undetermined`: it cannot be read or placed now; + * - `no_row`: the engine holds no row for it; + * - `foreign`: an item run of a `map` that carries another record. Its + * steps are an approval of that record and are not read; `over`: it is + * in a terminal status, so the batch parked on it has nothing left to + * wait for; + * - `in_progress`: parked at a node of the set, on nothing the walk reads; + * - `waits`: parked at a node of the set (`node`) on a child run (`on`), + * which says what this run says (`ApprovalService.waitingRun`); + * - `own_node`: the latest request's own run, parked at that request's node; + * - `read`: everything else. `over`: it is in a terminal status. `stopped`: + * it reports paused at a pause that is gone, past the age bound and as + * the judgement before read it ({@link stoodState}), so it will not go + * on. `endedWhy`: it ended, or stopped, between two steps. + * + * `cut`, on any of the last four: why its step log does not name every + * child run it started ({@link stepLogCut}). + */ +type ApprovalRunRead = + | { answer: 'undetermined'; why: string } + | { answer: 'no_row' } + | { answer: 'foreign'; over: boolean } + | { answer: 'in_progress'; children: ChildRunRef[]; cut?: string } + | { answer: 'waits'; on: string; item: boolean; node: string; children: ChildRunRef[]; cut?: string } + | { answer: 'own_node'; flow?: string; children: ChildRunRef[]; cut?: string } + | { answer: 'read'; over: boolean; stopped?: boolean; endedWhy?: string; endedAt?: string; children: ChildRunRef[]; cut?: string }; + /** * [ADR-0162 Execution item 8] What the door answered for an approval after it * resumed or cancelled one of its runs (`ApprovalService.judgeApprovalAfterDoor`). @@ -2530,6 +3029,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,26 +5783,52 @@ 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 reads and keeps + * at every door, also at one that leaves a request open, whose answer it + * does not need (the seat's reading 7257555103 of ruling A3). It answers + * one of: * * - **in progress**: a request of the approval is pending or returned on - * the record, or the run is parked at a pause a step can follow (a node - * of the set the request carries). Nothing is written, and the mark + * the record, or a run is parked at a pause a step can follow (a node + * of the set the request carries) and is not waiting, through its child + * runs, on the step last decided. Nothing is written, and the mark * stays. - * - **finished**: 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, a + * run's step log is cut, the approval's runs number more than one + * judgement reads, or the latest request's own run is still parked at + * its own node. Nothing is written, and the mark stays for the + * reconciler. + * + * Past the age bound (`opts.ageBoundMs`, the reconciler's), the last four + * have stopped at the step last decided, once two judgements in a row + * read the same of the same run (S14 of delta review 7269135624; + * {@link stoodState}), and the first of the two cannot tell (rulings A3 + * and B2 on #37767; a tree of more runs than one judgement reads, once a + * judgement keeps no run the approval had not kept, S11 of contract + * review 7266979193): where + * a step can follow it, the approval is abandoned and a run still parked + * there is cancelled, with the runs that wait on it ({@link cancelStoppedRun}); + * where none can, it is finished, and once its outcome is on the record the + * administrators are told that its flow could not be seen through to its + * end after its last step + * ({@link reportFlowNotContinued}; ruling 3 on #37767: the outcome and the + * notice in one stroke, so a refused write sends no notice, and the pass on + * which the write lands sends it). * * In an approval that holds nothing back, finished and abandoned both end - * the hold: the mark is cleared and nothing is written. Where the approval's + * the hold: the mark is cleared and nothing is written, cancelled or told; + * where a run was placed, a line in the log says so. Where the approval's * latest request was recalled, the writer that recalled it already wrote * what an abandoned approval leaves: the mark is cleared and nothing more is * written. Where no request of the approval carries the mark, it was judged @@ -5316,6 +5843,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'; @@ -5338,7 +5866,28 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // Open: a pending request, or a returned one in its revise window, which // is the approval's latest (a resubmitted round stays `returned`). const latest = approval[approval.length - 1] ?? row; - if (approval.some((r) => r.status === 'pending') || latest.status === 'returned') return 'in_progress'; + if (approval.some((r) => r.status === 'pending') || latest.status === 'returned') { + // [the seat's reading 7257555103 of ruling A3, point 1] "At each + // door" is literal: a door that leaves a request open still reads the + // runs it can reach and keeps what it read, so that a child run that + // ended in this passage is read before its row can be trimmed. The + // answer of the reading is not used: an open request is in progress. + // Nor are the states it read kept (S14 of delta review 7269135624): + // this is no judgement, and a run parked at the step of a request + // that is still open has not stopped there. What it keeps carries no + // such state, so a judgement after it reads them anew. + try { + const read = (await this.readCarryingRun(latest, stamp, approval)).kept; + await this.keepRunsRead(latest, approval, read && { + ended: read.ended, open: read.open, ...(read.between ? { between: read.between } : {}), + }); + } catch (err: any) { + this.logger?.warn?.('[approvals] could not read an approval\'s runs at a door that left a request open; the next door reads them', { + request: requestId, error: err?.message ?? String(err), + }); + } + return 'in_progress'; + } const marked = approval.filter(isMarked); if (marked.length === 0) return 'judged'; if (latest.status !== 'approved' && latest.status !== 'rejected') { @@ -5346,7 +5895,19 @@ 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. A state that says a run has stopped then places the run, where + // the judgement before read the same ({@link stoodState}). + const now = this.clock.now().getTime(); + const aged = opts?.ageBoundMs != null && marked.every((r) => { + const at = new Date(r.unjudged_since).getTime(); + 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 +5922,41 @@ 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 ?? ''); + // The flow the step stands in: the parked run's where a run is still + // parked at it, otherwise the one its request records, so that a + // node of another flow of the set that carries the step's id does + // not answer for it (N20 of contract review 7266979193). + const stepFlow = reading.flow ?? flowNameOfProcess(latest.process_name); + if (stepNode && standsBetweenSteps(stamp, stepFlow, stepNode)) { + answer = 'abandoned'; + parkedRun = reading.parkedRun; + } else { + lastStepStopped = reading.why; + } + why = reading.why; + if (!holds) { + // Nothing was held back, so nothing is written, cancelled or told: + // the log keeps what was concluded of a run that did not go on. + this.logger?.info?.( + `[approvals] after ${door}, the approval of ${row.object_name}/${row.record_id} is over, and held nothing back: ${reading.why} ` + + 'Its marks were cleared; nothing was written, cancelled or told.', + { request: requestId, latest: latest.id, run: reading.parkedRun ?? null }, + ); + } + } + if (answer === 'finished') { if (!holds) { await this.clearMarks(marked); return 'finished'; @@ -5373,14 +5968,25 @@ 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 (!refusal) await this.clearMarks(marked); + // [ruling 3 on #37767] The outcome and the administrators' notice in + // one stroke. A refused write keeps the marks and sends no notice + // that the flow could not be seen through to its end (the mirror + // reports its refusal); the pass on which the write lands sends it. + if (!refusal) { + if (lastStepStopped !== undefined) await this.reportFlowNotContinued(latest, lastStepStopped); + await this.clearMarks(marked); + } return 'finished'; } if (!holds) { 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, with the + // runs that wait on it, so that nothing resumes the approval on a + // record that was put back. + if (parkedRun) await this.cancelStoppedRun(latest, parkedRun, why); return 'abandoned'; } catch (err: any) { this.logger?.warn?.( @@ -5393,124 +5999,629 @@ 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 and place + * where each stopped against `stamp`. The walk starts at the run that + * carries the record, the latest request's own run, and every run the + * approval kept as read to its end over a child not read yet (`open`, + * {@link RunsRead}), and follows the child runs each delegating step + * records (`childRunIds` on the step log): every `subflow` child, and every + * `map` item run that does not carry another record (an item that is a + * record carries an approval of its own). A run kept as ended is not read + * again: what it showed is in the kept reading, and every run below it was + * read to its end before it was kept ({@link keptAsEnded}). + * + * It reads the whole tree before it answers, so that no run it could read + * is left out of what it keeps, and one run's answer does not hide + * another's. A run it cannot read ends the reading at once, since nothing + * can be concluded past it: + * + * - A run that cannot be read because the store did not answer, that + * another process is advancing, or that reports paused with no pause to + * be found (within the age bound, and past it where the judgement + * before did not read it so): `undetermined`. + * - A tree of more runs than one judgement reads + * ({@link MAX_RUNS_READ_PER_APPROVAL}): `undetermined` within the age + * bound, and past it while this reading keeps a run the approval had + * not kept and that reading is on the request, so that the next + * judgement reads on from it. The reading that keeps none cannot + * finish the tree: it answers from the runs it did read, and where + * they say nothing it is `placed`, as below. + * - Otherwise, a run parked at a node of the set that is not waiting on + * the step last decided: `in_progress`. A run parked there on a child + * run says what its child says ({@link ApprovalService.waitingRun}): the + * walk reads the child, down to the latest request's own run where that + * is what the runs above it wait on. + * - Otherwise, a failure between two steps that no later request answered, + * read now or kept, or a later step that could not open (the note on + * `latest`, read once the runs are read, {@link laterStepNotOpenedOn}): + * `abandoned`. + * - Otherwise, a run with no row that no run read speaks for, a run whose + * step log is cut ({@link stepLogCut}: the runs it leaves out cannot be + * read), a tree this reading could not finish, or the latest request's + * own run still parked at its own node: within the bound + * `undetermined`; past it `placed` where the judgement before read + * every such state of this reading too, and `undetermined` where it + * did not. Placed, the run has stopped at the step last decided + * (rulings A3 and B2 on #37767, one rule), and + * {@link judgeApprovalAfterDoor} ends the approval by whether a step can + * follow that step. + * - Otherwise `finished`. + * + * A run with no row is spoken for where a run that was read went on past + * the step that names it (the seat's reading 7257555103 of ruling A3; + * {@link childRunsOf}, {@link passedWithNoRow}): it counts as passed at + * that step, and is kept as ended. A continuation along a failure route is + * not going on past the step, and a log that is cut speaks for no run. + * + * A failure between two steps is a failure the flow routed, of a node of + * the set at the top level of a run (N46 c′: a failure handled in a + * `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}. Then a run that reports paused while its + * pause is gone is read as stopped at its last step, and a run parked at a + * `subflow` or a `map` whose child run has ended (an item run that carries + * another record included), has no row or will not go on itself, as + * stopped at that node. + * + * Each of these, and each state that places the approval by the step last + * decided, is also what a run the engine is advancing reads as, and the + * bound is counted from the marks, not from the run's last movement. So a + * state stands only where the judgement before this one read it too, for + * the same run (S14 of delta review 7269135624; {@link stoodState}): the + * reading that meets a state first answers `undetermined`, or + * `in_progress` for a run parked on a child that has ended, and keeps the + * state. Every reading keeps the states it read, aged or not, in place of + * those kept before; a reading that reaches none keeps none. + * + * Every answer carries `kept`: the kept reading with what this reading + * found ({@link runsReadAfter}), which the door writes on the latest + * request. A reading that ended early keeps what it had read by then. */ 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 }; } - let run: { status?: string; flowName?: string; steps?: unknown } | null; + + 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 found = noRunsFound(); + let between = prior.between && !(instantOf(prior.between.at) < lastOpened) ? prior.between : undefined; + const kept = (): RunsRead => runsReadAfter(prior, found, between); + // [S14 of delta review 7269135624] A state that says a run has stopped + // stands only where the judgement before this one read it too, for the + // same run: the engine may be advancing the run, and then the state + // clears within that passage. Every such state this reading reads is + // kept for the next judgement, whatever this one answers. + const stoodBefore = new Set(prior.stood ?? []); + const stands = (state: string): boolean => { + found.stood.add(state); + return aged && stoodBefore.has(state); + }; + + const ownRunId = latest.flow_run_id != null ? String(latest.flow_run_id) : ''; + const queue: ChildRunRef[] = [{ id: rootId, item: false, passed: false }]; + if (ownRunId && ownRunId !== rootId) queue.push({ id: ownRunId, item: false, passed: false }); + for (const id of prior.open) queue.push({ id, item: false, passed: false }); + /** What each run read in this walk answered, in the order read. */ + const read = new Map(); + /** The first run read whose step log is cut ({@link stepLogCut}). */ + let cutLog: { runId: string; why: string } | undefined; + /** Every run read whose step log is cut. */ + const cutRuns: string[] = []; + /** The first run this reading did not get to: the tree holds more runs than one judgement reads. */ + let unread: string | undefined; + while (queue.length > 0) { + const next = queue.shift()!; + const runId = next.id; + if (next.passed) found.passed.add(runId); + if (read.has(runId) || settled.has(runId)) continue; + if (read.size >= MAX_RUNS_READ_PER_APPROVAL) { + // No further run is read. The queue is still emptied, so that every + // run a run that was read went on past counts as passed. + unread ??= runId; + continue; + } + const one = await this.readApprovalRun(runId, { + stamp, lastOpened, aged, stands, item: next.item && !ownRuns.has(runId), latest, + }); + read.set(runId, one); + if (one.answer === 'undetermined') return { answer: 'undetermined', why: one.why, runId, kept: kept() }; + if (one.answer === 'no_row') { + found.noRow.add(runId); + continue; + } + if (one.answer === 'foreign') { + // Kept as ended once it has ended. One that has not is not kept: the + // batch above it is read again, and reads it again. + if (one.over) found.foreign.add(runId); + continue; + } + // A run whose log is cut names its children in part: they are read, + // and it is never kept as ended ({@link keptAsEnded} wants its children). + if (one.cut === undefined) found.childrenOf.set(runId, one.children.map((c) => c.id)); + else { + cutLog ??= { runId, why: one.cut }; + cutRuns.push(runId); + } + if (one.answer === 'read' && one.over) { + found.terminal.add(runId); + if (one.endedWhy !== undefined && !between) between = { why: one.endedWhy, at: one.endedAt ?? null }; + } + queue.push(...one.children); + // The child a parked run waits on is read as well, also where no step + // names it; and it is read next, so that what a parked run waits on is + // read before the runs beside it use up the reading. + if (one.answer === 'waits') queue.unshift({ id: one.on, item: one.item, passed: false }); + } + + const missing = [...found.noRow].filter((id) => !passedWithNoRow(prior, found).has(id)); + let inProgress = false; + let endedWhy: string | undefined; + let parkedAtOwnNode: { runId: string; flow?: string } | undefined; + for (const [runId, one] of read) { + if (one.answer === 'in_progress') { + inProgress = true; + } else if (one.answer === 'own_node') { + parkedAtOwnNode = { runId, flow: one.flow }; + } else if (one.answer === 'read') { + endedWhy ??= one.endedWhy; + } else if (one.answer === 'waits') { + const says = this.waitingRun(runId, read, settled, stands); + // A child the reading did not get to says nothing of the run parked + // on it: in a tree that cannot be finished, it is not in progress. + if (says === 'moving' || (says === 'unread' && unread === undefined)) inProgress = true; + else if (typeof says !== 'string') endedWhy ??= says.why; + } + } + // The states that place the approval by the step last decided. Each is + // read here, before any answer, so that it is kept for the next + // judgement also where this one answers something else; and the + // approval is placed only where every one of them stood before + // ({@link stoodState}). + const placing = [ + ...(parkedAtOwnNode ? [stoodState('own_node', parkedAtOwnNode.runId)] : []), + ...cutRuns.map((id) => stoodState('cut', id)), + ...(unread !== undefined ? [stoodState('tree', rootId)] : []), + ...missing.map((id) => stoodState('no_row', id)), + ]; + const allStood = placing.map(stands).every(Boolean); + + // [S11 of contract review 7266979193] A tree of more runs than one + // judgement reads has an end. Within the age bound the next judgement + // reads on. Past it, it reads on only where this reading kept a run the + // approval had not kept, and that reading is on the request: the kept + // list only grows and holds at most MAX_RUNS_READ_PER_APPROVAL runs, so + // the judgements that read on are numbered. The reading that keeps none + // cannot finish the tree, and answers below from the runs it did read. + if (unread !== undefined) { + const reading = kept(); + const readsOn = !aged + || (reading.ended.length > prior.ended.length && await this.keepRunsRead(latest, approval, reading)); + if (readsOn) { + return { + answer: 'undetermined', runId: unread, kept: reading, + why: `its runs number more than the ${MAX_RUNS_READ_PER_APPROVAL} one judgement reads; the runs read to their end are kept, and the next judgement reads on.`, + }; + } + } + + if (inProgress) return { answer: 'in_progress', kept: kept() }; + const notOpened = await this.laterStepNotOpenedOn(latest); + if (notOpened) { + return { + answer: 'abandoned', + why: `its step '${String(notOpened.node ?? '')}' could not open (${String(notOpened.reason ?? 'no reason recorded')}).`, + kept: kept(), + }; + } + const failed = endedWhy ?? between?.why; + if (failed) return { answer: 'abandoned', why: failed, kept: kept() }; + if (placing.length > 0) { + const what = parkedAtOwnNode + ? `its run '${parkedAtOwnNode.runId}' is still parked at the step '${String(latest.flow_node_id ?? '')}' its decision was recorded on, so the run did not go on after it` + : cutLog + ? `the step log of its run '${cutLog.runId}' does not name every child run it started (${cutLog.why}), so the runs below it cannot all be read` + : unread !== undefined + ? `its runs number more than the ${MAX_RUNS_READ_PER_APPROVAL} one judgement reads, and this judgement kept no further run as read to its end, so its runs (the run '${unread}' among them) cannot all be read` + : `its run '${missing[0]}' has no row the automation engine can read, and no run that was read went on past it, so where it stopped cannot be read`; + const runId = parkedAtOwnNode?.runId ?? cutLog?.runId ?? missing[0]; + if (!aged) { + return { + answer: 'undetermined', runId, kept: kept(), + why: parkedAtOwnNode || !cutLog ? `${what}, and a process may still be moving it.` : `${what}; within the age bound nothing is concluded from it.`, + }; + } + if (!allStood) { + return { + answer: 'undetermined', runId, kept: kept(), + why: `${what}; the judgement before this one did not read the same, so a process may be moving it, and the next judgement places it if it still reads so.`, + }; + } + return { + answer: 'placed', + why: `${what}; past the age bound it has stopped at that step.`, + ...(parkedAtOwnNode ? { parkedRun: parkedAtOwnNode.runId, flow: parkedAtOwnNode.flow } : {}), + kept: kept(), + }; + } + return { answer: 'finished', kept: kept() }; + } + + /** + * [ADR-0162 Execution item 8, S6 of contract review 7257527251] The note + * that a later step of `latest`'s approval could not open + * ({@link noteLaterStepNotOpened}), read from the row now and not from the + * copy the judgement began with. A passage writes the note before its run + * ends or parks, so a judgement that reads it once the runs are read + * cannot answer from runs that are still over a note it has not seen. + */ + private async laterStepNotOpenedOn(latest: any): Promise<{ node?: unknown; reason?: unknown } | undefined> { + const rows = await this.engine.find('sys_approval_request', { + where: { id: latest.id }, fields: ['id', 'node_config_json'], limit: 1, context: SYSTEM_CTX, + }); + const row: any = (Array.isArray(rows) ? rows[0] : undefined) ?? latest; + const note = parseJson>(row.node_config_json, {})[LATER_STEP_NOT_OPENED_KEY]; + return note && typeof note === 'object' ? note as { node?: unknown; reason?: unknown } : undefined; + } + + /** + * [ADR-0162 D5, Execution item 8] What a run parked at a node of the set on + * a child run says of the approval, once the walk has read that child + * ({@link readCarryingRun}). A parked parent moves only when its child + * does, so it says what the child says: + * + * - `moving`: the child is in progress in its own right, is parked at a + * pause that is not of the set, or carries another record and has not + * ended; or the child has ended or has no row, and the engine may still + * be resuming the parent: within the age bound, and past it where the + * judgement before did not read the parent parked on that same child + * so ({@link stoodState}). The approval is in progress. + * - `unread`: the reading did not get to the child, so the parent says + * nothing. The caller reads it as moving, except in a tree of more runs + * than one judgement reads ({@link readCarryingRun}). + * - `still`: the child is the latest request's own run, parked at the step + * its decision was recorded on, or a run that waits on that run in turn. + * The parent says nothing of its own: the one rule places the approval + * by that step (B2 on #37767), at whatever depth the step sits. + * - `{ why }`: past the age bound, and as the judgement before read it, + * the child has ended, has no row, or reports paused at a pause that is + * gone, so nothing will resume the parent, between two steps. An item + * run of a `map` that carries another record has ended once it is in a + * terminal status (S12 of contract review 7266979193). + */ + private waitingRun( + runId: string, + read: ReadonlyMap, + settled: ReadonlySet, + stands: (state: string) => boolean, + above: ReadonlySet = new Set(), + ): 'moving' | 'still' | 'unread' | { why: string } { + const parent = read.get(runId); + if (parent?.answer !== 'waits' || above.has(runId)) return 'moving'; + const child = read.get(parent.on); + const stopped = (how: string) => ({ + why: `its run '${runId}' is parked at '${parent.node}' on a child run that ${how}, so nothing will resume it, between two steps.`, + }); + // Between a child's end and the resume of the run parked on it, the + // engine has not claimed the parent's pause yet: the state stands only + // where the judgement before read it too ({@link stoodState}). + const ended = () => (stands(stoodState('on_ended', runId, parent.on)) ? stopped('has ended') : 'moving' as const); + if (!child) return settled.has(parent.on) ? ended() : 'unread'; + switch (child.answer) { + case 'no_row': return ended(); + case 'foreign': return child.over ? ended() : 'moving'; + case 'own_node': return 'still'; + case 'waits': { + const says = this.waitingRun(parent.on, read, settled, stands, new Set([...above, runId])); + return typeof says === 'string' ? says : stopped('will not go on'); + } + case 'read': + if (child.over) return ended(); + return child.stopped ? stopped('will not go on') : 'moving'; + default: return 'moving'; + } + } + + /** + * [ADR-0162 D5, Execution item 8] One run of an approval's tree, for + * {@link readCarryingRun}: whether it can be read and is still, whether it + * is parked between two steps or at the latest request's own node, whether + * it is over (a terminal status) and ended between two steps, and the + * child runs to read next. `item`: the run is an item run of a `map` that + * is not the run of a request of the approval; one that carries a record + * other than the approval's is `foreign`: it is not followed, and only + * whether it has ended is read. + */ + private async readApprovalRun( + runId: string, + at: { stamp: readonly StampedNode[]; lastOpened: number; aged: boolean; stands: (state: string) => boolean; item: boolean; latest: any }, + ): Promise { + const log: { cut?: string } = {}; + const one = await this.placeApprovalRun(runId, at, log); + return log.cut !== undefined && 'children' in one ? { ...one, cut: log.cut } : one; + } + + /** The body of {@link readApprovalRun}; `log.cut` is set where the run's step log is cut ({@link stepLogCut}). */ + private async placeApprovalRun( + runId: string, + at: { stamp: readonly StampedNode[]; lastOpened: number; aged: boolean; stands: (state: string) => boolean; item: boolean; latest: any }, + log: { cut?: string }, + ): Promise { + const { stamp, lastOpened, aged, stands, item, latest } = at; + const automation = this.automation!; + let run: { + status?: string; flowName?: string; completedAt?: string; trigger?: { object?: string; recordId?: string }; steps?: unknown; + summary?: { nodes?: ReadonlyArray<{ runs?: number; skipped?: number }>; detailOmitted?: boolean }; + } | 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: 'no_row' }; + 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', over: typeof run.status === 'string' && TERMINAL_RUN_STATUSES.has(run.status) }; + } } - 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[]; + log.cut = stepLogCut(run, steps, TERMINAL_RUN_STATUSES.has(status)); + const speaks = log.cut === undefined; + let children = childRunsOf(steps, REACHED_AN_END.has(status), undefined, speaks); + + // A failure the flow routed, at the top level of the run, on a node of + // the set, after which no request of the approval opened. Read for a + // 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) { + // What a run the engine is advancing reads as, too: its pause is + // consumed, and it has not parked again or ended. It has stopped + // only where the judgement before read it so as well (S14). + if (!stands(stoodState('pause_gone', runId))) { + return { + answer: 'undetermined', + why: aged + ? `the run '${runId}' reports paused, and no pause of it can be found; the judgement before this one did not read the same, so a process may be resuming it, and the next judgement places it if it still reads so.` + : `the run '${runId}' reports paused, and no pause of it can be found.`, + }; + } + const stop = stopOf(steps, 'failed'); + const routed = routedFailure(stop); + if (routed) return { answer: 'read', over: false, stopped: true, endedWhy: routedWhy(routed), children }; + return { + answer: 'read', over: false, stopped: true, children, + ...(stop && standsBetweenSteps(stamp, flow, stop) + ? { endedWhy: `its run '${runId}' reports paused at a pause that is gone, so it will not go on, between two steps.` } + : {}), + }; + } + // The run did not go on past the node it is parked at. + children = childRunsOf(steps, false, parked.nodeId, speaks); + // [ruling B2 on #37767] The latest request's own run, still parked at + // the node its decision was recorded on: the run was not resumed. + if (String(runId) === String(latest.flow_run_id ?? '') && parked.nodeId === String(latest.flow_node_id ?? '')) { + return { answer: 'own_node', flow: parked.flowName ?? flow, children }; + } + if (standsBetweenSteps(stamp, parked.flowName ?? flow, parked.nodeId)) { + // Parked between two steps. On a child run, it says what the child + // says, and the walk reads the child ({@link waitingRun}); on + // anything else, a step can still follow. + const correlation = typeof parked.correlation === 'string' ? parked.correlation : ''; + const child = childOfCorrelation(correlation); + return child + ? { answer: 'waits', on: child, item: correlation.startsWith('map:'), node: parked.nodeId, children } + : { answer: 'in_progress', children }; + } + // Parked outside the set (M3 of 7255916895): a routed failure before + // the pause still ended the approval between two steps. + const routed = routedFailure(undefined); + return { answer: 'read', over: false, children, ...(routed ? { endedWhy: routedWhy(routed) } : {}) }; + } + if (!TERMINAL_RUN_STATUSES.has(status)) { + return { answer: 'undetermined', why: `the run '${runId}' reports the status '${status}', which the plugin does not place.` }; + } + + const stop = stopOf(steps, status); + const routed = routedFailure(stop); + if (routed) { + return { answer: 'read', over: true, endedWhy: routedWhy(routed), endedAt: typeof routed.startedAt === 'string' ? routed.startedAt : undefined, children }; + } + if (REACHED_AN_END.has(status)) return { answer: 'read', over: true, children }; + // A run that ended before the approval's latest request opened did not + // stop it: the approval went on. + const answered = instantOf(run.completedAt) < lastOpened; + const endedAt = typeof run.completedAt === 'string' ? run.completedAt : undefined; + if (!stop) { + return { answer: 'read', over: true, children, ...(answered ? {} : { endedWhy: `its run '${runId}' ended ${status}, at a node the plugin cannot place.`, endedAt }) }; + } + if (!answered && standsBetweenSteps(stamp, flow, stop)) { + return { answer: 'read', over: true, endedWhy: `its run '${runId}' ended ${status} at node '${stop}', between two steps.`, endedAt, children }; + } + return { answer: 'read', over: true, children }; + } + + /** + * [ADR-0162 Execution item 8, ruling A3 on #37767] Keep `kept` on + * `latest`'s snapshot ({@link RUNS_READ_KEY}), where it differs from what + * the approval kept; `latest` is updated in place, so a later write of its + * snapshot in the same judgement carries it. + * + * The reading is a cache of what the runs showed, and the snapshot also + * holds facts other writers leave between this judgement's read of the row + * and this write: the note that a later step could not open + * (`__laterStepNotOpened`) and the journal of a failed resume + * (`__strandedContinuation`). So it writes its own key only, onto the + * snapshot read again just before the write, and the write is conditional: + * it lands only while the column still reads what the key was set on. A + * write that finds the column changed reads it again, at most + * {@link KEEP_RUNS_READ_ATTEMPTS} times. It can therefore not write a + * stale snapshot over another writer's note, whenever that note lands. + * + * Best-effort: a reading that is not kept leaves the runs to be read + * again, and leaves on the request the reading kept before it, its states + * included ({@link stoodState}). The next judgement stands on that + * earlier reading, which is not the one before it: where it holds the + * same state for the same run, the run is placed on it; where it holds + * none, nothing is placed. So an approval whose reading is never kept is + * held with no end (N29 of delta review 7270552441). The condition of the + * write is the column as read just before it, so of two judgements at + * once the one that read first can write last. It answers whether `kept` + * is on the approval's rows now, which a judgement that relies on the + * next one reading on from it asks ({@link readCarryingRun}); the + * judgement that places a state does not ask. + */ + private async keepRunsRead(latest: any, approval: readonly any[], kept: RunsRead | undefined): Promise { + if (!kept || !latest?.id) return false; + if (sameRunsRead(runsReadOf(approval), kept)) return true; + try { + for (let attempt = 0; attempt < KEEP_RUNS_READ_ATTEMPTS; attempt++) { + const rows = await this.engine.find('sys_approval_request', { + where: { id: latest.id }, fields: ['id', 'node_config_json'], limit: 1, context: SYSTEM_CTX, + }); + const current: any = Array.isArray(rows) ? rows[0] : undefined; + if (!current) return false; + const before: unknown = current.node_config_json; + const node_config_json = JSON.stringify({ ...parseJson>(before, {}), [RUNS_READ_KEY]: kept }); + // The predicate form: the engine answers how many rows it wrote. + const landed = await this.engine.update('sys_approval_request', { node_config_json }, { + where: { id: latest.id, node_config_json: typeof before === 'string' ? before : { $null: true } }, + multi: true, context: SYSTEM_CTX, + }); + if (Number(landed) > 0) { + latest.node_config_json = node_config_json; + return true; + } + } + this.logger?.warn?.('[approvals] could not keep what was read of an approval\'s runs: its request\'s snapshot kept changing under the write; the next judgement reads them again', { + request: latest.id, + }); + } catch (err: any) { + this.logger?.warn?.('[approvals] could not keep what was read of an approval\'s runs; the next judgement reads them again', { + request: latest.id, error: err?.message ?? String(err), + }); } + return false; + } - 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')}).`, - }; - } - // 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 }; + /** + * [ADR-0162 Execution item 8, ruling A3 on #37767] What a request that is + * opening keeps of its approval's runs: what the plugin can read from the + * run that carries the record, the request's own run and the runs the + * approval kept as open, down the child runs their steps name, kept by the + * rule every reading keeps by ({@link runsReadAfter}): a run is kept as + * ended only once every child it names is. Every failure before this + * opening is answered by it, so none is kept. A run being advanced is read + * from what it logged when it last paused, so the run opening the + * approval's first request, which has logged nothing yet, is read at the + * first door. `undefined` where nothing is kept. Best-effort and never + * throws: a run it cannot read is read at the next door. + */ + private async runsReadAtOpening(row: { + 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 settled = new Set(prior.ended); + const ownRuns = new Set([...approval.map((r) => String(r?.flow_run_id ?? '')), String(row.flow_run_id ?? '')].filter(Boolean)); + const found = noRunsFound(); + const queue: ChildRunRef[] = [{ id: rootId, item: false, passed: false }]; + if (row.flow_run_id && String(row.flow_run_id) !== rootId) queue.push({ id: String(row.flow_run_id), item: false, passed: false }); + for (const id of prior.open) queue.push({ id, item: false, passed: false }); + const seen = new Set(); + while (queue.length > 0 && seen.size < MAX_RUNS_READ_PER_APPROVAL) { + const { id, item, passed } = queue.shift()!; + if (passed) found.passed.add(id); + if (seen.has(id) || settled.has(id)) continue; + seen.add(id); + let run: { status?: string; trigger?: { object?: string; recordId?: string }; steps?: unknown; + summary?: { nodes?: ReadonlyArray<{ runs?: number; skipped?: number }>; detailOmitted?: boolean }; + } | null; + try { + run = await this.automation.getRun(id, { strict: true }); + } catch { + continue; + } + if (!run) { + found.noRow.add(id); + continue; + } + const record = run.trigger?.recordId; + const status = typeof run.status === 'string' ? run.status : ''; + if (item && !ownRuns.has(id) && record != null && record !== '' + && (String(record) !== String(row.record_id) || (run.trigger?.object != null && String(run.trigger.object) !== String(row.object_name)))) { + // An item run of another record is kept as ended once it has ended. + if (TERMINAL_RUN_STATUSES.has(status)) found.foreign.add(id); + continue; + } + const steps = (Array.isArray(run.steps) ? run.steps : []) as RunStepRead[]; + // A cut log names its children in part and speaks for none: its run is not kept as ended. + const whole = stepLogCut(run, steps, TERMINAL_RUN_STATUSES.has(status)) === undefined; + const children = childRunsOf(steps, REACHED_AN_END.has(status), undefined, whole); + if (whole) found.childrenOf.set(id, children.map((c) => c.id)); + if (TERMINAL_RUN_STATUSES.has(status)) found.terminal.add(id); + queue.push(...children); } + const kept = runsReadAfter(prior, found, undefined); + return kept.ended.length === 0 && kept.open.length === 0 ? undefined : kept; + } catch (err: any) { + this.logger?.warn?.('[approvals] could not read an approval\'s runs as its request opened; the next door reads them', { + error: err?.message ?? String(err), + }); + return undefined; } - return { answer: 'finished' }; } /** @@ -5603,13 +6714,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 +6758,97 @@ 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, up to + * the run that carries the record, deepest first: nothing resumes the + * approval on a record that was put back. + * + * The chain goes through a `map` as through a `subflow`. A `map` between + * the run that carries the record and the parked run has items that are + * not records, so its items are steps of this one approval: the batch is + * cancelled with its item, and is not woken to start the next item, which + * would open a step of the abandoned approval. (A batch whose items are + * records sits above the run that carries the record, and is not in the + * chain.) + * + * A cancel that fails is logged; the approval stays abandoned, and the + * door that continues a restored run refuses it. + */ + private async cancelStoppedRun(latest: any, runId: string, why: string): Promise { + if (typeof this.automation?.cancelRun !== 'function') { + 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', + { throughMap: true }, + ); + 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 could not be seen + * through to its end after that step, so the flow's nodes after it may not + * have run: the run did not go on, has no row, or could not be read in full + * (a cut step log, a tree of more runs than the judgements read). The + * notice asks for a check and states no failure (N19 of contract review + * 7266979193). The run's pause, where it has one, is left for an operator + * to continue or cancel. + * Sent once per request, and only on the pass whose outcome write landed + * (ruling 3 on #37767). + */ + 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 could not be seen through to its end after its last step', { + request: latest.id, organizationId: org, error: admins.failure, + }); + } + } catch (err: any) { + this.logger?.warn?.('[approvals] could not tell the organization\'s administrators that a flow could not be seen through to its end 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 +6868,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 +7255,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 +8106,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, @@ -8933,16 +10171,21 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * below its lowest `map:` link. `[runId]` alone when there is nothing to * walk (no record run, silently), or when the walk cannot be completed * (told at `warn`). + * + * `throughMap` is {@link cancelStoppedRun}'s: the chain is not cut at a + * `map:` link, so the batch and the runs above it are in it. */ private async voidedRunChain( requestId: string, runId: string, recordRunId: string | undefined, + whose = 'whose approval a record delete voided', + opts?: { throughMap?: boolean }, ): Promise { if (!recordRunId || recordRunId === runId) return [runId]; const alone = (why: string, error?: unknown): string[] => { 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) } : {}) }, ); @@ -8959,7 +10202,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const correlation: string = parked?.correlation ?? ''; if (correlation.startsWith('map:')) { // A batch stays a batch: the chain starts again below it. - chain.length = 0; + if (!opts?.throughMap) chain.length = 0; current = correlation.slice('map:'.length) || undefined; } else if (correlation.startsWith('subflow:')) { current = correlation.slice('subflow:'.length) || undefined; @@ -10382,6 +11625,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 +12329,167 @@ 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 two + * passes in a row read in the same of these states, the first of which + * may be a pass within the bound or a door (rulings A3 and B2 on #37767; + * S14 of delta review 7269135624, {@link stoodState}): a run that reports + * paused while its pause is gone, a run parked at a `subflow` or a `map` + * whose child run has ended or has no row (an item run of a `map` that + * carries another record included, once it is in a terminal status), and, + * as one rule, a run with no row that no run read speaks for, a run whose + * step log is cut ({@link stepLogCut}), a tree of more runs than one + * judgement reads once a judgement keeps no run the approval had not kept + * ({@link MAX_RUNS_READ_PER_APPROVAL}), and the latest request's own run + * still parked at the step its decision was recorded on (at whatever depth + * below the run that carries the record), each of which has stopped at the + * step last decided. Where a step can follow it, the approval is abandoned (and + * a run still parked there is cancelled, with the runs that wait on it); + * where none can, the outcome is written and, once it has landed, the + * administrators are told that the flow could not be seen through to its + * end after its last step. + * + * What each judgement reads of the runs is kept on the approval's latest + * request ({@link RunsRead}), so a pass reads on from where the last one + * stopped: a run is not read again only once it and every run below it + * were read to an end. + * + * A refused outcome or put-back leaves the marks, so the next pass tries it + * again; the mirror's notice to the administrators is keyed per request and + * 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. + * Each of the states it holds within the age bound is placed past it, + * once a reading of that state is kept and the next one reads the same. + * That has an end where the kept write lands; an approval whose reading + * is never kept, and that kept no such state before, is held with no end + * ({@link keepRunsRead}). What also stays cannot tell at any age is a run + * that cannot be read (a store that does not answer, a run that reports a + * status the plugin does not place or that another process is advancing): + * it is read again on the next pass. + * + * 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..5f995e5dcd9 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 could not be seen through to its end', + approvalFlowNotContinuedBody: 'The approval of {{object}} {{record}} was decided at its last step and the decision was written, but its flow could not be seen through to its end after that step, so the steps that follow it may not have run. Check the approval\'s flow run: where it is still paused, continue or cancel it; where it has ended or no run is left, check that the steps after the decision were done.', approvalReturnedTitle: 'Sent back for revision', approvalReturnedBody: 'Your {{object}} {{record}} needs rework before it can be approved.', 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: 'No se pudo comprobar que el flujo de la aprobación llegara al final', + approvalFlowNotContinuedBody: 'La aprobación de {{object}} {{record}} se decidió en su último paso y la decisión se escribió, pero no se pudo comprobar que su flujo continuara hasta el final después de ese paso, así que es posible que los pasos siguientes no se hayan ejecutado. Revise la ejecución del flujo de la aprobación: si sigue en pausa, continúela o cancélela; si ya terminó o no queda ninguna ejecución, compruebe que se hicieron los pasos posteriores a la decisión.', approvalReturnedTitle: 'Devuelto para revisión', approvalReturnedBody: 'Su {{object}} {{record}} necesita cambios antes de poder aprobarse.', 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 pu être vérifié jusqu’à son terme', + approvalFlowNotContinuedBody: 'L’approbation de {{object}} {{record}} a été décidée à sa dernière étape et la décision a été écrite, mais il n’a pas pu être vérifié que son flux s’est poursuivi jusqu’à son terme après cette étape : les étapes suivantes n’ont peut-être pas été exécutées. Vérifiez l’exécution du flux de l’approbation : si elle est encore en pause, poursuivez-la ou annulez-la ; si elle est terminée ou s’il n’en reste aucune, vérifiez que les étapes qui suivent la décision ont été faites.', approvalReturnedTitle: 'Renvoyé pour révision', approvalReturnedBody: 'Votre demande sur {{object}} {{record}} doit être retravaillée avant de pouvoir être approuvée.', 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: 'Não foi possível confirmar que o fluxo da aprovação foi até o fim', + approvalFlowNotContinuedBody: 'A aprovação de {{object}} {{record}} foi decidida em sua última etapa e a decisão foi gravada, mas não foi possível confirmar que o fluxo continuou até o fim depois dessa etapa, então as etapas seguintes podem não ter sido executadas. Verifique a execução do fluxo da aprovação: se ainda estiver pausada, continue-a ou cancele-a; se já tiver terminado ou não restar nenhuma execução, confira se as etapas após a decisão foram feitas.', approvalReturnedTitle: 'Devolvido para revisão', approvalReturnedBody: 'Sua solicitação sobre {{object}} {{record}} precisa de ajustes antes de poder ser aprovada.', 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 ließ sich nicht bis zum Ende nachvollziehen', + approvalFlowNotContinuedBody: 'Die Genehmigung zu {{object}} {{record}} wurde in ihrem letzten Schritt entschieden und die Entscheidung geschrieben, aber es ließ sich nicht feststellen, dass ihr Ablauf nach diesem Schritt bis zum Ende fortgesetzt wurde, sodass die folgenden Schritte möglicherweise nicht ausgeführt wurden. Prüfen Sie den Ablauf der Genehmigung: Ist er noch pausiert, setzen Sie ihn fort oder brechen Sie ihn ab; ist er beendet oder kein Lauf mehr vorhanden, prüfen Sie, ob die Schritte nach der Entscheidung erledigt wurden.', approvalReturnedTitle: 'Zur Überarbeitung zurückgesendet', approvalReturnedBody: 'Ihre Anfrage zu {{object}} {{record}} muss überarbeitet werden, bevor sie genehmigt werden kann.', approvalRequestInfoTitle: 'Weitere Informationen angefordert', @@ -1088,6 +1108,8 @@ export const koMessages: ApprovalMessages = { approvalAutoRejectedBody: '{{object}} {{record}}이(가) 수정 횟수 한도({{limit}})를 넘어 반려되었습니다.', approvalAbandonedTitle: '승인이 완료되지 않았습니다', approvalAbandonedBody: '{{object}} {{record}}의 승인이 두 단계 사이에서 멈춰 완료되지 않았고, 레코드는 열린 상태로 되돌아갔습니다. 준비가 되면 다시 제출하세요.', + approvalFlowNotContinuedTitle: '승인 흐름이 끝까지 진행되었는지 확인할 수 없습니다', + approvalFlowNotContinuedBody: '{{object}} {{record}}의 승인은 마지막 단계에서 결정되었고 결정도 기록되었지만, 그 단계 이후 흐름이 끝까지 진행되었는지 확인할 수 없어 이후 단계가 실행되지 않았을 수 있습니다. 승인의 흐름 실행을 확인하세요. 아직 일시 중지되어 있으면 계속하거나 취소하고, 실행이 끝났거나 남은 실행이 없으면 결정 이후의 단계가 수행되었는지 확인하세요.', approvalReturnedTitle: '수정 요청됨', approvalReturnedBody: '{{object}} {{record}}을(를) 승인받으려면 먼저 수정해야 합니다.', approvalRequestInfoTitle: '추가 정보 요청', diff --git a/packages/services/service-messaging/src/preference-options.ts b/packages/services/service-messaging/src/preference-options.ts index f5d9b3fde07..dd1084bc933 100644 --- a/packages/services/service-messaging/src/preference-options.ts +++ b/packages/services/service-messaging/src/preference-options.ts @@ -55,6 +55,7 @@ export const PLATFORM_NOTIFICATION_TOPICS: readonly string[] = [ 'approval.comment', 'approval.escalated', + 'approval.flow_not_continued', 'approval.ooo_skipped', 'approval.ooo_substituted', 'approval.reassigned',