Skip to content

Commit 828b6ec

Browse files
fix(automation): reading one run answers its terminal store row over this process's stale paused entry (#38969)
Fixes #38674 Clause-②: no Metadata-protocol: none ## 维护者速读 - 多进程部署下的审批使用者:一台进程已办完的审批,另一台进程读取这次流程运行时,以前可能显示为“暂停中”,现在正确显示为“已完成”。 - 属于审批流程的数据可靠性工作:防止审批插件把其实已经完成的审批误判为放弃。 - 出错的话,某次运行的状态会读错(误判已结束或仍暂停);改动只在读取顺序上,可直接撤回本 PR 恢复原行为。 - 无。 ## What changes `getRun` (`packages/services/service-automation/src/run-history.ts`) answered from this process's in-memory ring first and returned the ring entry before it asked the store. A run that paused here and was resumed and finished by another process kept reading `paused` here although the store held its terminal row. Now: - **Terminal ring entry**: answers alone, with no store read (unchanged). - **Non-terminal ring entry** (`paused`): `loadTerminal` is asked. A terminal row answers, **unless** the store also holds a live pause for the run (`store.load`), in which case the ring entry answers. - **No terminal row**: the ring entry answers, and the suspension row is not read for it (unchanged). - **No ring entry**: unchanged (terminal row, then paused row). **Default read and strict read change together.** Which source answers is not what `strict` decides. Strict (ADR-0162 Execution item 8) decides only what a store failure becomes. The default readers act on the same stale `paused` answer: the run-detail route shows a finished run as paused, and the approvals dead-run sweep skips a run that ended. One precedence keeps the two reads telling one story. On either new read failing, the default read answers the ring entry and logs a `warn` naming that degradation. The strict read throws the store failure, as it already does for its other two reads. **Why the live-pause exception (a measured deviation from the card's literal Ask 1).** The literal rule ("a terminal row wins over a non-terminal ring entry") turned `consumed-suspension-restore.test.ts` > "records the run as paused again, so the repair is not invisible" red (`expected 'failed' to be 'paused'`). `restoreConsumedSuspension` re-parks a run that failed mid-resume. It re-persists its pause and logs a NEW `paused` ring entry, and it leaves the run's `failed` row in place. Its own comment says that `getRun`'s ring-first order is what makes the restored `paused` the answer. There the ring entry is the later word, not the stale one. Under the literal rule the approvals plugin's strict read would read a restored approval run as `failed`, the same wrong-ending harm the card exists to stop. The discriminator: a run another process finished has no live pause left (a resume claims the pause before it continues). A restored run has one again. Every case the card describes (a second engine finished the run, or a terminal row written with no live pause) answers the terminal row. **Cost.** One `loadTerminal` (a single-row read by id) only for a run whose ring entry is non-terminal, plus one `store.load` only when a terminal row is found. A process with no ring entry for the run already pays `loadTerminal` and `load`. Hot paths that call `getRun` per row: the approvals dead-run sweep and the stranded-request scan (one call per pending request) now pay one indexed read for each request whose run is paused in this ring. The Runs list does not call `getRun` (`listRunsPage`), so it pays nothing. ### Consumers that act on a non-terminal answer (Ask 3) None reads the ring directly: `git grep -n executionLogs` outside `packages/services/service-automation` has 0 hits at `645e6b15`. Every consumer goes through `getRun`: - `plugin-approvals` `placeApprovalRun` (via `readApprovalRun`, **strict**): this is the abandonment path. A `paused` answer with no pause found (`suspensionOf`) reads `pause_gone`, and once a later judgement reads the same, the run is read as stopped and the approval as ended. - `plugin-approvals` `runsReadAtOpening` (**strict**): child runs read `paused` are not kept as ended. - `plugin-approvals` dead-run sweep (default): releases a pending request only on a terminal answer, so a stale `paused` delayed the release. - `plugin-approvals` `inspectStrandedRequests` (default, report only), `runHasEnded` (display only), the flow-name lookup at the decision door. - `runtime` run-detail routes (`domains/automation.ts`), the MCP run read (`domains/mcp.ts`), `flow-slot-view.ts`. - Engine-internal: `restoreConsumedSuspension`'s refusal reasons and `continuePastCancelledMapItem` (`run-resume.ts`). **Docblock.** The published `AutomationEngine.getRun` docblock in `engine.ts` now states the new order: a terminal in-memory entry, else the terminal history row unless the store holds a live pause, else a non-terminal in-memory entry, else the suspension row. Claim amendment 1 added this one docblock to the file surface; nothing else in `engine.ts` changes. **Read first** (by risk): 1. `run-history.ts` `terminalRowUnlessParked`: the live-pause exception and its failure arms. 2. `run-history.ts` `getRun`: the `terminal` handoff out of the `loadTerminal` try, and the `inMem` return placed before the paused-row probe. 3. `run-history-terminal-row-wins.test.ts`: the two-engine pin. **Two-minute check:** `pnpm --filter @objectstack/service-automation exec vitest run --maxWorkers=2 src/run-history-terminal-row-wins.test.ts src/consumed-suspension-restore.test.ts`. Expect 38 passed. ## Tests New `packages/services/service-automation/src/run-history-terminal-row-wins.test.ts` (14 tests). Each of the first 5 runs on both the default and the strict read: - engine B resumes and completes a run engine A parked: A answers `completed` (the card's "second engine" pin); - a terminal row written straight to the store, with no live pause left: answers `cancelled`; - a terminal row beside a live pause: the ring's `paused` answers (1 `loadTerminal`, 1 `load`); - no terminal row: ring `paused`, 1 `loadTerminal`, 0 `load`; - terminal ring entry: 0 store reads; - `loadTerminal` or `load` throws: the default read answers `paused` and logs one `warn`; the strict read rejects with the store's error. <details><summary>Red first, and the ablation of the fix (HEAD 7ae8901, by scripts/ablation-replace.mjs, restore verified blob == HEAD)</summary> Ablation 1 put back origin/main's `if (inMem) return inMem;`. Result: **12 failed / 26 passed** over the new file plus `consumed-suspension-restore.test.ts`. All 12 new-file tests outside the "terminal ring entry: 0 store reads" pair went red, for example `expected 'paused' to be 'completed'` and `expected 'paused' to be 'cancelled'`. The two "0 store reads" tests stay green by design: that behaviour is unchanged. Ablation 2 replaced `return parked ? inMem : this.runRecordToLogEntry(terminal);` with the literal rule. Result: **3 failed / 35 passed**: both "beside a live pause" tests, and `consumed-suspension-restore.test.ts` > "records the run as paused again, so the repair is not invisible". </details> <details><summary>Package suite and typecheck</summary> - `pnpm --filter @objectstack/service-automation exec vitest run --maxWorkers=2` at 6cddeb3 (literal rule): 1 failed / 4477 passed. The failure was the restore test above, which led to the live-pause exception. After 9300337, the new file plus `consumed-suspension-restore`, `run-history`, `engine-residual-log-cause` and `multi-replica-resume-staleness`: 5 files, 97 passed. - `pnpm --filter @objectstack/service-automation build && … typecheck`: exit 0. `check:test-typecheck: OK — 0 file(s) / 0 error(s)`. - At head 730465d (the docblock commit): build and typecheck exit 0, and the built `dist/index.d.ts` carries the new sentence (1 hit). `run-history-terminal-row-wins.test.ts` + `run-history.test.ts`: 2 files, 36 passed. </details> ## Acceptance notes - Not changed, noted: a run parked here, resumed by another process and parked again at a later node, still answers this ring's older `paused` entry, whose steps stop at the earlier node. The status is right but the step log is stale. The store's newer suspension row is not read when no terminal row exists. Read from the code; not reproduced. - Not changed, noted: a terminal row beside a suspension row whose delete was lost answers the ring's `paused`. That is today's answer, so nothing regresses. - `test:repo` was not run locally (CI `Test Core`). Approvals plugin tests were not run locally: the public types are byte-unchanged, and CI runs them. ## Verification Local gate subset: `node scripts/pm/dispatch-gates.mjs --commands` derived 70 commands at 7ae8901, reconciled with `--ran`. See the report comment on the card for each exit code. Two came back NOT MEASURED (prerequisite not met, not a pass): `check-plugin-teardown-shape --self-test` (a shallow clone cannot reach its pinned fixture commit) and `check:dual-build-cjs-loads` (needs a full `pnpm build`). Both go to CI. At head 730465d: the derivation grew to 72 commands (`check:facade-delegation-only` and `check:startup-registry-verdict` joined for `engine.ts`). Both exit 0. `check:doc-authoring`, `check:issue-citations`, `check:nul-bytes`, `check:adr-anchors`, `check:adr-symbol-anchors`, `check:durability-log-level`, `check:type-check-debt` and `check:type-check-coverage` were re-run: all exit 0. `overlap-check`: `VERDICT clean exit 0`. --- _Generated by [Claude Code](https://claude.ai/code/session_01WGufzhKEbEnW8pwZRgK2gJ)_ <!-- signed: repo:objectstack@os-support-ai · os-support-ai · session_01WGufzhKEbEnW8pwZRgK2gJ --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 5704d13 commit 828b6ec

