Skip to content

Commit 5c0b6f6

Browse files
fix(service-automation): re-evaluate the start condition on every retry attempt (#34090)
<!-- claude-projects-attribution: {"github_login":"zhuangjianguo"} --> _Requested by **Steedos** · [project thread](https://claude.ai/code/project/chan_018ETKaNwMZCNRYD7D8Q9Ubb?thread=cmsg_018ETKaNwMZCNRYD7D8Q9UbbCpddLFmKzR39wJWZpkRMCi)_ Fixes #33935 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:流程配置 `errorHandling.strategy: 'retry'` 时,每次重试都会重新判断开始节点的启动条件;两条执行路径共用同一个判断函数。 - 为什么改:原来启动条件第一次求值出错后,重试路径完全不看启动条件,直接执行节点,作者设置的"是否运行"闸门被一次故障打开,可能写数据或发外部请求。 - 风险与回滚:只影响"启动条件求值出错 + retry 策略"这一错误路径;以前会无条件执行节点的运行,现在会失败或被跳过。回滚即撤销本 PR。 - 先看:`packages/services/service-automation/src/dag-traversal.ts` 的 `startConditionHolds` 与 `executeWithoutRetry` 里新增的闸门;其次 `engine.ts` 的 `execute` 闸门改为调用同一函数。 - 两分钟验证:`pnpm --filter @objectstack/service-automation exec vitest run src/start-condition-retry-33935.test.ts`,预期 5 个用例全部通过。 - 需要你做的:无,席位落地。 ## What changes - `dag-traversal.ts` gains `startConditionHolds`, the one start-node trigger-condition evaluator. No condition authored means the run proceeds. A condition that does not hold returns `false`. A condition that cannot be evaluated throws, as `evaluateCondition` already does (ADR-0032 §1c). - `execute()` (attempt 1) calls it instead of its inline copy, and its behaviour is unchanged. - `executeWithoutRetry` (every retry attempt) now calls the same gate in the same place, after the start-node lookup and before the input-schema guard and any node. Before, it went straight to the nodes, so a condition that faulted on attempt 1 let attempts 2 and later run the nodes ungated. - Result under `strategy: 'retry'`: a condition that faults on every attempt is retried as a fault, and the run ends `failed` with no node executed. A condition that faults once and then holds runs the nodes once. A condition that faults once and then does not hold answers the same `condition_not_met` skip that attempt 1 gives. The default strategy is unchanged. - The dry-run contract's retry qualifier (the divergence that the contract for #33757, in PR #33799, names) can be dropped once this lands. That follow-up belongs to the spec owner. - A patch changeset for `@objectstack/service-automation`. ## Tests New file `packages/services/service-automation/src/start-condition-retry-33935.test.ts`, with five pins written against an executor that counts real node executions: 1. A condition that faults on every attempt (a real CEL fault, `'abc' > 10`) with `retry` and `maxRetries: 2`: no node runs, the result is `success: false`, `status: 'failed'`, the gate is evaluated 3 times, and 3 failed rows are written. 2. Faults on attempt 1, then holds: the nodes run once and the gate is evaluated twice. 3. Faults on attempt 1, then does not hold: the `condition_not_met` skip envelope, no node, and the gate is evaluated twice. 4. CONTROL, default strategy: `failed` on the first fault, one evaluation, one failed row. 5. CONTROL, `retry` with a condition that holds or does not hold on attempt 1: answered on attempt 1, as before. Ablation (the fix was committed first; `scripts/ablation-replace.mjs`, mutation proven on disk, restore proven): the re-evaluation in `executeWithoutRetry` was replaced with `if (false ...)`. Pins 1–3 went red and the two controls stayed green. Pin 1's red was `expected 1 to be +0` at `expect(runs.count).toBe(0)`: the node ran on a retry attempt, which is the defect reproduced. Restore: blob back to the HEAD blob, and `git diff HEAD` empty. ## Acceptance notes - `retryExecution` treats a skipped attempt (`success: true`) as a successful attempt and returns it, so a skip on attempt 2 ends the retry loop. That matches attempt 1's skip answer. Attempt 1's fault still left its one `failed` row. - The sibling #33893/#33905 fold (branch `claude/area-A5b-33893` at 75b2f32) also edits `engine.ts`. `git merge-tree` against it and against `origin/main` is clean, and its hunks do not touch the start-condition gate or the `executeWithoutRetry` host. ## Verification Final head b55412e, after merging `origin/main`, with install and the closure rebuilt: <details><summary>Touched package and direct dependents</summary> - `pnpm --filter @objectstack/service-automation typecheck`: exit 0 (tsc plus `check:test-typecheck` OK) - `pnpm --filter @objectstack/service-automation test`: exit 0, Test Files 283 passed (283), Tests 4006 passed (4006) - `@objectstack/trigger-record-change` test: exit 0, 12/12 files, 122/122 tests - `@objectstack/trigger-schedule` test: exit 0, 13/13 files, 256/256 tests - `@objectstack/plugin-approvals` test: exit 0, 120/120 files, 1652/1652 tests - eslint on the three touched source files: exit 0 </details> <details><summary>Derived gate families</summary> dispatch-gates --commands derived 71 families for this diff at b55412e. 70 ran locally, all exit 0 (each exit captured before any pipe; check:type-check-debt ran under the verify lock: re-measure OK, 0 raw tsc errors). 1 not run locally: check:dual-build-cjs-loads, left to CI. The --ran reconciliation reads 71 derived, 70 run, 1 UNRUN (that one). </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01QsR2jUZKdq3PK2Sab53cT3)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent b0e8f6b commit 5c0b6f6

4 files changed

Lines changed: 230 additions & 15 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/service-automation': patch
3+
---
4+
5+
fix(service-automation): a flow under `errorHandling.strategy: 'retry'` re-evaluates its start condition on every retry attempt
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
When a flow's start-node `condition` could not be evaluated (a CEL fault against the record, for example), `execute()` handed the fault to the flow's error strategy. Under `strategy: 'retry'` every retry attempt then ran the flow's nodes without evaluating the start condition at all, so a fault on attempt 1 opened the author's gate on attempts 2 and later. Both attempt paths now call one start-condition evaluator. A condition that faults on every attempt is retried as a fault and the run ends `failed` with no node executed. A condition that faults once and then holds runs the nodes once. A condition that faults once and then does not hold skips the run with the same `condition_not_met` answer attempt 1 gives. The default strategy is unchanged.

‎packages/services/service-automation/src/dag-traversal.ts‎

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1230,9 +1230,49 @@ export function seedRunVariables(
12301230
return variables;
12311231
}
12321232

1233+
/**
1234+
* The start node's trigger-condition gate — the ONE evaluator both attempt
1235+
* paths call: `execute()` (attempt 1) and {@link executeWithoutRetry} (every
1236+
* retry attempt).
1237+
*
1238+
* The start node's `condition` is the predicate that decides whether the
1239+
* trigger event should launch the flow at all (e.g.
1240+
* `status == "done" && previous.status != "done"`). The engine, not the
1241+
* trigger, owns evaluating it, so every trigger type and a manual `execute()`
1242+
* share one gate. Plain-string conditions are routed through CEL so bare field
1243+
* references resolve.
1244+
*
1245+
* Three answers, the same on every attempt:
1246+
* - no condition authored (absent, `null` or `''`) → `true`, the run proceeds;
1247+
* - the condition does not hold → `false`, the caller answers the
1248+
* `condition_not_met` skip and runs no node;
1249+
* - the condition cannot be evaluated → it THROWS (ADR-0032 §1c, via
1250+
* `evaluateCondition`): a fault, which `execute()`'s catch hands to the
1251+
* flow's error strategy. Under `strategy: 'retry'` the fault is retried,
1252+
* and each retry attempt re-runs this gate — a fault stays a fault and
1253+
* never becomes a pass. Before this was shared, the retry path never
1254+
* evaluated the condition, so a condition that faulted on attempt 1 let
1255+
* attempts 2..N run the nodes ungated.
1256+
*/
1257+
export function startConditionHolds(
1258+
this: Pick<DagTraversalHost, 'evaluateCondition'>,
1259+
startNode: FlowNodeParsed,
1260+
variables: Map<string, unknown>,
1261+
context: AutomationContext,
1262+
): boolean {
1263+
const startCondition = (startNode.config as Record<string, unknown> | undefined)?.condition as
1264+
| string
1265+
| { dialect?: string; source?: string; ast?: unknown }
1266+
| undefined;
1267+
if (startCondition === undefined || startCondition === null || startCondition === '') return true;
1268+
const condExpr =
1269+
typeof startCondition === 'string' ? { dialect: 'cel', source: startCondition } : startCondition;
1270+
return this.evaluateCondition(condExpr, variables, context);
1271+
}
1272+
12331273
/** The body of {@link AutomationEngine.executeWithoutRetry}, moved unedited; that method's docblock is its contract. */
12341274
export async function executeWithoutRetry(
1235-
this: Pick<DagTraversalHost, 'flows' | 'isFlowEnabled' | 'describeDisabledFlow' | 'nextRunId' | 'seedRunVariables' | 'resolveRunContext' | 'validateNodeInputSchemas' | 'executeNode' | 'recordLog' | 'logger' | 'finishRefusedRun' | 'persistSuspendedRun' | 'flowChecksumOf' | 'renderFlowTerminalMessage' | 'flowSlotPackage'>,
1275+
this: Pick<DagTraversalHost, 'flows' | 'isFlowEnabled' | 'describeDisabledFlow' | 'nextRunId' | 'seedRunVariables' | 'resolveRunContext' | 'evaluateCondition' | 'validateNodeInputSchemas' | 'executeNode' | 'recordLog' | 'logger' | 'finishRefusedRun' | 'persistSuspendedRun' | 'flowChecksumOf' | 'renderFlowTerminalMessage' | 'flowSlotPackage'>,
12361276
flowName: string,
12371277
context?: AutomationContext,
12381278
dispatched?: { errorMessage: string | undefined },
@@ -1296,6 +1336,19 @@ export async function executeWithoutRetry(
12961336
return { success: false, code: 'FLOW_NO_START_NODE', error: 'Flow has no start node' };
12971337
}
12981338

1339+
// The SAME trigger-condition gate attempt 1 runs under, through the
1340+
// same evaluator (`startConditionHolds`), and in the same place: after
1341+
// the start-node lookup, before the input-schema guard and any node.
1342+
// A condition that does not hold on this attempt skips the run with
1343+
// the envelope `execute()` answers; one that throws lands in this
1344+
// method's failure arm below and consumes one retry attempt, so a
1345+
// condition that faults on every attempt ends the run `failed` with no
1346+
// node executed. `start-condition-retry-33935.test.ts` pins all three.
1347+
if (!startConditionHolds.call(this, startNode, variables, runContext)) {
1348+
this.logger.debug(`Flow '${flowName}' skipped: start condition not met`);
1349+
return { success: true, output: { skipped: true, reason: 'condition_not_met' }, flowLabel: flow.label };
1350+
}
1351+
12991352
// [#9889] The SAME definition-level guard attempt 1 runs under —
13001353
// the sixth instance of this method drifting from `execute()`
13011354
// (#9378, #9415, #9414, #9510, #9704 before it), and the first

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

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,7 @@ import {
126126
evaluateCondition,
127127
seedDeclaredVariables,
128128
seedRunVariables,
129+
startConditionHolds,
129130
executeWithoutRetry,
130131
type runUserOf,
131132
} from './dag-traversal.js';
@@ -7767,20 +7768,18 @@ export class AutomationEngine implements IAutomationService {
77677768
// trigger — owns evaluating it, so every trigger type (record-change,
77687769
// schedule, …) and a manual `execute()` share one gate. Plain-string
77697770
// conditions are routed through CEL so bare field references resolve.
7770-
const startCondition = (startNode.config as Record<string, unknown> | undefined)?.condition as
7771-
| string
7772-
| { dialect?: string; source?: string; ast?: unknown }
7773-
| undefined;
7774-
if (startCondition !== undefined && startCondition !== null && startCondition !== '') {
7775-
const condExpr =
7776-
typeof startCondition === 'string' ? { dialect: 'cel', source: startCondition } : startCondition;
7777-
if (!this.evaluateCondition(condExpr, variables, runContext)) {
7778-
this.logger.debug(`Flow '${flowName}' skipped: start condition not met`);
7779-
// `flowLabel` rides even here, unlike `successMessage` /
7780-
// `summary`: it names the flow, it claims no work done, and
7781-
// this answer reaches a runner as a 200 like any other.
7782-
return { success: true, output: { skipped: true, reason: 'condition_not_met' }, flowLabel: flow.label };
7783-
}
7771+
//
7772+
// The evaluator is shared with `executeWithoutRetry`, which re-runs
7773+
// this gate on every retry attempt: a condition that throws here
7774+
// is a fault the catch below hands to the error strategy, and
7775+
// under `strategy: 'retry'` each later attempt evaluates it again
7776+
// rather than running the nodes ungated (see `startConditionHolds`).
7777+
if (!startConditionHolds.call(this, startNode, variables, runContext)) {
7778+
this.logger.debug(`Flow '${flowName}' skipped: start condition not met`);
7779+
// `flowLabel` rides even here, unlike `successMessage` /
7780+
// `summary`: it names the flow, it claims no work done, and
7781+
// this answer reaches a runner as a 200 like any other.
7782+
return { success: true, output: { skipped: true, reason: 'condition_not_met' }, flowLabel: flow.label };
77847783
}
77857784

77867785
// Re-entrancy loop guard (see `activeRecordFlows`). Breaks the SAME
@@ -11550,6 +11549,7 @@ export class AutomationEngine implements IAutomationService {
1155011549
nextRunId: (...a) => this.nextRunId(...a),
1155111550
seedRunVariables: (...a) => this.seedRunVariables(...a),
1155211551
resolveRunContext: (...a) => this.resolveRunContext(...a),
11552+
evaluateCondition: (...a) => this.evaluateCondition(...a),
1155311553
validateNodeInputSchemas: (...a) => this.validateNodeInputSchemas(...a),
1155411554
executeNode: (...a) => this.executeNode(...a),
1155511555
recordLog: (...a) => this.recordLog(...a),
Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
import { describe, it, expect, vi } from 'vitest';
4+
import { AutomationEngine } from './engine.js';
5+
6+
/**
7+
* The start node's trigger-condition gate must hold on EVERY attempt, not
8+
* only the first.
9+
*
10+
* `execute()` evaluates the start condition; a condition that cannot be
11+
* evaluated THROWS (ADR-0032 §1c), and the throw lands in `execute()`'s catch,
12+
* which hands a flow declaring `errorHandling.strategy: 'retry'` to
13+
* `retryExecution`. Every retry attempt runs through `executeWithoutRetry`.
14+
* Before the repair that method went from the start-node lookup straight to
15+
* the nodes and never evaluated the condition, so a condition that faulted on
16+
* attempt 1 let attempts 2..N run the flow's nodes ungated: the author's gate
17+
* on whether the flow runs at all, opened by a fault.
18+
*
19+
* The rule pinned here: both attempt paths call one evaluator
20+
* (`startConditionHolds`), so a fault stays a fault (retried, never a pass),
21+
* a condition that does not hold skips the run exactly as on attempt 1, and a
22+
* condition that holds runs the nodes once.
23+
*
24+
* Written against the OBSERVABLE side effect, an executor counting real node
25+
* executions, never the returned envelope alone: the defect's harm is a
26+
* side-effecting node running when it should not.
27+
*/
28+
29+
function createTestLogger(): any {
30+
return { info: () => {}, warn: () => {}, error: () => {}, debug: () => {}, child: () => createTestLogger() };
31+
}
32+
33+
/** An engine holding one start-gated flow whose single work node counts every REAL execution. */
34+
function gatedFlowEngine(opts: { strategy?: 'retry' | 'fail' } = {}) {
35+
const engine = new AutomationEngine(createTestLogger());
36+
const runs = { count: 0 };
37+
38+
engine.registerNodeExecutor({
39+
type: 'probe_step',
40+
async execute() {
41+
runs.count++;
42+
return { success: true };
43+
},
44+
} as any);
45+
46+
engine.registerFlow('gated', {
47+
name: 'gated',
48+
label: 'Gated',
49+
type: 'autolaunched',
50+
...(opts.strategy === 'retry'
51+
? { errorHandling: { strategy: 'retry', maxRetries: 2, backoffMs: 0 } }
52+
: {}),
53+
nodes: [
54+
{ id: 'start', type: 'start', label: 'Start', config: { condition: 'record.amount > 10' } },
55+
{ id: 'work', type: 'probe_step', label: 'Work' },
56+
{ id: 'end', type: 'end', label: 'End' },
57+
],
58+
edges: [
59+
{ id: 'e0', source: 'start', target: 'work' },
60+
{ id: 'e1', source: 'work', target: 'end' },
61+
],
62+
} as any);
63+
64+
return { engine, runs };
65+
}
66+
67+
/** `'abc' > 10` has no CEL overload, so the real evaluator faults on this record. */
68+
const FAULTING_RECORD = { id: 'r1', amount: 'abc' };
69+
70+
describe("start condition under errorHandling.strategy: 'retry' — evaluated on every attempt", () => {
71+
it('a condition that faults on EVERY attempt runs no node, and the run ends failed', async () => {
72+
const { engine, runs } = gatedFlowEngine({ strategy: 'retry' });
73+
const evaluate = vi.spyOn(engine, 'evaluateCondition');
74+
75+
const result = await engine.execute('gated', { record: { ...FAULTING_RECORD } } as any);
76+
77+
// The point: the side-effecting node never ran. Before the repair it
78+
// ran on attempt 2, and that attempt answered success.
79+
expect(runs.count).toBe(0);
80+
expect(result.success).toBe(false);
81+
expect(result.status).toBe('failed');
82+
expect(result.error).toContain('condition');
83+
84+
// A fault is retried, never skipped: the gate was evaluated on attempt
85+
// 1 and on each of the `maxRetries: 2` retry attempts, and each attempt
86+
// left one failed row.
87+
expect(evaluate).toHaveBeenCalledTimes(3);
88+
const failedRows = await engine.listRuns('gated', { status: 'failed' });
89+
expect(failedRows).toHaveLength(3);
90+
});
91+
92+
it('a condition that faults on attempt 1 and holds on attempt 2 runs the nodes once', async () => {
93+
const { engine, runs } = gatedFlowEngine({ strategy: 'retry' });
94+
// Attempt 1 faults; every later call is the real evaluator, which
95+
// judges `record.amount > 10` against a record where it holds.
96+
const evaluate = vi.spyOn(engine, 'evaluateCondition').mockImplementationOnce(() => {
97+
throw new Error('condition evaluation error: transient fault — source: `record.amount > 10`');
98+
});
99+
100+
const result = await engine.execute('gated', { record: { id: 'r1', amount: 20 } } as any);
101+
102+
expect(result.success).toBe(true);
103+
expect((result.output as { skipped?: unknown } | undefined)?.skipped).toBeUndefined();
104+
expect(runs.count).toBe(1);
105+
expect(evaluate).toHaveBeenCalledTimes(2);
106+
});
107+
108+
it('a condition that faults on attempt 1 and does not hold on attempt 2 skips, running no node', async () => {
109+
const { engine, runs } = gatedFlowEngine({ strategy: 'retry' });
110+
const evaluate = vi.spyOn(engine, 'evaluateCondition').mockImplementationOnce(() => {
111+
throw new Error('condition evaluation error: transient fault — source: `record.amount > 10`');
112+
});
113+
114+
const result = await engine.execute('gated', { record: { id: 'r1', amount: 5 } } as any);
115+
116+
// The same skip envelope attempt 1 answers when its condition does not hold.
117+
expect(result).toMatchObject({
118+
success: true,
119+
output: { skipped: true, reason: 'condition_not_met' },
120+
flowLabel: 'Gated',
121+
});
122+
expect(runs.count).toBe(0);
123+
expect(evaluate).toHaveBeenCalledTimes(2);
124+
});
125+
126+
it('CONTROL — the default strategy answers failed on the first fault and never retries', async () => {
127+
const { engine, runs } = gatedFlowEngine();
128+
const evaluate = vi.spyOn(engine, 'evaluateCondition');
129+
130+
const result = await engine.execute('gated', { record: { ...FAULTING_RECORD } } as any);
131+
132+
expect(runs.count).toBe(0);
133+
expect(result.success).toBe(false);
134+
expect(result.status).toBe('failed');
135+
expect(result.error).toContain('condition');
136+
expect(evaluate).toHaveBeenCalledTimes(1);
137+
const failedRows = await engine.listRuns('gated', { status: 'failed' });
138+
expect(failedRows).toHaveLength(1);
139+
});
140+
141+
it('CONTROL — under retry, a condition that holds or does not hold on attempt 1 is answered there', async () => {
142+
const held = gatedFlowEngine({ strategy: 'retry' });
143+
const ran = await held.engine.execute('gated', { record: { id: 'r1', amount: 20 } } as any);
144+
expect(ran.success).toBe(true);
145+
expect(held.runs.count).toBe(1);
146+
147+
const notHeld = gatedFlowEngine({ strategy: 'retry' });
148+
const skipped = await notHeld.engine.execute('gated', { record: { id: 'r1', amount: 5 } } as any);
149+
expect(skipped).toMatchObject({ success: true, output: { skipped: true, reason: 'condition_not_met' } });
150+
expect(notHeld.runs.count).toBe(0);
151+
});
152+
});

0 commit comments

Comments
 (0)