Skip to content

Commit 5704d13

Browse files
fix(plugin-approvals): a terminal run is read by the steps it logged by its end, not a fan-out branch's late steps (#38978)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwB12LHqjnJsWFhAJNYDzW4BQ)_ Fixes #38691 Clause-②: no Metadata-protocol: none ## 维护者速读 - 问题:流程在顶层同时分出两条分支时,一条分支失败后另一条还会继续跑,并在运行已经结束后往日志里追加步骤。审批插件把"日志最后一步"当成运行停下的位置,于是对账时把失败位置认错,还会把一个没有历史行的子运行当成"已通过"。 - 已复现(真实引擎):修复前新测试 2 个失败、2 个通过;修复后 4 个全部通过。 - 做法:审批插件只按运行 `completedAt` 之前完成的步骤来判断停在哪里、哪些步骤已过。没有 `completedAt` 的运行、同一毫秒完成的步骤,读法不变。 - 顺手修正:卡片第 2 到 5 项(一处注释、一次重复序列化、两个缺失的测试、spec 文件里一段注释,没有改 schema)。 - 另外发现一个越界问题(失败的运行上仍会打开新的审批请求),已立为 #38985,不在本 PR 里修。 - 审查指出的三种未覆盖情况(挂起状态只在内存里、被拒绝的运行、`routedFailure` 仍读晚到的步骤)已立为后续卡 #38988。 - 要你做什么:无。 ## What changes **Item 1 (N23 + `stopOf`), `@objectstack/plugin-approvals`, `approval-service.ts`.** - New helper `loggedAfterEnd(step, ended)`: a step whose `completedAt` is strictly later than the run's `completedAt`. - `stopOf(log, status, endedAt?)` skips those steps when it picks the last top-level step of a terminal run. - `childRunsOf(…, endedAt?)` computes the last in-run step without them, so `passed` (a step before the last one) no longer counts a step another branch completed after the run ended. - The three call sites pass `run.completedAt`; the run read type gains `completedAt?`. The docblocks now say log order is a convention, and why. - Unchanged: a run with no `completedAt`, a step completed in the same millisecond as the run, a paused run (the parked-visit guard still applies), and a run cancelled from its pause (pinned as a control). **Item 2 (N14), `@objectstack/service-automation`, `engine-run-log.ts`.** The `MAX_STEP_CHILD_RUN_IDS` docblock (the constant moved here from `engine.ts`) names `MAX_RUNS_READ_PER_APPROVAL` in `@objectstack/plugin-approvals`. Both are 200 on the base. The real-engine reconciler suite already ties them (`approval-reconciler-37767.integration.test.ts`, the case near line 1533), so no new tie is added. **Item 3 (N15), `suspended-run-store.ts`.** `serializeStepsBounded` stringifies the log once. Under the cap it returns that string; over it, it sheds and halves as before. An empty log still returns `null`. **Item 4 (N16), `step-child-runs.test.ts`.** Two cases: a log still over the cap after the shed is halved, with the newest steps kept and marked; and the 28-byte band, where a log that fits only without its marks is halved while the same log with no links is kept whole. **Item 5 (N17), `@objectstack/spec`, `execution.zod.ts`.** Comment only, over `childRunIds`: the list is bounded and can be shed (seat ruling 7258590209, ruling 7268216330), so a reader cannot count on reaching every run of its tree from the log alone. No schema byte and no `.describe()` text changes. ## Reproduction (item 1, real kernel) New test `packages/plugins/plugin-approvals/src/approval-fanout-stop-38691.test.ts`, on the real-kernel harness of `approval-reconciler-37767.integration.test.ts`. Flow `fork_fail`: an approval, then a top-level fork to a slow subflow branch (`mid`) and a branch (`note`) that fails first. - The stored log of the failed run reads `… note(failure), mid(success)`, and `mid.completedAt` is later than the run's `completedAt`. This is the card's premise, measured. - The reconciler and the decision door give the same sentence: "ended failed at node 'note', between two steps". - A child run with no history row under a step completed after the run's end is not taken as passed: the result is undetermined and the record stays pending. - Control: a parked run that is cancelled is still read as abandoned at `mid`. Red first on the base (origin/main `d38006b9`, test only): 2 failed, 2 passed. The two failures: the door said "its node 'note' failed between two steps, and the flow went on…", and the reconciler counted `finished: 1` for the child with no row. On this head: 4 of 4 pass. `step-child-runs.test.ts`: 12 of 12 pass. ## Out of scope, measured: #38985 After `note` fails, the other branch keeps running and can reach a later approval step. In a probe (`mid` → `second`, an approval), approving `first` answers `RESUME_FAILED`, the run is `failed`, `second` is opened and stays `pending` on the failed run, the record stays `pending`, and the record carries no reconciliation mark, so the reconciler never judges it. That is a different defect: which branch runs, not how the log is read. This PR does not change it. It is in the #38838 family and is filed as #38985. ## Acceptance notes - File surface is the claim's: `approval-service.ts` (`stopOf`, `childRunsOf`, the new helper, three call sites and their run type), `engine-run-log.ts` (docblock), `suspended-run-store.ts` (`serializeStepsBounded`), `step-child-runs.test.ts`, `execution.zod.ts` (comment), the new test, the changeset. `run-history.ts` (#38674, PR #38969) is not touched; #38969 carries the `engine.ts` `getRun` docblock line, as agreed with the seat. - Semver: `patch` on the three packages. `Clause-②: no`: no accept set, export or schema moves; one read (where a terminal fan-out run stopped, and whether a step passed) changes in the cell above. - L2 at the contract-review tier: PASS, comment 7318891630 (no must-fix, no should-fix). Its escalation (a suspension held in memory, a refused fan-out run, `routedFailure` reading late steps, with nits N2 to N5) is the follow-up #38988; this PR keeps `Fixes #38691` on the seat's ruling. L1 owed. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01WGufzhiGvpFMQX4XptMEtQ <!-- signed: repo:objectstack@os-support-ai · os-support-ai · session_01WGufzhiGvpFMQX4XptMEtQ --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent b53e70f commit 5704d13