4 files changed

Lines changed: 357 additions & 9 deletions

File tree

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
---
2+
'@objectstack/service-automation': patch
3+
---
4+
5+
fix(automation): reading one run answers the run's final row over this process's stale "paused" entry
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
Reading one automation run (`getRun`, which backs the run-detail route and the approvals plugin's judgement of a run) answered from this process's in-memory run log first, and only looked at the run history store when that log had nothing. On a deployment with more than one process, a run that paused in this process and was then resumed and finished by another process kept reading `paused` here, although the store held its `completed` (or `failed`, `cancelled`) row. The approvals plugin reads a run that is `paused` with no pause left as stopped, so it could abandon an approval whose run had in fact finished.
11+
12+
Now, when this process's entry for the run is not terminal, the read asks the store for the run's terminal row, and that row answers, on the default read and on the strict read (`getRun(runId, { strict: true })`) alike. Two cases keep this process's entry as the answer:
13+
14+
- **The store holds no terminal row for the run.** The `paused` entry answers as before; the run's suspension row is not read for it.
15+
- **The store also holds a live pause for the run.** That is a run put back after it ended: an operator's `restoreConsumedSuspension` re-parks a failed run and records it `paused`, leaving its `failed` row in place. The `paused` entry is the later word then, and the run still reads `paused`, as it did before this change.
16+
17+
A run whose entry in this process is already terminal is answered with no store read. The added cost is one read of the run's terminal row for a run whose entry here is `paused`, plus one read of its live pause only when a terminal row is found; a run with no entry in this process already paid the first read.
18+
19+
Where one of these added reads fails, the default read answers this process's entry and logs, at `warn`, that it did; the strict read throws the store's failure to its caller, as it already does for the store reads it made before. The strict read's contract (a store failure is the caller's answer, never "no such run") is otherwise unchanged.
20+
21+
No action is needed.

