From 6919071e79f548b0363fbf67179e9600bb8917b0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 16:10:41 +0000 Subject: [PATCH 1/3] fix(service-automation): re-evaluate the start condition on every retry attempt Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUZKdq3PK2Sab53cT3 --- .../service-automation/src/dag-traversal.ts | 55 ++++++- .../services/service-automation/src/engine.ts | 28 ++-- .../src/start-condition-retry-33935.test.ts | 152 ++++++++++++++++++ 3 files changed, 220 insertions(+), 15 deletions(-) create mode 100644 packages/services/service-automation/src/start-condition-retry-33935.test.ts diff --git a/packages/services/service-automation/src/dag-traversal.ts b/packages/services/service-automation/src/dag-traversal.ts index 450973092ab..136e5e1ada9 100644 --- a/packages/services/service-automation/src/dag-traversal.ts +++ b/packages/services/service-automation/src/dag-traversal.ts @@ -1230,9 +1230,49 @@ export function seedRunVariables( return variables; } +/** + * The start node's trigger-condition gate — the ONE evaluator both attempt + * paths call: `execute()` (attempt 1) and {@link executeWithoutRetry} (every + * retry attempt). + * + * The start node's `condition` is the predicate that decides whether the + * trigger event should launch the flow at all (e.g. + * `status == "done" && previous.status != "done"`). The engine, not the + * trigger, owns evaluating it, so every trigger type and a manual `execute()` + * share one gate. Plain-string conditions are routed through CEL so bare field + * references resolve. + * + * Three answers, the same on every attempt: + * - no condition authored (absent, `null` or `''`) → `true`, the run proceeds; + * - the condition does not hold → `false`, the caller answers the + * `condition_not_met` skip and runs no node; + * - the condition cannot be evaluated → it THROWS (ADR-0032 §1c, via + * `evaluateCondition`): a fault, which `execute()`'s catch hands to the + * flow's error strategy. Under `strategy: 'retry'` the fault is retried, + * and each retry attempt re-runs this gate — a fault stays a fault and + * never becomes a pass. Before this was shared, the retry path never + * evaluated the condition, so a condition that faulted on attempt 1 let + * attempts 2..N run the nodes ungated. + */ +export function startConditionHolds( + this: Pick, + startNode: FlowNodeParsed, + variables: Map, + context: AutomationContext, +): boolean { + const startCondition = (startNode.config as Record | undefined)?.condition as + | string + | { dialect?: string; source?: string; ast?: unknown } + | undefined; + if (startCondition === undefined || startCondition === null || startCondition === '') return true; + const condExpr = + typeof startCondition === 'string' ? { dialect: 'cel', source: startCondition } : startCondition; + return this.evaluateCondition(condExpr, variables, context); +} + /** 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 }, @@ -1296,6 +1336,19 @@ export async function executeWithoutRetry( return { success: false, code: 'FLOW_NO_START_NODE', error: 'Flow has no start node' }; } + // The SAME trigger-condition gate attempt 1 runs under, through the + // same evaluator (`startConditionHolds`), and in the same place: after + // the start-node lookup, before the input-schema guard and any node. + // A condition that does not hold on this attempt skips the run with + // the envelope `execute()` answers; one that throws lands in this + // method's failure arm below and consumes one retry attempt, so a + // condition that faults on every attempt ends the run `failed` with no + // node executed. `start-condition-retry-33935.test.ts` pins all three. + if (!startConditionHolds.call(this, startNode, variables, runContext)) { + this.logger.debug(`Flow '${flowName}' skipped: start condition not met`); + return { success: true, output: { skipped: true, reason: 'condition_not_met' }, flowLabel: flow.label }; + } + // [#9889] The SAME definition-level guard attempt 1 runs under — // the sixth instance of this method drifting from `execute()` // (#9378, #9415, #9414, #9510, #9704 before it), and the first diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index a1b58d9187b..cc91208f2ac 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -126,6 +126,7 @@ import { evaluateCondition, seedDeclaredVariables, seedRunVariables, + startConditionHolds, executeWithoutRetry, type runUserOf, } from './dag-traversal.js'; @@ -7767,20 +7768,18 @@ export class AutomationEngine implements IAutomationService { // trigger — owns evaluating it, so every trigger type (record-change, // schedule, …) and a manual `execute()` share one gate. Plain-string // conditions are routed through CEL so bare field references resolve. - const startCondition = (startNode.config as Record | undefined)?.condition as - | string - | { dialect?: string; source?: string; ast?: unknown } - | undefined; - if (startCondition !== undefined && startCondition !== null && startCondition !== '') { - const condExpr = - typeof startCondition === 'string' ? { dialect: 'cel', source: startCondition } : startCondition; - if (!this.evaluateCondition(condExpr, variables, runContext)) { - this.logger.debug(`Flow '${flowName}' skipped: start condition not met`); - // `flowLabel` rides even here, unlike `successMessage` / - // `summary`: it names the flow, it claims no work done, and - // this answer reaches a runner as a 200 like any other. - return { success: true, output: { skipped: true, reason: 'condition_not_met' }, flowLabel: flow.label }; - } + // + // The evaluator is shared with `executeWithoutRetry`, which re-runs + // this gate on every retry attempt: a condition that throws here + // is a fault the catch below hands to the error strategy, and + // under `strategy: 'retry'` each later attempt evaluates it again + // rather than running the nodes ungated (see `startConditionHolds`). + if (!startConditionHolds.call(this, startNode, variables, runContext)) { + this.logger.debug(`Flow '${flowName}' skipped: start condition not met`); + // `flowLabel` rides even here, unlike `successMessage` / + // `summary`: it names the flow, it claims no work done, and + // this answer reaches a runner as a 200 like any other. + return { success: true, output: { skipped: true, reason: 'condition_not_met' }, flowLabel: flow.label }; } // Re-entrancy loop guard (see `activeRecordFlows`). Breaks the SAME @@ -11550,6 +11549,7 @@ export class AutomationEngine implements IAutomationService { nextRunId: (...a) => this.nextRunId(...a), seedRunVariables: (...a) => this.seedRunVariables(...a), resolveRunContext: (...a) => this.resolveRunContext(...a), + evaluateCondition: (...a) => this.evaluateCondition(...a), validateNodeInputSchemas: (...a) => this.validateNodeInputSchemas(...a), executeNode: (...a) => this.executeNode(...a), recordLog: (...a) => this.recordLog(...a), diff --git a/packages/services/service-automation/src/start-condition-retry-33935.test.ts b/packages/services/service-automation/src/start-condition-retry-33935.test.ts new file mode 100644 index 00000000000..c5287df1fb9 --- /dev/null +++ b/packages/services/service-automation/src/start-condition-retry-33935.test.ts @@ -0,0 +1,152 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, it, expect, vi } from 'vitest'; +import { AutomationEngine } from './engine.js'; + +/** + * The start node's trigger-condition gate must hold on EVERY attempt, not + * only the first. + * + * `execute()` evaluates the start condition; a condition that cannot be + * evaluated THROWS (ADR-0032 §1c), and the throw lands in `execute()`'s catch, + * which hands a flow declaring `errorHandling.strategy: 'retry'` to + * `retryExecution`. Every retry attempt runs through `executeWithoutRetry`. + * Before the repair that method went from the start-node lookup straight to + * the nodes and never evaluated the condition, so a condition that faulted on + * attempt 1 let attempts 2..N run the flow's nodes ungated: the author's gate + * on whether the flow runs at all, opened by a fault. + * + * The rule pinned here: both attempt paths call one evaluator + * (`startConditionHolds`), so a fault stays a fault (retried, never a pass), + * a condition that does not hold skips the run exactly as on attempt 1, and a + * condition that holds runs the nodes once. + * + * Written against the OBSERVABLE side effect, an executor counting real node + * executions, never the returned envelope alone: the defect's harm is a + * side-effecting node running when it should not. + */ + +function createTestLogger(): any { + return { info: () => {}, warn: () => {}, error: () => {}, debug: () => {}, child: () => createTestLogger() }; +} + +/** An engine holding one start-gated flow whose single work node counts every REAL execution. */ +function gatedFlowEngine(opts: { strategy?: 'retry' | 'fail' } = {}) { + const engine = new AutomationEngine(createTestLogger()); + const runs = { count: 0 }; + + engine.registerNodeExecutor({ + type: 'probe_step', + async execute() { + runs.count++; + return { success: true }; + }, + } as any); + + engine.registerFlow('gated', { + name: 'gated', + label: 'Gated', + type: 'autolaunched', + ...(opts.strategy === 'retry' + ? { errorHandling: { strategy: 'retry', maxRetries: 2, backoffMs: 0 } } + : {}), + nodes: [ + { id: 'start', type: 'start', label: 'Start', config: { condition: 'record.amount > 10' } }, + { id: 'work', type: 'probe_step', label: 'Work' }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e0', source: 'start', target: 'work' }, + { id: 'e1', source: 'work', target: 'end' }, + ], + } as any); + + return { engine, runs }; +} + +/** `'abc' > 10` has no CEL overload, so the real evaluator faults on this record. */ +const FAULTING_RECORD = { id: 'r1', amount: 'abc' }; + +describe("start condition under errorHandling.strategy: 'retry' — evaluated on every attempt", () => { + it('a condition that faults on EVERY attempt runs no node, and the run ends failed', async () => { + const { engine, runs } = gatedFlowEngine({ strategy: 'retry' }); + const evaluate = vi.spyOn(engine, 'evaluateCondition'); + + const result = await engine.execute('gated', { record: { ...FAULTING_RECORD } } as any); + + // The point: the side-effecting node never ran. Before the repair it + // ran on attempt 2, and that attempt answered success. + expect(runs.count).toBe(0); + expect(result.success).toBe(false); + expect(result.status).toBe('failed'); + expect(result.error).toContain('condition'); + + // A fault is retried, never skipped: the gate was evaluated on attempt + // 1 and on each of the `maxRetries: 2` retry attempts, and each attempt + // left one failed row. + expect(evaluate).toHaveBeenCalledTimes(3); + const failedRows = await engine.listRuns('gated', { status: 'failed' }); + expect(failedRows).toHaveLength(3); + }); + + it('a condition that faults on attempt 1 and holds on attempt 2 runs the nodes once', async () => { + const { engine, runs } = gatedFlowEngine({ strategy: 'retry' }); + // Attempt 1 faults; every later call is the real evaluator, which + // judges `record.amount > 10` against a record where it holds. + const evaluate = vi.spyOn(engine, 'evaluateCondition').mockImplementationOnce(() => { + throw new Error('condition evaluation error: transient fault — source: `record.amount > 10`'); + }); + + const result = await engine.execute('gated', { record: { id: 'r1', amount: 20 } } as any); + + expect(result.success).toBe(true); + expect(result.output?.skipped).toBeUndefined(); + expect(runs.count).toBe(1); + expect(evaluate).toHaveBeenCalledTimes(2); + }); + + it('a condition that faults on attempt 1 and does not hold on attempt 2 skips, running no node', async () => { + const { engine, runs } = gatedFlowEngine({ strategy: 'retry' }); + const evaluate = vi.spyOn(engine, 'evaluateCondition').mockImplementationOnce(() => { + throw new Error('condition evaluation error: transient fault — source: `record.amount > 10`'); + }); + + const result = await engine.execute('gated', { record: { id: 'r1', amount: 5 } } as any); + + // The same skip envelope attempt 1 answers when its condition does not hold. + expect(result).toMatchObject({ + success: true, + output: { skipped: true, reason: 'condition_not_met' }, + flowLabel: 'Gated', + }); + expect(runs.count).toBe(0); + expect(evaluate).toHaveBeenCalledTimes(2); + }); + + it('CONTROL — the default strategy answers failed on the first fault and never retries', async () => { + const { engine, runs } = gatedFlowEngine(); + const evaluate = vi.spyOn(engine, 'evaluateCondition'); + + const result = await engine.execute('gated', { record: { ...FAULTING_RECORD } } as any); + + expect(runs.count).toBe(0); + expect(result.success).toBe(false); + expect(result.status).toBe('failed'); + expect(result.error).toContain('condition'); + expect(evaluate).toHaveBeenCalledTimes(1); + const failedRows = await engine.listRuns('gated', { status: 'failed' }); + expect(failedRows).toHaveLength(1); + }); + + it('CONTROL — under retry, a condition that holds or does not hold on attempt 1 is answered there', async () => { + const held = gatedFlowEngine({ strategy: 'retry' }); + const ran = await held.engine.execute('gated', { record: { id: 'r1', amount: 20 } } as any); + expect(ran.success).toBe(true); + expect(held.runs.count).toBe(1); + + const notHeld = gatedFlowEngine({ strategy: 'retry' }); + const skipped = await notHeld.engine.execute('gated', { record: { id: 'r1', amount: 5 } } as any); + expect(skipped).toMatchObject({ success: true, output: { skipped: true, reason: 'condition_not_met' } }); + expect(notHeld.runs.count).toBe(0); + }); +}); From cd76bb216797c1bd2bdbc32b295b5535388379a2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 16:20:22 +0000 Subject: [PATCH 2/3] chore(changeset): patch note for the start-condition retry gate Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUZKdq3PK2Sab53cT3 --- .changeset/33935-start-condition-retry.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 .changeset/33935-start-condition-retry.md diff --git a/.changeset/33935-start-condition-retry.md b/.changeset/33935-start-condition-retry.md new file mode 100644 index 00000000000..b6c63df2f2d --- /dev/null +++ b/.changeset/33935-start-condition-retry.md @@ -0,0 +1,10 @@ +--- +'@objectstack/service-automation': patch +--- + +fix(service-automation): a flow under `errorHandling.strategy: 'retry'` re-evaluates its start condition on every retry attempt + +Clause-②: no +Metadata-protocol: none + +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. From 94cd8fbbc460da1564b54cda00c1a9f9dfca2968 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 17:23:12 +0000 Subject: [PATCH 3/3] test(service-automation): type the skipped-output read in the start-condition retry pins Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUZKdq3PK2Sab53cT3 --- .../service-automation/src/start-condition-retry-33935.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/services/service-automation/src/start-condition-retry-33935.test.ts b/packages/services/service-automation/src/start-condition-retry-33935.test.ts index c5287df1fb9..30ccf6cd380 100644 --- a/packages/services/service-automation/src/start-condition-retry-33935.test.ts +++ b/packages/services/service-automation/src/start-condition-retry-33935.test.ts @@ -100,7 +100,7 @@ describe("start condition under errorHandling.strategy: 'retry' — evaluated on const result = await engine.execute('gated', { record: { id: 'r1', amount: 20 } } as any); expect(result.success).toBe(true); - expect(result.output?.skipped).toBeUndefined(); + expect((result.output as { skipped?: unknown } | undefined)?.skipped).toBeUndefined(); expect(runs.count).toBe(1); expect(evaluate).toHaveBeenCalledTimes(2); });