7 files changed

Lines changed: 412 additions & 21 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/plugin-approvals': patch
3+
'@objectstack/service-automation': patch
4+
'@objectstack/spec': patch
5+
---
6+
7+
fix(plugin-approvals): an approval's run is read by the steps it logged by its end, not a fan-out branch that went on after it
8+
9+
Clause-②: no
10+
Metadata-protocol: none
11+
12+
When a flow's node fans out to branches that run together and one branch fails, the automation engine does not stop the others: they go on appending steps to the run's log after the run has ended. The approvals plugin read the last top-level step of a terminal run as where it stopped, and any later step as the run going on past a step, so a step another branch completed after the run's end moved both readings: the reconciler placed a failed run at the other branch's node (and told a failure the flow never routed as one it went on from), and took a child run with no history row as passed. Both readings now use only the steps the run completed by its `completedAt`; a run that names no `completedAt`, and a step completed in the same millisecond, read as before.
13+
14+
Also: the terminal history row serializes a log under its size cap once, not twice (`@objectstack/service-automation`); the source comment over the step log's `childRunIds` no longer says a reader reaches every run of its tree from the log alone, since the list is bounded and can be shed (`@objectstack/spec`, comment only, no schema change).

‎packages/plugins/plugin-approvals/src/approval-fanout-stop-38691.test.ts‎

Lines changed: 277 additions & 0 deletions
Large diffs are not rendered by default.

‎packages/plugins/plugin-approvals/src/approval-service.ts‎

