From 1195142e5d2f817b986faf0feaa6569ff0057daa Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 10:47:06 +0000 Subject: [PATCH 1/5] feat(automation): a delegating step records the child runs it started A subflow step names the run it started on every exit, and a map step the item runs that execution started (childRunIds on the step log, ADR-0162 Execution item 8). A run that ends inside execute answers no runId, so the engine names the run it started for a context (runStartedFor), which the subflow and map nodes read. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5pigknx7rC8rXnA3my --- .changeset/37767-step-child-runs.md | 16 +++ .../docs/references/automation/execution.mdx | 2 + .../src/builtin/map-node.ts | 13 ++ .../src/builtin/subflow-node.ts | 9 ++ .../service-automation/src/dag-traversal.ts | 19 ++- .../services/service-automation/src/engine.ts | 37 ++++++ .../src/step-child-runs.test.ts | 112 ++++++++++++++++++ .../spec/authorable-surface/automation.json | 1 + packages/spec/src/automation/execution.zod.ts | 6 + 9 files changed, 214 insertions(+), 1 deletion(-) create mode 100644 .changeset/37767-step-child-runs.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..e6dc9285f46 --- /dev/null +++ b/.changeset/37767-step-child-runs.md @@ -0,0 +1,16 @@ +--- +'@objectstack/spec': patch +'@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: the run log's step entry (`ExecutionStepLogSchema`) gains the optional, engine-written `childRunIds: string[]`; `AutomationEngine` gains the public read `runStartedFor(context)`, and a node executor's result (`NodeExecutionResult`) the optional `childRunIds`. + +- **`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. `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; `undefined` where no run started. Under `errorHandling.strategy: 'retry'` it is the last attempt's run. The `subflow` and `map` nodes read it for a child that ended inside the call. + +Unchanged: what a run does, the `runId` the contract returns, and every existing step field. 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..f4beee46551 100644 --- a/packages/services/service-automation/src/builtin/map-node.ts +++ b/packages/services/service-automation/src/builtin/map-node.ts @@ -216,6 +216,11 @@ 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. + const startedRuns: string[] = []; + const rolledRuns = (): { childRunIds?: string[] } => (startedRuns.length > 0 ? { childRunIds: [...startedRuns] } : {}); const rolledDrops = () => { const droppedFields = foldDropEvents(itemDrops); return droppedFields ? { droppedFields } : {}; @@ -260,6 +265,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 +285,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 +316,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 +361,7 @@ export function registerMapNode(engine: AutomationEngine, ctx: PluginContext): v : rolledFailures()), }, ...rolledDrops(), + ...rolledRuns(), }; } // Synchronous completion — record and advance. @@ -401,6 +413,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..8c327b1472e 100644 --- a/packages/services/service-automation/src/builtin/subflow-node.ts +++ b/packages/services/service-automation/src/builtin/subflow-node.ts @@ -123,6 +123,12 @@ 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: 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. + 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 +144,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 +184,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 +217,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..4ae34c7b825 100644 --- a/packages/services/service-automation/src/dag-traversal.ts +++ b/packages/services/service-automation/src/dag-traversal.ts @@ -121,6 +121,19 @@ export function runUserOf(context: AutomationContext | undefined): EvalUserParse * nothing well-typed left is omitted, never `[]`. Total, never throwing: it * runs inside the step's `try`, where a throw would read as a node failure. */ +/** + * [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 } : {}; +} + function stepAdvisoriesOf(result: NodeExecutionResult): { warnings?: string[]; droppedFields?: DroppedFieldsEvent[] } { const out: { warnings?: string[]; droppedFields?: DroppedFieldsEvent[] } = {}; const rawWarnings: unknown = result.warnings; @@ -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 }, @@ -1402,6 +1418,7 @@ export async function executeWithoutRetry( const runId = this.nextRunId(); const startedAt = new Date().toISOString(); const steps: StepLogEntry[] = []; + this.noteRunStarted(context, runId); // ADR-0049 / #1888 — establish the run's effective execution identity // from flow.runAs (see execute() / resolveRunContext); threaded below. diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index 32d6bba6bdc..1354f5dced8 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -471,6 +471,14 @@ 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. 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. + */ + 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 @@ -3812,6 +3820,33 @@ 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, or its + * start condition skipped it). Under `errorHandling.strategy: 'retry'` it + * is the last attempt's 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 @@ -8370,6 +8405,7 @@ export class AutomationEngine implements IAutomationService { const runId = this.nextRunId(); const startedAt = new Date().toISOString(); const steps: StepLogEntry[] = []; + this.noteRunStarted(context, runId); // ADR-0049 / #1888 — establish the run's effective execution identity // from flow.runAs (a COPY, never mutating the caller's context, so the @@ -12280,6 +12316,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/step-child-runs.test.ts b/packages/services/service-automation/src/step-child-runs.test.ts new file mode 100644 index 00000000000..a934926429e --- /dev/null +++ b/packages/services/service-automation/src/step-child-runs.test.ts @@ -0,0 +1,112 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [ADR-0162 Execution item 8] A delegating step records the child runs it +// started (`childRunIds` on its step log entry): the one run of a `subflow`, +// on every exit, and for a `map` the item runs this execution of the step +// started. The approvals plugin follows the link to read every run of an +// approval's tree. A child that ends inside the call answers no `runId`, so +// the engine names the run it started for the context it was handed +// (`runStartedFor`). + +import { describe, it, expect, vi } from 'vitest'; +import { AutomationEngine } from './engine.js'; +import { InMemoryFlowActivationStore } from './flow-activation-store.js'; +import { + registerSubflowNode, + registerMapNode, + registerWaitNode, + registerLogicNodes, +} from './builtin/index.js'; +import type { AutomationContext } from '@objectstack/spec/contracts'; +import { withLoaderSetFromPull } from './loader-set.test-support.js'; + +function createTestLogger(): any { + const l: any = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; + l.child = () => 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 } }); + +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(); + }); +}); 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 907f848e6600c70329f66d1100fdd28cbd2f2c92 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 10:47:06 +0000 Subject: [PATCH 2/5] feat(approvals): the reconciler, and the door reads every run of an approval The door walks the approval's run tree from the run that carries the record through the child runs each step records, so a sibling child, a middle run and a run being advanced are placed (ADR-0162 Execution item 8). The reconciler judges every marked approval oldest first on the sweep clock: a cancelled run, a process that died after a decision, past the age bound a run whose pause is gone or that is parked on an ended child, and a deleted record, whose marks it clears. The stranded-request report leaves stamped requests to it. A refused write tried again leaves its timeline line once. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5pigknx7rC8rXnA3my --- .../37767-outcome-when-approval-over.md | 2 +- .changeset/37767-reconciler.md | 20 + content/docs/automation/approvals.mdx | 56 ++- ...roval-reconciler-37767.integration.test.ts | 451 +++++++++++++++++ .../plugin-approvals/src/approval-service.ts | 462 ++++++++++++++---- .../plugin-approvals/src/approvals-plugin.ts | 4 + 6 files changed, 890 insertions(+), 105 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-outcome-when-approval-over.md b/.changeset/37767-outcome-when-approval-over.md index 131a7031538..dab0dc083cf 100644 --- a/.changeset/37767-outcome-when-approval-over.md +++ b/.changeset/37767-outcome-when-approval-over.md @@ -13,7 +13,7 @@ What changes, only for an approval the check stamped when it opened (one with a - **The decision is held back.** Where the object closes on the step's mirror field at `approved` or `rejected`, neither decision is written onto the record when it is made. The request records it as before, and the field keeps `pending`. Every other status (`pending` as a request opens, `returned` at a send-back, what a recall leaves) is written as before. - **The mark.** Every decision on a request of such an approval sets `unjudged_since` in the update that records it, also where nothing is held back. It is cleared when the approval is judged, and when the approval's next request opens on the record. A recall, an administrator's override and the dead-run sweep clear it on the approval's earlier requests. -- **The door judges the approval.** After a decision (by a person or the SLA clock), a send-back (and its auto-rejection), a resubmission, a recall and the continuation of a restored run, the plugin reads the run that carries the record and the approval's requests on it. Finished (the run completed, stopped after the last step, or is parked at a pause no step can follow): it writes the latest request's decision, as the person who decided it. In progress (a request is open, or the run is parked at a pause a step can follow): nothing. Ended between two steps (the run stopped on a node a step could still follow, a failure the flow routed at the top level ended it, or a later step could not open, whatever the flow did with that): the approval is abandoned. Cannot tell (the run is being advanced or cannot be read): nothing, and the mark stays. +- **The door judges the approval.** After a decision (by a person or the SLA clock), a send-back (and its auto-rejection), a resubmission, a recall and the continuation of a restored run, the plugin reads the run that carries the record and the approval's requests on it. Finished (the 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): it writes the latest request's decision, as the person who decided it. In progress (a request is open, or the run is parked at a pause a step can follow): nothing. Ended between two steps (the run stopped on a node a step could still follow, a failure the flow routed at the top level ended it, or a later step could not open, whatever the flow did with that): the approval is abandoned. Cannot tell (the run is being advanced or cannot be read): nothing, and the mark stays. - **An abandoned approval.** The latest request is marked abandoned, the field is put back by item 7's order (never a closed value, and nothing where another approval's request is open on the record on the same field), a timeline line with no actor says why and what the record was put back to, and the submitter is told on `approval.abandoned` instead of `approval.approved` or `approval.rejected`. The decisions already made stay on their requests. - **A restored run is refused.** `continueRestoredRun` refuses a request of an abandoned approval with `INVALID_STATE` and tells the operator to cancel the restored run. diff --git a/.changeset/37767-reconciler.md b/.changeset/37767-reconciler.md new file mode 100644 index 00000000000..a150a4e7852 --- /dev/null +++ b/.changeset/37767-reconciler.md @@ -0,0 +1,20 @@ +--- +'@objectstack/plugin-approvals': patch +--- + +feat(approvals): the reconciler, and the door reads every run of an approval (ADR-0162 Execution item 8) + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened: `ApprovalService` gains `reconcileMarkedApprovals(options?)`, which the plugin runs on the sweep clock beside the escalation, dead-run and stranded-request sweeps; the `getRun` member of the automation surface the plugin declares types the step log's `childRunIds`. + +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 a `map` item run where it is the run of one of the approval's own requests. One run decides for the whole approval: one that cannot be read or that another process is advancing makes it cannot tell; one parked at a node a step can follow, in progress; one that ended between two steps, abandoned. So a sibling child whose failure the flow routed, a middle run two levels down that failed, and a run between two others that is being advanced are no longer read as finished. A tree of more than 200 runs is cannot tell. +- **The reconciler.** It scans the marked requests (`unjudged_since`), oldest first, at most 200 a pass, and judges each approval among them once, as the door would have: it writes the outcome in the name of the request's recorded decider, abandons the approval, or, where nothing was held back, clears the mark and writes nothing. It ends what no door saw: a run that was cancelled, a parent run cancelled while its child's request was pending, a process that died after a decision. Once every mark of an approval has stood for an hour (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. +- **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 request the check stamped to the reconciler. + +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 e12d0d4f765..4aed1d60192 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 @@ -1559,14 +1560,61 @@ Nothing in the message is the submitter's to fix: every gap is the app's configuration or the host's. Whoever maintains the app fixes the field, the flow or the host, and the submitter then submits again. +### 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 holds a request of the approval. It answers one of: + +- **In progress.** A request is pending or returned on the record, or a run is + parked at a node between two steps. Nothing is written. +- **Ended between two steps.** A run stopped on a node a step could still follow + (it failed or was cancelled there), a failure the flow routed at the top level + of a run ended it, or a later step could not open. The approval is abandoned, + below. +- **Cannot tell.** A run is being advanced by another process, or 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. + +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, oldest first, as the action would have: +after a process that died, a run that was cancelled, or a parent run cancelled +while its child's request was pending. 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. +Where nothing was held back it clears the mark and writes nothing. A write that +a rule or a hook refuses is reported as above, once, and tried again on each +sweep while the mark stands. Where the record was deleted, the reconciler clears +the mark and writes nothing. + ### What an abandoned approval leaves 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, above, 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 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..9da51b85e3a --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-reconciler-37767.integration.test.ts @@ -0,0 +1,451 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D5, Execution item 8 "The reconciler", #37767 piece 4] The door + * reads every run of an approval's tree, and the reconciler judges every + * approval whose mark no door cleared. + * + * The door follows the child runs each delegating step records + * (`childRunIds`): a sibling `subflow` child, a middle run two levels down, + * a run another process is advancing. The reconciler scans the mark oldest + * first and judges each approval as the door would have: a parent run that + * was cancelled while its child's request was pending, a process that died + * between a decision and the write of its outcome, an approval whose field + * the object does not close on, a record deleted in a passage, and, past + * the age bound, a run whose pause is gone and a run parked at a `subflow` + * whose child has ended. + * + * Real kernel, real ObjectQL engine, real automation engine, real approval + * node, driver-sql on better-sqlite3 `:memory:`. + */ + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { APPROVAL_REVISE_NODE_TYPE } from '@objectstack/spec/automation'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { AutomationServicePlugin, type AutomationEngine } from '@objectstack/service-automation'; +import { ApprovalService, RECONCILER_AGE_BOUND_MS } from './approval-service.js'; +import { registerApprovalNode } from './approval-node.js'; +import { SysApprovalRequest } from './sys-approval-request.object.js'; +import { SysApprovalAction } from './sys-approval-action.object.js'; +import { SysApprovalApprover } from './sys-approval-approver.object.js'; +import { SysApprovalDelegation } from './sys-approval-delegation.object.js'; +import { SysApprovalToken } from './sys-approval-token.object.js'; + +const ORG = 'org_default'; +const SYS = { isSystem: true } as const; +const asPerson = (userId: string) => ({ userId, positions: [], permissions: [] }) as any; + +const text = (name: string) => ({ name, type: 'text' as const }); +const PLATFORM_GLOBAL = { enabled: false }; +const authzObjects = [ + { owner: '@objectstack/plugin-auth', def: { name: 'sys_user', label: 'User', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, email: text('email') } } }, + { owner: '@objectstack/plugin-auth', def: { name: 'sys_member', label: 'Member', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), organization_id: text('organization_id'), role: text('role') } } }, + { owner: '@objectstack/plugin-security', def: { name: 'sys_user_position', label: 'User Position', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), position: text('position'), organization_id: text('organization_id') } } }, + { owner: '@objectstack/plugin-security', def: { name: 'sys_user_permission_set', label: 'User Permission Set', tenancy: PLATFORM_GLOBAL, fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), permission_set: text('permission_set'), organization_id: text('organization_id') } } }, +] as const; + +const statusField = { + name: 'approval_status', type: 'select' as const, defaultValue: 'draft', + options: ['draft', 'pending', 'returned', 'approved', 'rejected', 'recalled'].map((value) => ({ label: value, value })), +}; +const fields = { name: text('name'), approval_status: statusField, stage: text('stage') }; +/** Closes on its approval's outcome, both ways. */ +const invoice = { name: 'crm_invoice', label: 'Invoice', fields, closedStates: { approval_status: ['approved', 'rejected'] } }; +/** Closes on `approved` alone: a rejected order moves on. */ +const order = { name: 'crm_order', label: 'Order', fields, closedStates: { approval_status: ['approved'] } }; +/** Closes on `rejected` alone: an approved claim moves on. */ +const claim = { name: 'crm_claim', label: 'Claim', fields, closedStates: { approval_status: ['rejected'] } }; +/** Declares closed states, on another field than the approval's: its approval holds nothing back. */ +const ticket = { name: 'crm_ticket', label: 'Ticket', fields, closedStates: { stage: ['done'] } }; +/** Declares no closed state: the control, which behaves as before. */ +const memo = { name: 'crm_memo', label: 'Memo', fields }; + +const step = (id: string, approver: string, extra: Record = {}) => ({ + id, type: 'approval', label: id, + config: { approvers: [{ type: 'user', value: approver }], approvalStatusField: 'approval_status', ...extra }, +}); +const mark = (id: string) => ({ id, type: 'mark', label: id }); +const START = { id: 'start', type: 'start', label: 'Start' }; +const END = { id: 'end', type: 'end', label: 'End' }; +const edge = (source: string, target: string, label?: string, type?: string) => + ({ id: `${source}_${target}_${label ?? type ?? ''}`, source, target, ...(label ? { label } : {}), ...(type ? { type } : {}) }); +const flow = (name: string, nodes: unknown[], edges: unknown[], extra: Record = {}) => + ({ name, label: name, type: 'autolaunched', nodes: [START, ...nodes, END], edges, ...extra }); +/** `a` then `b`, each step's reject edge to the end. */ +const decided = (a: string, b: string) => [edge(a, b, 'approve'), edge(a, 'end', 'reject')]; + +const FLOWS = [ + flow('child_one_step', [step('only', 'approver')], [edge('start', 'only'), edge('only', 'end', 'approve'), edge('only', 'end', 'reject')]), + // A sibling child after the child that holds the first step: a node that + // fails before its step, routed to the child's end. + flow('child_boom_then_step', [mark('boom'), step('second', 'approver2')], + [edge('start', 'boom'), edge('boom', 'second'), edge('boom', 'end', undefined, 'fault'), ...decided('second', 'end')]), + flow('parent_two_subs', [ + { id: 'sub1', type: 'subflow', label: 'First', config: { flowName: 'child_one_step' } }, + { id: 'sub2', type: 'subflow', label: 'Second', config: { flowName: 'child_boom_then_step' } }], + [edge('start', 'sub1'), edge('sub1', 'sub2'), edge('sub2', 'end')]), + // Two levels down: the root delegates to a middle run, which delegates the + // first step and holds the second after a node that fails, unrouted. + flow('middle_boom', [{ id: 'inner', type: 'subflow', label: 'Inner', config: { flowName: 'child_one_step' } }, mark('boom'), step('second', 'approver2')], + [edge('start', 'inner'), edge('inner', 'boom'), edge('boom', 'second'), ...decided('second', 'end')]), + flow('root_of_middle', [{ id: 'mid', type: 'subflow', label: 'Middle', config: { flowName: 'middle_boom' } }], + [edge('start', 'mid'), edge('mid', 'end'), edge('mid', 'end', undefined, 'fault')]), + // A child step, then a step in the parent. + flow('sub_then_second', [{ id: 'sub', type: 'subflow', label: 'Approval', config: { flowName: 'child_one_step' } }, step('second', 'approver2')], + [edge('start', 'sub'), edge('sub', 'second'), ...decided('second', 'end')]), + // A node between the two steps that fails, unrouted: the run fails there. + flow('boom_between', [step('first', 'approver'), mark('boom'), step('second', 'approver2')], + [edge('start', 'first'), edge('first', 'boom', 'approve'), edge('first', 'end', 'reject'), edge('boom', 'second'), ...decided('second', 'end')]), + flow('two_step', [step('first', 'approver'), step('second', 'approver2')], + [edge('start', 'first'), ...decided('first', 'second'), ...decided('second', 'end')]), + // A send-back past the limit auto-rejects the second step, whose reject + // edge runs a node that fails before the third step, routed to the end. + flow('spent_then_boom', [step('first', 'approver'), step('second', 'approver2', { maxRevisions: 0 }), + { id: 'revise', type: APPROVAL_REVISE_NODE_TYPE, label: 'Revise' }, mark('boom'), step('third', 'approver')], + [edge('start', 'first'), ...decided('first', 'second'), edge('second', 'third', 'approve'), edge('second', 'boom', 'reject'), + edge('second', 'revise', 'revise'), { id: 'back', source: 'revise', target: 'second', label: 'resubmit', type: 'back' }, + edge('boom', 'third'), edge('boom', 'end', undefined, 'fault'), ...decided('third', 'end')]), +]; + +describe('[ADR-0162 item 8] the door reads every run, and the reconciler judges what no door did', () => { + let kernel: ObjectKernel; + let ql: ObjectQL; + let automation: AutomationEngine; + let svc: ApprovalService; + /** Nodes of type `mark` that throw, by id. */ + let throwOn: Set; + /** What each `read` node saw on the record's field. */ + let seen: unknown[]; + let notices: Array<{ topic: string; audience: string[] }>; + let infos: string[]; + + afterEach(async () => { + try { await kernel?.shutdown(); } catch { /* noop */ } + }); + + beforeEach(async () => { + throwOn = new Set(); + seen = []; + notices = []; + kernel = new ObjectKernel({ logger: { level: 'silent' } } as any); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(new AutomationServicePlugin()); + await kernel.bootstrap(); + ql = kernel.getService('objectql'); + automation = kernel.getService('automation'); + + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + await driver.connect(); + ql.registerDriver(driver, true); + for (const def of [invoice, order, claim, ticket, memo, SysApprovalRequest, SysApprovalAction, SysApprovalApprover, SysApprovalDelegation, SysApprovalToken]) { + ql.registry.registerObject(def as any, 'approvals-test', 'approvals-test'); + } + for (const o of authzObjects) ql.registry.registerObject(o.def as any, o.owner); + ql.registry.registerObject( + { name: 'sys_organization', label: 'Organization', managedBy: 'better-auth', fields: { name: text('name'), slug: text('slug') } } as any, + '@objectstack/plugin-auth', + ); + await ql.syncSchemas(); + await ql.insert('sys_organization', { id: ORG, name: 'Default Organization', slug: 'default' }, { context: SYS }); + for (const id of ['owner', 'approver', 'approver2']) { + await ql.insert('sys_user', { id, email: `${id}@example.test` }, { context: SYS }); + await ql.insert('sys_member', { id: `mem_${id}`, user_id: id, organization_id: ORG, role: 'member' }, { context: SYS }); + } + const quiet = { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} }; + infos = []; + const heard = { ...quiet, info: (m: unknown) => { infos.push(String(m)); } }; + svc = new ApprovalService({ engine: ql, logger: heard as any }); + svc.noteSweepClockScheduled(); + svc.attachMessaging({ emit: async (n: any) => { notices.push({ topic: n.topic, audience: n.audience }); } } as any); + svc.attachAutomation(automation as any); + registerApprovalNode(automation as any, svc, quiet as any); + (automation as any).registerNodeExecutor({ + type: 'mark', + descriptor: { type: 'mark', supportsPause: false }, + async execute(node: any, _variables: any, context: any) { + if (throwOn.has(node.id)) throw new Error(`${node.id} failed`); + if (node.id === 'read') { + const id = context?.record?.id; + seen.push((await ql.find(context?.object ?? 'crm_invoice', { where: { id }, context: SYS }))[0]?.approval_status); + } + return { success: true }; + }, + }); + for (const f of FLOWS) automation.registerFlow(f.name, f as any); + }); + + const read = async (object: string, id: string) => (await ql.find(object, { where: { id }, context: SYS }))[0]; + const field = async (object: string, id: string) => (await read(object, id))?.approval_status; + const requestsOn = async (id: string) => + (await ql.find('sys_approval_request', { where: { record_id: id }, orderBy: [{ field: 'created_at', order: 'asc' }], context: SYS })) as any[]; + const steps = async (id: string) => (await requestsOn(id)).map((r) => [r.flow_node_id, r.status]); + const marks = async (id: string) => (await requestsOn(id)).map((r) => r.unjudged_since != null); + const pendingOn = async (id: string) => (await requestsOn(id)).find((r) => r.status === 'pending' || r.status === 'returned'); + const timeline = async (requestId: string) => + (await ql.find('sys_approval_action', { where: { request_id: requestId }, orderBy: [{ field: 'created_at', order: 'asc' }], context: SYS }) as any[]) + .map((a) => [a.action, a.actor_id ?? null, a.comment ?? null]); + const seed = (object: string, id: string) => + ql.insert(object, { id, name: id, organization_id: ORG }, { context: { isSystem: true, tenantId: ORG } }); + const start = async (name: string, object: string, id: string) => { + await seed(object, id); + return automation.execute(name, { object, record: await read(object, id), userId: 'owner' } as any) as Promise; + }; + const decide = async (id: string, decision: 'approve' | 'reject', who: string) => + svc.decide(String((await requestsOn(id)).find((r) => r.status === 'pending').id), { decision, actorId: who, ...(decision === 'reject' ? { comment: 'no' } : {}) } as any, asPerson(who)); + const settle = (p: Promise) => p.then((v) => ({ ok: v as T }), (e: any) => ({ error: e as Error })); + + + /** Run `fn` with no door judging: the shape a process that died after the door's own action leaves. */ + const withoutDoor = async (fn: () => Promise): Promise => { + const judge = (svc as any).judgeApprovalAfterDoor; + (svc as any).judgeApprovalAfterDoor = async () => 'undetermined'; + try { return await fn(); } finally { (svc as any).judgeApprovalAfterDoor = judge; } + }; + /** Move every mark on the record's requests past the reconciler's age bound. */ + const age = async (id: string) => { + const past = new Date(Date.now() - 2 * RECONCILER_AGE_BOUND_MS).toISOString(); + for (const r of await requestsOn(id)) { + if (r.unjudged_since != null) await ql.update('sys_approval_request', { id: r.id, unjudged_since: past }, { context: SYS }); + } + }; + const recordWrites = (object: string) => { + const writes: unknown[] = []; + const original = ql.update.bind(ql); + (ql as any).update = async (o: string, data: any, options?: any) => { + if (o === object && 'approval_status' in (data ?? {})) writes.push([data.approval_status, options?.context?.userId ?? null]); + return original(o, data, options); + }; + return writes; + }; + + describe('the door reads every run of the approval', () => { + it('a sibling subflow child whose node failed before its step, routed to its end: abandoned, not finished', async () => { + await start('parent_two_subs', 'crm_invoice', 'i_sib'); + throwOn.add('boom'); + await decide('i_sib', 'approve', 'approver'); + const [first] = await requestsOn('i_sib'); + expect((await automation.getRun(String(first.record_run_id)))?.status, 'the carrying run completed').toBe('completed'); + expect(await steps('i_sib'), 'the second step was never asked').toEqual([['only', 'approved']]); + expect(await field('crm_invoice', 'i_sib')).toBe('recalled'); + expect((await timeline(String(first.id))).at(-1)![2]).toMatch(/its node 'boom' failed between two steps/); + expect(await marks('i_sib')).toEqual([false]); + }); + + it('the delegating steps record the child runs they started', async () => { + await start('parent_two_subs', 'crm_invoice', 'i_links'); + await decide('i_links', 'approve', 'approver'); + const [first] = await requestsOn('i_links'); + const root: any = await automation.getRun(String(first.record_run_id)); + const sub1 = root.steps.filter((s: any) => s.nodeId === 'sub1'); + expect(sub1.length).toBeGreaterThan(0); + for (const s of sub1) expect(s.childRunIds).toEqual([String(first.flow_run_id)]); + const sub2 = root.steps.find((s: any) => s.nodeId === 'sub2'); + expect(sub2.childRunIds).toHaveLength(1); + expect(sub2.childRunIds[0]).not.toBe(String(first.flow_run_id)); + expect(root.steps.find((s: any) => s.nodeId === 'start').childRunIds).toBeUndefined(); + }); + + it('a middle run, two levels down, that failed between two steps: abandoned', async () => { + await start('root_of_middle', 'crm_invoice', 'i_mid'); + throwOn.add('boom'); + await settle(decide('i_mid', 'approve', 'approver')); + const [first] = await requestsOn('i_mid'); + expect(await steps('i_mid')).toEqual([['only', 'approved']]); + expect(await field('crm_invoice', 'i_mid')).toBe('recalled'); + expect((await timeline(String(first.id))).at(-1)![2]).toMatch(/ended failed at node 'boom', between two steps/); + }); + + it('a middle run another process is advancing: nothing is written, and the mark stays', async () => { + await start('root_of_middle', 'crm_invoice', 'i_mid_busy'); + const [first] = await requestsOn('i_mid_busy'); + const root: any = await automation.getRun(String(first.record_run_id)); + const middle = String(root.steps.find((s: any) => s.nodeId === 'mid').childRunIds[0]); + expect(middle).not.toBe(String(first.flow_run_id)); + const original = automation.getRun.bind(automation); + (automation as any).getRun = async (id: string) => { + const run: any = await original(id); + return id === middle ? { ...run, status: 'running' } : run; + }; + throwOn.add('boom'); + await settle(decide('i_mid_busy', 'approve', 'approver')); + expect(await field('crm_invoice', 'i_mid_busy')).toBe('pending'); + expect(await marks('i_mid_busy')).toEqual([true]); + expect(infos.some((m) => m.includes(`the run '${middle}' is running, so another process may be advancing it`))).toBe(true); + }); + + it('an abandoned auto-rejection sends the abandoned notice and no auto-rejected one', async () => { + await start('spent_then_boom', 'crm_invoice', 'i_spent'); + await decide('i_spent', 'approve', 'approver'); + throwOn.add('boom'); + const second = await pendingOn('i_spent'); + notices.length = 0; + const out: any = await svc.sendBack(String(second.id), { actorId: 'approver2' } as any, asPerson('approver2')); + expect(out.autoRejected).toBe(true); + expect(await field('crm_invoice', 'i_spent')).toBe('recalled'); + expect(notices.filter((n) => n.topic === 'approval.abandoned').map((n) => n.audience)).toEqual([['owner']]); + expect(notices.some((n) => n.topic === 'approval.returned'), 'no auto-rejected notice').toBe(false); + }); + }); + + describe('the reconciler', () => { + it('a parent run cancelled while its child\'s request is pending, which no door judged: abandoned', async () => { + await start('sub_then_second', 'crm_invoice', 'i_cancel'); + const [child] = await requestsOn('i_cancel'); + await automation.cancelRun(String(child.record_run_id)); + await withoutDoor(() => settle(decide('i_cancel', 'approve', 'approver'))); + expect(await field('crm_invoice', 'i_cancel'), 'held: no door judged').toBe('pending'); + expect(await marks('i_cancel')).toEqual([true]); + + const out = await svc.reconcileMarkedApprovals(); + expect(out.judged).toEqual({ abandoned: 1 }); + expect(await steps('i_cancel')).toEqual([['only', 'approved']]); + expect(await field('crm_invoice', 'i_cancel')).toBe('recalled'); + expect(await marks('i_cancel')).toEqual([false]); + expect((await svc.reconcileMarkedApprovals()).scanned, 'nothing left to judge').toBe(0); + }); + + it('a process that died between the last decision and the write of its outcome: written in the decider\'s name', async () => { + await start('two_step', 'crm_invoice', 'i_died'); + await decide('i_died', 'approve', 'approver'); + await withoutDoor(() => decide('i_died', 'approve', 'approver2')); + expect(await field('crm_invoice', 'i_died')).toBe('pending'); + expect(await marks('i_died')).toEqual([false, true]); + + const writes = recordWrites('crm_invoice'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(writes).toEqual([['approved', 'approver2']]); + expect(await field('crm_invoice', 'i_died')).toBe('approved'); + expect(await marks('i_died')).toEqual([false, false]); + }); + + it('a refused outcome is tried again while the mark stands, noted once and told under one key', async () => { + await start('two_step', 'crm_invoice', 'i_refuse'); + await decide('i_refuse', 'approve', 'approver'); + await withoutDoor(() => decide('i_refuse', 'approve', 'approver2')); + const original = ql.update.bind(ql); + let refuse = true; + (ql as any).update = async (o: string, data: any, options?: any) => { + if (refuse && o === 'crm_invoice' && data?.approval_status === 'approved') throw new Error('VALIDATION_FAILED: a rule of the app'); + return original(o, data, options); + }; + (svc as any).organizationAdministrators = async () => ({ ids: ['org_admin'] }); + const keys: unknown[] = []; + svc.attachMessaging({ emit: async (n: any) => { if (n.topic === 'approval.status_mirror_refused') keys.push([n.audience, n.dedupKey]); } } as any); + await svc.reconcileMarkedApprovals(); + await svc.reconcileMarkedApprovals(); + expect(await field('crm_invoice', 'i_refuse')).toBe('pending'); + expect(await marks('i_refuse')).toEqual([false, true]); + const [, last] = await requestsOn('i_refuse'); + // The notice is keyed per request and status, so the messaging service sends it once. + expect(keys).toEqual([[['org_admin'], `approval-mirror-refused-${last.id}-approved`], [['org_admin'], `approval-mirror-refused-${last.id}-approved`]]); + const lines = (await timeline(String(last.id))).filter(([, actor, text]) => actor === null && /could not|NOT|refused/i.test(String(text))); + expect(lines, 'the refusal is noted on the timeline once').toHaveLength(1); + + refuse = false; + await svc.reconcileMarkedApprovals(); + expect(await field('crm_invoice', 'i_refuse')).toBe('approved'); + expect(await marks('i_refuse')).toEqual([false, false]); + }); + + it('an approval whose field the object does not close on: the hold ends, the mark is cleared and nothing is written', async () => { + await start('two_step', 'crm_ticket', 't_died'); + await decide('t_died', 'approve', 'approver'); + await withoutDoor(() => decide('t_died', 'approve', 'approver2')); + expect(await field('crm_ticket', 't_died'), 'written at once, as on main').toBe('approved'); + expect(await marks('t_died')).toEqual([false, true]); + + const writes = recordWrites('crm_ticket'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ finished: 1 }); + expect(writes).toEqual([]); + expect(await marks('t_died')).toEqual([false, false]); + }); + + it('a record deleted in a passage: the marks are cleared once, with nothing written and no notice', async () => { + await start('two_step', 'crm_invoice', 'i_gone'); + await decide('i_gone', 'approve', 'approver'); + await withoutDoor(() => decide('i_gone', 'approve', 'approver2')); + await ql.delete('crm_invoice', { where: { id: 'i_gone' }, context: SYS } as any); + expect(await read('crm_invoice', 'i_gone')).toBeUndefined(); + notices.length = 0; + + const out = await svc.reconcileMarkedApprovals(); + expect(out.deletedRecords).toBe(1); + expect(out.judged).toEqual({}); + expect(await marks('i_gone')).toEqual([false, false]); + expect(notices).toEqual([]); + expect((await svc.reconcileMarkedApprovals()).scanned, 'cleared once: not scanned again').toBe(0); + }); + + it('past the age bound, a run that reports paused while its pause is gone stopped where it stood: abandoned', async () => { + await start('two_step', 'crm_invoice', 'i_lost'); + const [first] = await requestsOn('i_lost'); + // The shape a process that died after the decision's row landed and as + // its run's pause was consumed leaves: decided, marked, and a run that + // reports paused with no pause. + await ql.update('sys_approval_request', { id: first.id, status: 'approved', unjudged_since: new Date().toISOString() }, { context: SYS }); + const runId = String(first.flow_run_id); + const suspensionOf = (automation as any).suspensionOf.bind(automation); + (automation as any).suspensionOf = async (id: string) => (id === runId ? undefined : suspensionOf(id)); + expect((await automation.getRun(runId))?.status).toBe('paused'); + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound: cannot tell').toEqual({ undetermined: 1 }); + expect(await field('crm_invoice', 'i_lost')).toBe('pending'); + expect(await marks('i_lost')).toEqual([true]); + + await age('i_lost'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ abandoned: 1 }); + expect(await field('crm_invoice', 'i_lost')).toBe('recalled'); + expect((await timeline(String(first.id))).at(-1)![2]).toMatch(/reports paused at a pause that is gone, so it will not go on, between two steps\./); + expect(await marks('i_lost')).toEqual([false]); + }); + + it('past the age bound, a run parked at a subflow whose child has ended, which nothing will resume: abandoned', async () => { + await start('sub_then_second', 'crm_invoice', 'i_orphan'); + const [child] = await requestsOn('i_orphan'); + // The child's step was decided and its run ended, and the parent was never resumed. + await ql.update('sys_approval_request', { id: child.id, status: 'approved', unjudged_since: new Date().toISOString() }, { context: SYS }); + await automation.cancelRun(String(child.flow_run_id)); + expect((await automation.getRun(String(child.record_run_id)))?.status).toBe('paused'); + + expect((await svc.reconcileMarkedApprovals()).judged, 'within the bound: the parent is parked between two steps').toEqual({ in_progress: 1 }); + expect(await marks('i_orphan')).toEqual([true]); + + await age('i_orphan'); + expect((await svc.reconcileMarkedApprovals()).judged).toEqual({ abandoned: 1 }); + expect(await field('crm_invoice', 'i_orphan')).toBe('recalled'); + expect((await timeline(String(child.id))).at(-1)![2]).toMatch(/parked at 'sub' on a child run that has ended, so nothing will resume it, between two steps\./); + expect(await marks('i_orphan')).toEqual([false]); + }); + + it('scans the oldest mark first and at most its limit', 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).toBe(1); + expect(await field('crm_invoice', 'i_b'), 'the older mark').toBe('approved'); + expect(await field('crm_invoice', 'i_a')).toBe('pending'); + }); + + 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)); + }); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index b089f84ad54..ca4926ab6fc 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -370,13 +370,14 @@ 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`). + * a region names its container (`parentNodeId`). A delegating step names + * the child runs it started (`childRunIds`), which the door reads in turn. */ getRun?(runId: string): Promise<{ status?: string; flowName?: string; startedAt?: string; - steps?: ReadonlyArray<{ nodeId?: string; nodeType?: string; status?: string; parentNodeId?: string; startedAt?: string }>; + steps?: ReadonlyArray<{ nodeId?: string; nodeType?: string; status?: string; parentNodeId?: string; startedAt?: string; childRunIds?: readonly string[] }>; } | null>; /** * Whether a suspension still exists for `runId` — the pre-flight that keeps @@ -1886,9 +1887,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 +1900,56 @@ function stopOf(log: ReadonlyArray<{ nodeId?: unknown; parentNodeId?: unknown }> return last && typeof last.nodeId === 'string' ? last.nodeId : undefined; } +/** [ADR-0162 Execution item 8] One step of a run's log, as the door reads it. */ +type RunStepRead = { + nodeId?: unknown; nodeType?: unknown; status?: unknown; parentNodeId?: unknown; startedAt?: unknown; childRunIds?: unknown; +}; + +/** + * [ADR-0162 Execution item 8] How many runs one judgement of an approval + * reads, at most. Past it the door answers that it cannot tell, and the + * approval keeps its mark. + */ +const MAX_RUNS_READ_PER_APPROVAL = 200; + +/** + * [ADR-0162 Execution item 8] How long an approval's mark stands before the + * reconciler reads a run that will not move again as stopped where it stood: + * a run that reports paused while its pause is gone, and a run parked at a + * `subflow` or a `map` whose child run has ended. One hour: far past any + * passage a live process completes (a passage is the work between a decision + * and the next step, run in the same call), and short enough that a record a + * dead process left held is released the same working session. + */ +export const RECONCILER_AGE_BOUND_MS = 60 * 60 * 1000; + +/** + * [ADR-0162 Execution item 8] The child runs a run's steps name + * (`childRunIds`), to read next: every child of a `subflow` step, and a `map` + * item run only where it is the run of one of the approval's own requests + * (`ownRuns`): an item that is a record carries an approval of its own. + */ +function childRunsOf(steps: readonly RunStepRead[], ownRuns: ReadonlySet): string[] { + const out: string[] = []; + for (const s of steps) { + if (!Array.isArray(s?.childRunIds)) continue; + for (const id of s.childRunIds) { + if (typeof id !== 'string' || !id) continue; + if (s.nodeType === 'map' && !ownRuns.has(id)) continue; + out.push(id); + } + } + 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] What the door answered for an approval after it * resumed or cancelled one of its runs (`ApprovalService.judgeApprovalAfterDoor`). @@ -5316,6 +5370,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega request: { id?: unknown } | null | undefined, door: string, decided?: { requestId: string; actorId: string | null }, + opts?: { ageBoundMs?: number }, ): Promise { const requestId = request?.id != null ? String(request.id) : ''; if (!requestId) return 'unstamped'; @@ -5346,7 +5401,14 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega return 'judged'; } - const reading = await this.readCarryingRun(latest, stamp, approval); + // The reconciler's age bound: every mark of the approval has stood past + // it, so a run that has not moved since will not move again. + const now = this.clock.now().getTime(); + const aged = opts?.ageBoundMs != null && marked.every((r) => { + const at = new Date(r.unjudged_since).getTime(); + return Number.isFinite(at) && now - at >= opts.ageBoundMs!; + }); + const reading = await this.readCarryingRun(latest, stamp, approval, aged); 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} ` @@ -5393,124 +5455,182 @@ 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`. + * [ADR-0162 D5, Execution item 8] Read every run of the approval, once no + * request of it is pending or returned on its record, and place where each + * stopped against `stamp`. The walk starts at the run that carries the + * record and follows the child runs each delegating step records + * (`childRunIds` on the step log): every `subflow` child, and a `map` item + * run where it is the run of one of the approval's own requests (an item + * that is a record carries an approval of its own). The latest request's + * own run is read as well, for a run whose steps predate the link. One run + * of the tree decides for the whole approval: * - * - 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. + * - one that cannot be read, or that another process is advancing, or that + * reports paused with no pause to be found: `undetermined`; + * - one parked at a node of the set: `in_progress`; + * - otherwise, one that ended between two steps: `abandoned`; with none of + * those, the approval is `finished`. * - * Over, it ended between two steps where a later step of the approval was + * A run 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 + * 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 ({@link stopOf}). + * 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: the approval's mark has stood past + * {@link RECONCILER_AGE_BOUND_MS}, so a run that will never move again is + * read as stopped where it stood: one that reports paused while its pause is + * gone (a process died in a passage), and one parked at a `subflow` or a + * `map` whose child run has ended, which nothing will resume. */ 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 } > { - const runId = String(latest.record_run_id ?? latest.root_run_id ?? ''); + const rootId = String(latest.record_run_id ?? latest.root_run_id ?? ''); const automation = this.automation; - if (!runId) return { answer: 'undetermined', why: 'the request records no run that carries its record.' }; + if (!rootId) return { answer: 'undetermined', why: 'the request records no run that carries its record.' }; if (typeof automation?.getRun !== 'function') { - return { answer: 'undetermined', why: 'no automation engine that reports a run is attached.', runId }; + return { answer: 'undetermined', why: 'no automation engine that reports a run is attached.', runId: rootId }; + } + + const config = parseJson>(latest.node_config_json, {}); + const notOpened = config[LATER_STEP_NOT_OPENED_KEY] as { node?: unknown; reason?: unknown } | undefined; + const 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 ownRuns = new Set(approval.map((r) => (r?.flow_run_id != null ? String(r.flow_run_id) : '')).filter(Boolean)); + + const queue: string[] = [rootId]; + const ownRunId = latest.flow_run_id != null ? String(latest.flow_run_id) : ''; + if (ownRunId && ownRunId !== rootId) queue.push(ownRunId); + const seen = new Set(); + let endedWhy: string | undefined; + while (queue.length > 0) { + const runId = queue.shift()!; + if (seen.has(runId)) continue; + if (seen.size >= MAX_RUNS_READ_PER_APPROVAL) { + return { answer: 'undetermined', why: `its runs number more than ${MAX_RUNS_READ_PER_APPROVAL}, past what one judgement reads.`, runId }; + } + seen.add(runId); + const one = await this.readApprovalRun(runId, stamp, lastOpened, ownRuns, aged); + if (one.answer === 'undetermined') return { answer: 'undetermined', why: one.why, runId }; + if (one.answer === 'in_progress') return { answer: 'in_progress' }; + if (one.endedWhy && endedWhy === undefined) endedWhy = one.endedWhy; + queue.push(...one.children); } + if (notOpened && typeof notOpened === 'object') { + return { + answer: 'abandoned', + why: `its step '${String(notOpened.node ?? '')}' could not open (${String(notOpened.reason ?? 'no reason recorded')}).`, + }; + } + return endedWhy ? { answer: 'abandoned', why: endedWhy } : { answer: 'finished' }; + } + + /** + * [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, whether it ended between two steps, and the + * child runs to read next. + */ + private async readApprovalRun( + runId: string, + stamp: readonly StampedNode[], + lastOpened: number, + ownRuns: ReadonlySet, + aged: boolean, + ): Promise< + | { answer: 'undetermined'; why: string } + | { answer: 'in_progress' } + | { answer: 'read'; endedWhy?: string; children: string[] } + > { + const automation = this.automation!; let run: { status?: string; flowName?: string; steps?: unknown } | null; try { - run = await automation.getRun(runId); + run = await automation.getRun!(runId); } 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}).` }; } const status = typeof run?.status === 'string' ? run.status : ''; - if (!run || !status) return { answer: 'undetermined', why: `the run '${runId}' reports no status.`, runId }; + if (!run || !status) return { answer: 'undetermined', why: `the run '${runId}' reports no status.` }; if (ADVANCING_RUN_STATUSES.has(status)) { - return { answer: 'undetermined', why: `the run '${runId}' is ${status}, so another process may be advancing it.`, runId }; + return { answer: 'undetermined', why: `the run '${runId}' is ${status}, so another process may be advancing it.` }; } const flow = typeof run.flowName === 'string' ? run.flowName : undefined; - const steps = (Array.isArray(run.steps) ? run.steps : []) as Array<{ - nodeId?: unknown; nodeType?: unknown; status?: unknown; parentNodeId?: unknown; startedAt?: unknown; - }>; + const steps = (Array.isArray(run.steps) ? run.steps : []) as RunStepRead[]; + const children = childRunsOf(steps, ownRuns); + const instant = (v: unknown): number => (v == null || v === '' ? NaN : new Date(v as string).getTime()); - let stoppedAt: string | undefined; + let stop: string | undefined; + let stillWhere: 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) { + if (!aged) return { answer: 'undetermined', why: `the run '${runId}' reports paused, and no pause of it can be found.` }; + stop = stopOf(steps, 'failed'); + stillWhere = `its run '${runId}' reports paused at a pause that is gone, so it will not go on`; + } else if (standsBetweenSteps(stamp, parked.flowName ?? flow, parked.nodeId)) { + const child = typeof parked.correlation === 'string' ? childOfCorrelation(parked.correlation) : undefined; + if (!aged || !child || !(await this.childRunHasEnded(child))) return { answer: 'in_progress' }; + stop = parked.nodeId; + stillWhere = `its run '${runId}' is parked at '${parked.nodeId}' on a child run that has ended, so nothing will resume it`; + } else { + return { answer: 'read', children }; } - 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 }; + return { answer: 'undetermined', why: `the run '${runId}' reports the status '${status}', which the plugin does not place.` }; } else { - stoppedAt = stopOf(steps, status); + stop = stopOf(steps, status); } - const config = parseJson>(latest.node_config_json, {}); - const notOpened = config[LATER_STEP_NOT_OPENED_KEY] as { node?: unknown; reason?: unknown } | undefined; - if (notOpened && typeof notOpened === 'object') { - return { - answer: 'abandoned', - why: `its step '${String(notOpened.node ?? '')}' could not open (${String(notOpened.reason ?? 'no reason recorded')}).`, - }; + const routed = steps.find((s) => s?.status === 'failure' + && !s.parentNodeId + && typeof s.nodeId === 'string' + && s.nodeId !== stop + && standsBetweenSteps(stamp, flow, s.nodeId) + && !(instant(s.startedAt) < lastOpened)); + if (routed) { + return { answer: 'read', children, endedWhy: `its node '${String(routed.nodeId)}' failed between two steps, and the flow went on to its end without asking the next step.` }; } - // A failure the flow routed, at the top level of the run, on a node of the - // set, after which no request of the approval opened; or a stop on a node - // of the set. Read on the run that carries the record, and on the latest - // request's own run where that is another (a `subflow` body runs in a - // child run of its own, whose steps the carrying run does not log). - const instant = (v: unknown): number => (v == null || v === '' ? NaN : new Date(v as string).getTime()); - const lastOpened = approval.reduce((acc, r) => { - const at = instant(r?.created_at); - return Number.isFinite(at) && at > acc ? at : acc; - }, -Infinity); - const endedBetween = ( - log: ReadonlyArray<{ nodeId?: unknown; status?: unknown; parentNodeId?: unknown; startedAt?: unknown }>, - logFlow: string | undefined, - logStatus: string, - stop: string | undefined, - ): string | undefined => { - const routed = log.find((s) => s?.status === 'failure' - && !s.parentNodeId - && typeof s.nodeId === 'string' - && s.nodeId !== stop - && standsBetweenSteps(stamp, logFlow, s.nodeId) - && !(instant(s.startedAt) < lastOpened)); - if (routed) return `its node '${String(routed.nodeId)}' failed between two steps, and the flow went on to its end without asking the next step.`; - if (logStatus === 'paused' || REACHED_AN_END.has(logStatus)) return undefined; - if (!stop) return `its run ended ${logStatus}, at a node the plugin cannot place.`; - if (standsBetweenSteps(stamp, logFlow, stop)) return `its run ended ${logStatus} at node '${stop}', between two steps.`; - return undefined; - }; - const carried = endedBetween(steps, flow, status, stoppedAt); - if (carried) return { answer: 'abandoned', why: carried }; - const ownRunId = latest.flow_run_id != null ? String(latest.flow_run_id) : ''; - if (ownRunId && ownRunId !== runId) { - let own: { status?: string; flowName?: string; steps?: unknown } | null = null; - try { own = await automation.getRun(ownRunId); } catch { own = null; } - const ownStatus = typeof own?.status === 'string' ? own.status : ''; - if (own && TERMINAL_RUN_STATUSES.has(ownStatus)) { - const ownSteps = (Array.isArray(own.steps) ? own.steps : []) as typeof steps; - const ownStop = stopOf(ownSteps, ownStatus); - const inChild = endedBetween(ownSteps, typeof own.flowName === 'string' ? own.flowName : undefined, ownStatus, ownStop); - if (inChild) return { answer: 'abandoned', why: inChild }; - } + if (stillWhere !== undefined) { + return { answer: 'read', children, ...(stop && standsBetweenSteps(stamp, flow, stop) ? { endedWhy: `${stillWhere}, between two steps.` } : {}) }; + } + if (REACHED_AN_END.has(status)) return { answer: 'read', children }; + if (!stop) return { answer: 'read', children, endedWhy: `its run '${runId}' ended ${status}, at a node the plugin cannot place.` }; + if (standsBetweenSteps(stamp, flow, stop)) { + return { answer: 'read', children, endedWhy: `its run '${runId}' ended ${status} at node '${stop}', between two steps.` }; + } + return { answer: 'read', children }; + } + + /** [ADR-0162 Execution item 8] Whether `runId` has ended: read, and in a terminal status. */ + private async childRunHasEnded(runId: string): Promise { + if (typeof this.automation?.getRun !== 'function') return false; + try { + const run = await this.automation.getRun(runId); + return typeof run?.status === 'string' && TERMINAL_RUN_STATUSES.has(run.status); + } catch { + return false; } - return { answer: 'finished' }; } /** @@ -5603,13 +5723,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), @@ -5663,6 +5786,24 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega } } + /** + * [ADR-0162 Execution item 8] Whether `requestId`'s timeline already holds a + * line with no actor that reads `comment`: 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', 'actor_id'], limit: 5, context: SYSTEM_CTX, + }); + return (Array.isArray(rows) ? rows : []).some((r: any) => r?.actor_id == null || r.actor_id === ''); + } 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 +6173,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), @@ -10382,6 +10527,10 @@ 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 request of an approval the check stamped + // is the reconciler's ({@link reconcileMarkedApprovals}), which judges + // it and ends its hold: this report does not name it as well. + if (stampOf(raw) !== undefined) continue; let suspended: boolean; try { @@ -11080,6 +11229,119 @@ 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 requests the check stamped. It rides the sweep clock. + * + * It scans the marked requests oldest first, at most `limit` (default 200) + * of them, so that one pass is bounded and the oldest is never starved, and + * 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, a + * process that died after a decision. Once every mark of an approval has + * stood past {@link RECONCILER_AGE_BOUND_MS}, 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. + * + * A refused outcome or put-back leaves the marks, so the next pass tries it + * again; the mirror's notice to the administrators is keyed per request and + * status, so it is sent once. For a record that was deleted, the marks of + * its approval are cleared and nothing is written: no retry and no notice. + * An approval it cannot tell about keeps its marks for the next pass. + * + * Best-effort: one approval's failure costs only that approval. + */ + async reconcileMarkedApprovals(options?: { limit?: number }): Promise<{ + scanned: number; + judged: Partial>; + deletedRecords: number; + }> { + const judged: Partial> = {}; + let deletedRecords = 0; + let rows: any[]; + try { + rows = (await this.engine.find('sys_approval_request', { + where: { unjudged_since: { $null: false } }, + orderBy: [{ field: 'unjudged_since', order: 'asc' }, { field: 'id', order: 'asc' }], + limit: options?.limit ?? 200, context: SYSTEM_CTX, + })) ?? []; + } 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') { From 60c83d6c6ba16f7fba1861167752d46e943eab60 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 10:48:21 +0000 Subject: [PATCH 3/5] docs(approvals): the outcome's section follows what an abandoned approval leaves Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5pigknx7rC8rXnA3my --- content/docs/automation/approvals.mdx | 86 +++++++++++++-------------- 1 file changed, 43 insertions(+), 43 deletions(-) diff --git a/content/docs/automation/approvals.mdx b/content/docs/automation/approvals.mdx index 4aed1d60192..30a431aae2d 100644 --- a/content/docs/automation/approvals.mdx +++ b/content/docs/automation/approvals.mdx @@ -1560,55 +1560,13 @@ Nothing in the message is the submitter's to fix: every gap is the app's configuration or the host's. Whoever maintains the app fixes the field, the flow or the host, and the submitter then submits again. -### 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 holds a request of the approval. It answers one of: - -- **In progress.** A request is pending or returned on the record, or a run is - parked at a node between two steps. Nothing is written. -- **Ended between two steps.** A run stopped on a node a step could still follow - (it failed or was cancelled there), a failure the flow routed at the top level - of a run ended it, or a later step could not open. The approval is abandoned, - below. -- **Cannot tell.** A run is being advanced by another process, or 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. - -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, oldest first, as the action would have: -after a process that died, a run that was cancelled, or a parent run cancelled -while its child's request was pending. 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. -Where nothing was held back it clears the mark and writes nothing. A write that -a rule or a hook refuses is reported as above, once, and tried again on each -sweep while the mark stands. Where the record was deleted, the reconciler clears -the mark and writes nothing. - ### What an abandoned approval leaves 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. The platform -also abandons an approval whose run ended between two steps, above, at the +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 @@ -1646,6 +1604,48 @@ 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 holds a request of the approval. It answers one of: + +- **In progress.** A request is pending or returned on the record, or a run is + parked at a node between two steps. Nothing is written. +- **Ended between two steps.** A run stopped on a node a step could still follow + (it failed or was cancelled there), a failure the flow routed at the top level + of a run ended it, or a later step could not open. The approval is abandoned, + above. +- **Cannot tell.** A run is being advanced by another process, or 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. + +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, oldest first, as the action would have: +after a process that died, a run that was cancelled, or a parent run cancelled +while its child's request was pending. 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. +Where nothing was held back it clears the mark and writes nothing. A write that +a rule or a hook refuses is reported as above, once, and tried again on each +sweep while the mark stands. Where the record was deleted, the reconciler clears +the mark and writes nothing. + ## Why Separating *who configures* from *who approves* from *as whom it runs* is the same capability/assignment/requirement decoupling as the rest of authorization (ADR-0066). The `runAs` default of `user` means an approval flow can't silently grant the submitter cross-tenant or cross-owner reach — elevation is opt-in and auditable. That is the safe-by-default posture: the common case respects RLS; the elevated case is explicit. From 28dba1b11bf2836a412519c504fb355800d7c22a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 10:53:52 +0000 Subject: [PATCH 4/5] chore(changeset): the step log's field is a spec minor, and the slice 3 note stays as it is Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5pigknx7rC8rXnA3my --- .changeset/37767-outcome-when-approval-over.md | 2 +- .changeset/37767-reconciler.md | 2 ++ .changeset/37767-step-child-runs.md | 3 +-- .changeset/37767-step-log-child-runs-spec.md | 10 ++++++++++ 4 files changed, 14 insertions(+), 3 deletions(-) create mode 100644 .changeset/37767-step-log-child-runs-spec.md diff --git a/.changeset/37767-outcome-when-approval-over.md b/.changeset/37767-outcome-when-approval-over.md index dab0dc083cf..131a7031538 100644 --- a/.changeset/37767-outcome-when-approval-over.md +++ b/.changeset/37767-outcome-when-approval-over.md @@ -13,7 +13,7 @@ What changes, only for an approval the check stamped when it opened (one with a - **The decision is held back.** Where the object closes on the step's mirror field at `approved` or `rejected`, neither decision is written onto the record when it is made. The request records it as before, and the field keeps `pending`. Every other status (`pending` as a request opens, `returned` at a send-back, what a recall leaves) is written as before. - **The mark.** Every decision on a request of such an approval sets `unjudged_since` in the update that records it, also where nothing is held back. It is cleared when the approval is judged, and when the approval's next request opens on the record. A recall, an administrator's override and the dead-run sweep clear it on the approval's earlier requests. -- **The door judges the approval.** After a decision (by a person or the SLA clock), a send-back (and its auto-rejection), a resubmission, a recall and the continuation of a restored run, the plugin reads the run that carries the record and the approval's requests on it. Finished (the 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): it writes the latest request's decision, as the person who decided it. In progress (a request is open, or the run is parked at a pause a step can follow): nothing. Ended between two steps (the run stopped on a node a step could still follow, a failure the flow routed at the top level ended it, or a later step could not open, whatever the flow did with that): the approval is abandoned. Cannot tell (the run is being advanced or cannot be read): nothing, and the mark stays. +- **The door judges the approval.** After a decision (by a person or the SLA clock), a send-back (and its auto-rejection), a resubmission, a recall and the continuation of a restored run, the plugin reads the run that carries the record and the approval's requests on it. Finished (the run completed, stopped after the last step, or is parked at a pause no step can follow): it writes the latest request's decision, as the person who decided it. In progress (a request is open, or the run is parked at a pause a step can follow): nothing. Ended between two steps (the run stopped on a node a step could still follow, a failure the flow routed at the top level ended it, or a later step could not open, whatever the flow did with that): the approval is abandoned. Cannot tell (the run is being advanced or cannot be read): nothing, and the mark stays. - **An abandoned approval.** The latest request is marked abandoned, the field is put back by item 7's order (never a closed value, and nothing where another approval's request is open on the record on the same field), a timeline line with no actor says why and what the record was put back to, and the submitter is told on `approval.abandoned` instead of `approval.approved` or `approval.rejected`. The decisions already made stay on their requests. - **A restored run is refused.** `continueRestoredRun` refuses a request of an abandoned approval with `INVALID_STATE` and tells the operator to cancel the restored run. diff --git a/.changeset/37767-reconciler.md b/.changeset/37767-reconciler.md index a150a4e7852..17fb2c7b0ec 100644 --- a/.changeset/37767-reconciler.md +++ b/.changeset/37767-reconciler.md @@ -17,4 +17,6 @@ Only for an approval the check stamped when it opened (one with a step that can - **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 request the check stamped to the reconciler. +- **A refusing end is an end.** The door reads a run that reached an end of the flow as having ended there, a refusing end (`outcome: 'refused'`) included, as it already did for a completed run. + Unchanged: an object that declares no `closedStates`; an approval that opened before its object declared the key. diff --git a/.changeset/37767-step-child-runs.md b/.changeset/37767-step-child-runs.md index e6dc9285f46..59afc243861 100644 --- a/.changeset/37767-step-child-runs.md +++ b/.changeset/37767-step-child-runs.md @@ -1,5 +1,4 @@ --- -'@objectstack/spec': patch '@objectstack/service-automation': patch --- @@ -8,7 +7,7 @@ feat(automation): a delegating step records the child runs it started (ADR-0162 Clause-②: yes (widening) Metadata-protocol: none -Widened: the run log's step entry (`ExecutionStepLogSchema`) gains the optional, engine-written `childRunIds: string[]`; `AutomationEngine` gains the public read `runStartedFor(context)`, and a node executor's result (`NodeExecutionResult`) the optional `childRunIds`. +Widened: `AutomationEngine` gains the public read `runStartedFor(context)`, and a node executor's result (`NodeExecutionResult`) 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. `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; `undefined` where no run started. Under `errorHandling.strategy: 'retry'` it is the last attempt's run. The `subflow` and `map` nodes read it for a child that ended inside the call. 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..a861d5cb866 --- /dev/null +++ b/.changeset/37767-step-log-child-runs-spec.md @@ -0,0 +1,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) + +Clause-②: yes (widening) +Metadata-protocol: added + +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. From 5a93cb0a76165126fdfdd6c82560ebb475a0a7a4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 11:09:46 +0000 Subject: [PATCH 5/5] fix(approvals): the timeline-line probe reads no actor column Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5pigknx7rC8rXnA3my --- .../plugins/plugin-approvals/src/approval-service.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index ca4926ab6fc..0c1dcda7ef9 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -5788,17 +5788,17 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega /** * [ADR-0162 Execution item 8] Whether `requestId`'s timeline already holds a - * line with no actor that reads `comment`: 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. + * 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', 'actor_id'], limit: 5, context: SYSTEM_CTX, + fields: ['id'], limit: 1, context: SYSTEM_CTX, }); - return (Array.isArray(rows) ? rows : []).some((r: any) => r?.actor_id == null || r.actor_id === ''); + return Array.isArray(rows) && rows.length > 0; } catch { return false; }