‎packages/services/service-automation/src/engine.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4310,8 +4310,9 @@ export class AutomationEngine implements IAutomationService {
43104310
}
43114311

43124312
/**
4313-
* One run's log entry: the in-memory entry, else its terminal history row,
4314-
* else its suspension row; `null` where none answers. A store that fails
4313+
* One run's log entry: a terminal in-memory entry, else its terminal
4314+
* history row unless the store holds a live pause, else a non-terminal
4315+
* in-memory entry, else its suspension row; `null` where none answers. A store that fails
43154316
* is logged and read as `null` too, unless `options.strict` is set
43164317
* ([ADR-0162 Execution item 8]): then the store's failure is thrown, so a
43174318
* caller that decides on a missing run can tell a run with no row from a
Lines changed: 241 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,241 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* `getRun` answers a run's TERMINAL store row over a non-terminal entry in this
5+
* process's own ring.
6+
*
7+
* The ring (`executionLogs`) holds what THIS process saw of a run. A run that
8+
* paused here and was then resumed and finished by another process (a second
9+
* replica over the same store) leaves the ring saying `paused` while the store
10+
* holds the run's terminal row. `getRun` used to answer the ring first, so it
11+
* reported `paused` for a run that had completed — and the approvals plugin,
12+
* which reads a run that is paused with no pause left as stopped, could abandon
13+
* an approval that had finished.
14+
*
15+
* Pinned here, on the default read and the strict read alike:
16+
* - a second engine finishes the run: the first engine's `getRun` answers the
17+
* terminal row;
18+
* - the terminal row is written straight to the store and no live pause is
19+
* left: the same;
20+
* - a terminal row AND a live pause (the shape an operator's restore of a
21+
* failed run leaves, `consumed-suspension-restore.test.ts` pins it through
22+
* the real door): the ring's `paused` entry answers;
23+
* - no terminal row: the ring's own `paused` entry still answers, and the
24+
* suspension row is not read for it;
25+
* - a terminal ring entry answers with no store read at all (the cost bound);
26+
* - either extra read fails: the default read answers the ring entry and
27+
* logs that it did, the strict read throws the store's failure.
28+
*/
29+
30+
import { describe, it, expect } from 'vitest';
31+
import { defineActionDescriptor } from '@objectstack/spec/automation';
32+
import type { AutomationContext } from '@objectstack/spec/contracts';
33+
import { AutomationEngine } from './engine.js';
34+
import type { RunRecord, SuspendedRun, SuspendedRunStore } from './engine.js';
35+
import { InMemorySuspendedRunStore } from './suspended-run-store.js';
36+
37+
const HOLD_DESCRIPTOR = defineActionDescriptor({
38+
type: 'hold', version: '1.0.0', name: 'Hold',
39+
supportsPause: true, resumeAuthority: 'any',
40+
});
41+
42+
function recordingLogger() {
43+
const warns: string[] = [];
44+
const logger = {
45+
info() {}, error() {}, debug() {},
46+
warn(msg: string) { warns.push(msg); },
47+
child() { return logger; },
48+
};
49+
return { logger: logger as never, warns };
50+
}
51+
52+
const HELD_FLOW = {
53+
name: 'held_flow', label: 'held_flow', type: 'autolaunched',
54+
nodes: [
55+
{ id: 'start', type: 'start', label: 's' },
56+
{ id: 'hold', type: 'hold', label: 'h' },
57+
{ id: 'end', type: 'end', label: 'e' },
58+
],
59+
edges: [
60+
{ id: 'e1', source: 'start', target: 'hold' },
61+
{ id: 'e2', source: 'hold', target: 'end' },
62+
],
63+
};
64+
65+
/** One process: an engine over `store` that parks on `hold` until resumed. */
66+
function replica(store: SuspendedRunStore, logger: never = recordingLogger().logger): AutomationEngine {
67+
const engine = new AutomationEngine(logger, store);
68+
engine.registerNodeExecutor({
69+
type: 'hold',
70+
descriptor: HOLD_DESCRIPTOR,
71+
async execute() { return { success: true, suspend: true, correlation: 'held' }; },
72+
} as never);
73+
engine.registerFlow('held_flow', HELD_FLOW as never);
74+
return engine;
75+
}
76+
77+
const flush = () => new Promise<void>((r) => setTimeout(r, 0));
78+
79+
function terminalRow(runId: string, status: RunRecord['status']): RunRecord {
80+
const now = new Date().toISOString();
81+
return { runId, flowName: 'held_flow', status, startedAt: now, finishedAt: now, durationMs: 1, steps: [] };
82+
}
83+
84+
/** Parks one run on `engine`; its ring now holds the run's `paused` entry. */
85+
async function parkOne(engine: AutomationEngine): Promise<string> {
86+
const paused = await engine.execute('held_flow', { event: 'test' } as AutomationContext);
87+
expect(paused.status).toBe('paused');
88+
return paused.runId!;
89+
}
90+
91+
/** A store whose reads are counted, and whose `loadTerminal` or `load` can be made to throw. */
92+
function countingStore(inner: InMemorySuspendedRunStore, opts: { failLoadTerminal?: Error; failLoad?: Error } = {}) {
93+
const calls = { loadTerminal: 0, load: 0 };
94+
const store: SuspendedRunStore = {
95+
save: (run: SuspendedRun) => inner.save(run),
96+
load: async (runId: string) => {
97+
calls.load++;
98+
if (opts.failLoad) throw opts.failLoad;
99+
return inner.load(runId);
100+
},
101+
delete: (runId: string) => inner.delete(runId),
102+
claimSuspension: (runId, parkedAt) => inner.claimSuspension(runId, parkedAt),
103+
list: () => inner.list(),
104+
recordTerminal: (record: RunRecord) => inner.recordTerminal(record),
105+
listHistory: (flowName: string, limit: number) => inner.listHistory(flowName, limit),
106+
loadTerminal: async (runId: string) => {
107+
calls.loadTerminal++;
108+
if (opts.failLoadTerminal) throw opts.failLoadTerminal;
109+
return inner.loadTerminal(runId);
110+
},
111+
};
112+
return { store, calls };
113+
}
114+
115+
describe('getRun: a terminal store row wins over a non-terminal ring entry', () => {
116+
for (const strict of [false, true]) {
117+
const read = strict ? 'strict read' : 'default read';
118+
119+
it(`${read}: a run another engine finished answers its terminal row, not this ring's 'paused'`, async () => {
120+
const store = new InMemorySuspendedRunStore();
121+
const engineA = replica(store);
122+
const engineB = replica(store);
123+
124+
const runId = await parkOne(engineA);
125+
expect((await engineA.getRun(runId, { strict }))!.status).toBe('paused');
126+
127+
// The other process resumes and finishes the run.
128+
expect((await engineB.resume(runId)).success).toBe(true);
129+
await flush(); // recordTerminal is fire-and-forget
130+
expect((await store.loadTerminal(runId))?.status).toBe('completed');
131+
expect(await store.load(runId)).toBeNull();
132+
133+
const run = await engineA.getRun(runId, { strict });
134+
expect(run!.status).toBe('completed');
135+
expect(run!.id).toBe(runId);
136+
});
137+
138+
it(`${read}: a terminal row written straight to the store, with no live pause left, answers over this ring's 'paused'`, async () => {
139+
const store = new InMemorySuspendedRunStore();
140+
const engine = replica(store);
141+
const runId = await parkOne(engine);
142+
143+
await store.recordTerminal(terminalRow(runId, 'cancelled'));
144+
await store.delete(runId);
145+
146+
expect((await engine.getRun(runId, { strict }))!.status).toBe('cancelled');
147+
});
148+
149+
it(`${read}: a terminal row beside a live pause leaves this ring's 'paused' entry the answer`, async () => {
150+
const inner = new InMemorySuspendedRunStore();
151+
const { store, calls } = countingStore(inner);
152+
const engine = replica(store);
153+
const runId = await parkOne(engine);
154+
155+
// The run ended, and was then put back: its pause is live again.
156+
await inner.recordTerminal(terminalRow(runId, 'failed'));
157+
expect(await inner.load(runId)).not.toBeNull();
158+
159+
expect((await engine.getRun(runId, { strict }))!.status).toBe('paused');
160+
expect(calls.loadTerminal).toBe(1);
161+
expect(calls.load).toBe(1);
162+
});
163+
164+
it(`${read}: with no terminal row the ring's 'paused' entry answers, and the suspension row is not read`, async () => {
165+
const { store, calls } = countingStore(new InMemorySuspendedRunStore());
166+
const engine = replica(store);
167+
const runId = await parkOne(engine);
168+
169+
const run = await engine.getRun(runId, { strict });
170+
expect(run!.status).toBe('paused');
171+
expect(calls.loadTerminal).toBe(1);
172+
expect(calls.load).toBe(0);
173+
});
174+
175+
it(`${read}: a terminal ring entry answers with no store read`, async () => {
176+
const { store, calls } = countingStore(new InMemorySuspendedRunStore());
177+
const engine = replica(store);
178+
const runId = await parkOne(engine);
179+
expect((await engine.resume(runId)).success).toBe(true);
180+
await flush();
181+
calls.loadTerminal = 0;
182+
calls.load = 0;
183+
184+
expect((await engine.getRun(runId, { strict }))!.status).toBe('completed');
185+
expect(calls.loadTerminal).toBe(0);
186+
expect(calls.load).toBe(0);
187+
});
188+
}
189+
190+
it("default read: a failing terminal read answers this ring's 'paused' entry and logs that it did", async () => {
191+
const failure = new Error('store unreachable');
192+
const inner = new InMemorySuspendedRunStore();
193+
const { logger, warns } = recordingLogger();
194+
const engine = replica(inner, logger);
195+
const runId = await parkOne(engine);
196+
// Same ring, now reading through a store whose terminal read fails.
197+
engine.setSuspendedRunStore(countingStore(inner, { failLoadTerminal: failure }).store);
198+
199+
const run = await engine.getRun(runId);
200+
expect(run!.status).toBe('paused');
201+
const record = warns.filter((w) => w.includes('durable run lookup failed'));
202+
expect(record).toHaveLength(1);
203+
expect(record[0]).toContain("DEGRADES to this process's own 'paused' entry");
204+
});
205+
206+
it('strict read: a failing terminal read throws the store failure, not the ring entry', async () => {
207+
const failure = new Error('store unreachable');
208+
const inner = new InMemorySuspendedRunStore();
209+
const engine = replica(inner);
210+
const runId = await parkOne(engine);
211+
engine.setSuspendedRunStore(countingStore(inner, { failLoadTerminal: failure }).store);
212+
213+
await expect(engine.getRun(runId, { strict: true })).rejects.toBe(failure);
214+
});
215+
216+
it("default read: a failing live-pause read beside a terminal row answers this ring's 'paused' entry and logs that it did", async () => {
217+
const failure = new Error('store unreachable');
218+
const inner = new InMemorySuspendedRunStore();
219+
const { logger, warns } = recordingLogger();
220+
const engine = replica(inner, logger);
221+
const runId = await parkOne(engine);
222+
await inner.recordTerminal(terminalRow(runId, 'completed'));
223+
engine.setSuspendedRunStore(countingStore(inner, { failLoad: failure }).store);
224+
225+
expect((await engine.getRun(runId))!.status).toBe('paused');
226+
const record = warns.filter((w) => w.includes('durable paused-run lookup failed'));
227+
expect(record).toHaveLength(1);
228+
expect(record[0]).toContain("DEGRADES to this process's own 'paused' entry");
229+
});
230+
231+
it('strict read: a failing live-pause read beside a terminal row throws the store failure', async () => {
232+
const failure = new Error('store unreachable');
233+
const inner = new InMemorySuspendedRunStore();
234+
const engine = replica(inner);
235+
const runId = await parkOne(engine);
236+
await inner.recordTerminal(terminalRow(runId, 'completed'));
237+
engine.setSuspendedRunStore(countingStore(inner, { failLoad: failure }).store);
238+
239+
await expect(engine.getRun(runId, { strict: true })).rejects.toBe(failure);
240+
});
241+
});

0 commit comments

Comments
 (0)