Lines changed: 51 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1926,17 +1926,45 @@ const REACHED_AN_END: ReadonlySet<string> = new Set(['completed', 'refused']);
19261926
* suspension refused inside a region. There the last step logged is the node
19271927
* before it, and the run is placed by that node. `undefined` for a run that
19281928
* reached an `end` ({@link REACHED_AN_END}).
1929+
*
1930+
* [#38691] "The last step" is a convention of log order, and a top-level
1931+
* fan-out breaks it: the engine runs a node's unconditional out-edges
1932+
* together, and when one branch fails, the others are not stopped and go on
1933+
* appending their steps to the run's log after the run has ended. So the
1934+
* steps read here are those the run logged by its end, `endedAt` (its
1935+
* `completedAt`; {@link loggedAfterEnd}); a step completed after it is
1936+
* another branch's, and never where the run stood.
19291937
*/
1930-
function stopOf(log: ReadonlyArray<{ nodeId?: unknown; parentNodeId?: unknown }>, status: string): string | undefined {
1938+
function stopOf(
1939+
log: ReadonlyArray<{ nodeId?: unknown; parentNodeId?: unknown; completedAt?: unknown }>,
1940+
status: string,
1941+
endedAt?: unknown,
1942+
): string | undefined {
19311943
if (REACHED_AN_END.has(status)) return undefined;
1932-
const last = [...log].reverse().find((s) => !s?.parentNodeId) ?? log[log.length - 1];
1944+
const ended = instantOf(endedAt);
1945+
const inRun = log.filter((s) => !loggedAfterEnd(s, ended));
1946+
const read = inRun.length > 0 ? inRun : log;
1947+
const last = [...read].reverse().find((s) => !s?.parentNodeId) ?? read[read.length - 1];
19331948
return last && typeof last.nodeId === 'string' ? last.nodeId : undefined;
19341949
}
19351950

1951+
/**
1952+
* [#38691] Whether `step` of a terminal run was completed after the run had
1953+
* ended at `ended` (its `completedAt`, as an instant): a branch of a
1954+
* top-level fan-out that the engine did not stop when another branch failed
1955+
* (see {@link stopOf}). Strictly after: a step completed within the same
1956+
* millisecond as the run is read as the run's, as every step was before, and
1957+
* a run or step with no readable instant has nothing logged after its end.
1958+
*/
1959+
function loggedAfterEnd(step: { completedAt?: unknown } | null | undefined, ended: number): boolean {
1960+
const at = instantOf(step?.completedAt);
1961+
return Number.isFinite(ended) && Number.isFinite(at) && at > ended;
1962+
}
1963+
19361964
/** [ADR-0162 Execution item 8] One step of a run's log, as the door reads it. */
19371965
type RunStepRead = {
1938-
nodeId?: unknown; nodeType?: unknown; status?: unknown; parentNodeId?: unknown; startedAt?: unknown; childRunIds?: unknown;
1939-
childRunIdsTruncated?: unknown;
1966+
nodeId?: unknown; nodeType?: unknown; status?: unknown; parentNodeId?: unknown; startedAt?: unknown; completedAt?: unknown;
1967+
childRunIds?: unknown; childRunIdsTruncated?: unknown;
19401968
};
19411969

19421970
/**
@@ -2105,11 +2133,14 @@ interface ChildRunRef {
21052133
*
21062134
* `passed` (the seat's reading 7257555103 of ruling A3): the run went on
21072135
* past the step that names the child. The step succeeded, and the run
2108-
* reached an end of its flow (`reachedAnEnd`) or logged a later step. The
2109-
* engine logs one step for each visit of a node, a visit that paused and
2110-
* was resumed included, and a run stands at the last step it logged (as
2111-
* {@link stopOf} reads it), so a later step says the visit is over and
2112-
* every child of it has ended. Two things are never passed:
2136+
* reached an end of its flow (`reachedAnEnd`) or logged a later step by the
2137+
* time it ended. The engine logs one step for each visit of a node, a visit
2138+
* that paused and was resumed included, and by convention a run stands at
2139+
* the last step it logged (as {@link stopOf} reads it), so a later step says
2140+
* the visit is over and every child of it has ended. The convention is one of
2141+
* log order: in a top-level fan-out a later step can be another branch's, so
2142+
* a step a terminal run completed after its end, `endedAt`, is no later step
2143+
* ({@link loggedAfterEnd}, #38691). Two things are never passed:
21132144
*
21142145
* - the latest visit of the node a paused run is parked at (`parkedAt`),
21152146
* whatever was logged after it: a step on another branch of the flow can
@@ -2121,12 +2152,17 @@ interface ChildRunRef {
21212152
* And a log that is cut ({@link stepLogCut}, `speaks` false) passes none:
21222153
* it does not speak for the runs it names.
21232154
*/
2124-
function childRunsOf(steps: readonly RunStepRead[], reachedAnEnd: boolean, parkedAt?: string, speaks = true): ChildRunRef[] {
2155+
function childRunsOf(
2156+
steps: readonly RunStepRead[], reachedAnEnd: boolean, parkedAt?: string, speaks = true, endedAt?: unknown,
2157+
): ChildRunRef[] {
21252158
const out: ChildRunRef[] = [];
21262159
const parkedVisit = parkedAt === undefined ? -1 : steps.map((s) => s?.nodeId).lastIndexOf(parkedAt);
2160+
const ended = instantOf(endedAt);
2161+
let lastInRun = steps.length - 1;
2162+
while (lastInRun >= 0 && loggedAfterEnd(steps[lastInRun], ended)) lastInRun -= 1;
21272163
steps.forEach((s, i) => {
21282164
if (!Array.isArray(s?.childRunIds)) return;
2129-
const passed = speaks && s.status === 'success' && i !== parkedVisit && (reachedAnEnd || i < steps.length - 1);
2165+
const passed = speaks && s.status === 'success' && i !== parkedVisit && (reachedAnEnd || i < lastInRun);
21302166
for (const id of s.childRunIds) {
21312167
if (typeof id !== 'string' || !id) continue;
21322168
out.push({ id, item: s.nodeType === 'map', passed });
@@ -6402,7 +6438,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
64026438
const steps = (Array.isArray(run.steps) ? run.steps : []) as RunStepRead[];
64036439
log.cut = stepLogCut(run, steps, TERMINAL_RUN_STATUSES.has(status));
64046440
const speaks = log.cut === undefined;
6405-
let children = childRunsOf(steps, REACHED_AN_END.has(status), undefined, speaks);
6441+
let children = childRunsOf(steps, REACHED_AN_END.has(status), undefined, speaks, run.completedAt);
64066442

64076443
// A failure the flow routed, at the top level of the run, on a node of
64086444
// the set, after which no request of the approval opened. Read for a
@@ -6471,7 +6507,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
64716507
return { answer: 'undetermined', why: `the run '${runId}' reports the status '${status}', which the plugin does not place.` };
64726508
}
64736509

6474-
const stop = stopOf(steps, status);
6510+
const stop = stopOf(steps, status, run.completedAt);
64756511
const routed = routedFailure(stop);
64766512
if (routed) {
64776513
return { answer: 'read', over: true, endedWhy: routedWhy(routed), endedAt: typeof routed.startedAt === 'string' ? routed.startedAt : undefined, children };
@@ -6589,7 +6625,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
65896625
if (passed) found.passed.add(id);
65906626
if (seen.has(id) || settled.has(id)) continue;
65916627
seen.add(id);
6592-
let run: { status?: string; trigger?: { object?: string; recordId?: string }; steps?: unknown;
6628+
let run: { status?: string; completedAt?: string; trigger?: { object?: string; recordId?: string }; steps?: unknown;
65936629
summary?: { nodes?: ReadonlyArray<{ runs?: number; skipped?: number }>; detailOmitted?: boolean };
65946630
} | null;
65956631
try {
@@ -6612,7 +6648,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
66126648
const steps = (Array.isArray(run.steps) ? run.steps : []) as RunStepRead[];
66136649
// A cut log names its children in part and speaks for none: its run is not kept as ended.
66146650
const whole = stepLogCut(run, steps, TERMINAL_RUN_STATUSES.has(status)) === undefined;
6615-
const children = childRunsOf(steps, REACHED_AN_END.has(status), undefined, whole);
6651+
const children = childRunsOf(steps, REACHED_AN_END.has(status), undefined, whole, run.completedAt);
66166652
if (whole) found.childrenOf.set(id, children.map((c) => c.id));
66176653
if (TERMINAL_RUN_STATUSES.has(status)) found.terminal.add(id);
66186654
queue.push(...children);

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

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,8 +50,11 @@ export const MAX_PERSISTED_HISTORY_STEPS = 200;
5050
* history row's byte cap and cost the row the steps it keeps. A step whose
5151
* execution started more names the first ones started and carries
5252
* `childRunIdsTruncated: true`, so a reader never takes the list for all of
53-
* them. The same number as the approvals plugin's cap on the runs it reads
54-
* for one approval.
53+
* them. The same number as the approvals plugin's cap on the runs one
54+
* judgement of an approval reads (`MAX_RUNS_READ_PER_APPROVAL` in
55+
* `@objectstack/plugin-approvals`): the plugin's real-engine reconciler
56+
* suite ties the two, asserting that a step of a map of one item more names
57+
* exactly that many runs.
5558
*/
5659
export const MAX_STEP_CHILD_RUN_IDS = 200;
5760

‎packages/services/service-automation/src/step-child-runs.test.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -287,4 +287,58 @@ describe('[ADR-0162 item 8] the history row sheds the links before it drops a st
287287
await store.recordTerminal(record(steps));
288288
expect((await store.loadTerminal('r1'))!.steps).toEqual(steps);
289289
});
290+
291+
const CAP = 64 * 1024;
292+
/** A step that named every child run it started: its list is whole, so it carries no mark. */
293+
const whole = (n: number): StepLogEntry => ({
294+
nodeId: `each_${n}`, nodeType: 'map', status: 'success', startedAt: '2026-01-01T00:00:01.000Z',
295+
childRunIds: Array.from({ length: MAX_STEP_CHILD_RUN_IDS }, (_, i) => runIdLike(n * 1000 + i)),
296+
});
297+
const padded = (nodeId: string, length: number): StepLogEntry => ({ ...plain(nodeId), warnings: ['x'.repeat(length)] });
298+
const withoutLinks = (steps: StepLogEntry[]) => steps.map(({ childRunIds: _links, ...rest }) => rest);
299+
300+
it('a log still over the cap once its links are shed is halved: the newest steps are kept, each that named child runs marked', async () => {
301+
const table = rowTable();
302+
const store = new ObjectStoreSuspendedRunStore(table, createTestLogger());
303+
const steps = Array.from({ length: 16 }, (_, n) => [padded(`note_${n}`, 6 * 1024), delegating(n)]).flat();
304+
expect(JSON.stringify(withoutLinks(steps)).length, 'over the row cap without its links too').toBeGreaterThan(CAP);
305+
await store.recordTerminal(record(steps));
306+
307+
const kept = (await store.loadTerminal('r1'))!.steps!;
308+
expect(table.rows.get('run_r1').steps_json.length).toBeLessThanOrEqual(CAP);
309+
expect(kept.length, 'steps were dropped').toBeLessThan(steps.length);
310+
expect(kept.map((s) => s.nodeId), 'the newest steps, in order').toEqual(steps.slice(steps.length - kept.length).map((s) => s.nodeId));
311+
const marked = kept.filter((s) => s.nodeType === 'map');
312+
expect(marked.length).toBeGreaterThan(0);
313+
for (const s of marked) {
314+
expect(s.childRunIds).toBeUndefined();
315+
expect(s.childRunIdsTruncated).toBe(true);
316+
}
317+
for (const s of kept.filter((k) => k.nodeType !== 'map')) expect(s.childRunIdsTruncated).toBeUndefined();
318+
});
319+
320+
it('a log that fits the cap without its links by less than its marks cost is halved, where the same log that named no child run is kept whole', async () => {
321+
const MARK = ',"childRunIdsTruncated":true'.length;
322+
expect(MARK, 'what one mark costs').toBe(28);
323+
const build = (pad: number) => [padded('start', pad), ...Array.from({ length: 8 }, (_, n) => whole(n)), plain('end')];
324+
// Pad the log so that, without its links, it is 10 bytes under the cap: its 8 marks (224 bytes) put it over.
325+
const probe = JSON.stringify(withoutLinks(build(0))).length;
326+
const steps = build(CAP - 10 - probe);
327+
const bare = withoutLinks(steps);
328+
expect(JSON.stringify(bare).length).toBe(CAP - 10);
329+
expect(JSON.stringify(bare).length + 8 * MARK).toBeGreaterThan(CAP);
330+
331+
const table = rowTable();
332+
const store = new ObjectStoreSuspendedRunStore(table, createTestLogger());
333+
await store.recordTerminal(record(steps));
334+
const kept = (await store.loadTerminal('r1'))!.steps!;
335+
expect(kept.length, 'halved: the marks did not fit').toBe(steps.length - Math.ceil(steps.length / 2));
336+
expect(kept.map((s) => s.nodeId)).toEqual(steps.slice(Math.ceil(steps.length / 2)).map((s) => s.nodeId));
337+
338+
// The control: the same bytes from a log whose steps named no child run fit, and keep every step.
339+
const control = rowTable();
340+
const controlStore = new ObjectStoreSuspendedRunStore(control, createTestLogger());
341+
await controlStore.recordTerminal(record(bare));
342+
expect((await controlStore.loadTerminal('r1'))!.steps).toEqual(bare);
343+
});
290344
});

‎packages/services/service-automation/src/suspended-run-store.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1282,7 +1282,11 @@ function readConsumedSuspensionDropNotice(row: any): ConsumedSuspensionDropNotic
12821282
*/
12831283
function serializeStepsBounded(steps: RunRecord['steps']): string | null {
12841284
let tail = steps ?? [];
1285-
if (tail.length > 0 && JSON.stringify(tail).length > MAX_STEPS_JSON_BYTES) tail = tail.map(shedChildRunIds);
1285+
if (tail.length === 0) return null;
1286+
// A log under the cap is serialized once, and that text is the row's.
1287+
const whole = JSON.stringify(tail);
1288+
if (whole.length <= MAX_STEPS_JSON_BYTES) return whole;
1289+
tail = tail.map(shedChildRunIds);
12861290
while (tail.length > 0) {
12871291
const json = JSON.stringify(tail);
12881292
if (json.length <= MAX_STEPS_JSON_BYTES) return json;

‎packages/spec/src/automation/execution.zod.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -217,9 +217,12 @@ export const ExecutionStepLogSchema = lazySchema(() => z.object({
217217
droppedFields: z.array(DroppedFieldsEventSchema).optional()
218218
.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'),
219219
// [ADR-0162 Execution item 8] The child runs a delegating step started, so a
220-
// reader of one run can reach every run of its tree from the step log alone:
221-
// a child's own log is a row of its own, and nothing else on the parent's
222-
// log names it once the parent has moved past the step.
220+
// reader of one run can follow its log to the runs of its tree: a child's
221+
// own log is a row of its own, and nothing else on the parent's log names it
222+
// once the parent has moved past the step. Not to every run of it: the list
223+
// is bounded and can be shed (`childRunIdsTruncated` below, seat ruling
224+
// 7258590209 and ruling 7268216330), so a reader takes a marked step for
225+
// one that named only some of its runs, or none.
223226
childRunIds: z.array(z.string()).optional()
224227
.describe('Run ids of the child runs this step started: the one run of a `subflow`, and for a `map` the item runs this execution of the step started, at most 200, the first ones started. Absent for a step that started none, and where `childRunIdsTruncated` says the links were shed'),
225228
// [ADR-0162 Execution item 8] Seat ruling 7258590209 on #37767: the list is

0 commit comments

Comments
 (0)