Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .changeset/33935-start-condition-retry.md
Original file line number Diff line number Diff line change
@@ -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.
55 changes: 54 additions & 1 deletion packages/services/service-automation/src/dag-traversal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<DagTraversalHost, 'evaluateCondition'>,
startNode: FlowNodeParsed,
variables: Map<string, unknown>,
context: AutomationContext,
): boolean {
const startCondition = (startNode.config as Record<string, unknown> | 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<DagTraversalHost, 'flows' | 'isFlowEnabled' | 'describeDisabledFlow' | 'nextRunId' | 'seedRunVariables' | 'resolveRunContext' | 'validateNodeInputSchemas' | 'executeNode' | 'recordLog' | 'logger' | 'finishRefusedRun' | 'persistSuspendedRun' | 'flowChecksumOf' | 'renderFlowTerminalMessage' | 'flowSlotPackage'>,
this: Pick<DagTraversalHost, 'flows' | 'isFlowEnabled' | 'describeDisabledFlow' | 'nextRunId' | 'seedRunVariables' | 'resolveRunContext' | 'evaluateCondition' | 'validateNodeInputSchemas' | 'executeNode' | 'recordLog' | 'logger' | 'finishRefusedRun' | 'persistSuspendedRun' | 'flowChecksumOf' | 'renderFlowTerminalMessage' | 'flowSlotPackage'>,
flowName: string,
context?: AutomationContext,
dispatched?: { errorMessage: string | undefined },
Expand Down Expand Up @@ -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
Expand Down
28 changes: 14 additions & 14 deletions packages/services/service-automation/src/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ import {
evaluateCondition,
seedDeclaredVariables,
seedRunVariables,
startConditionHolds,
executeWithoutRetry,
type runUserOf,
} from './dag-traversal.js';
Expand Down Expand Up @@ -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<string, unknown> | 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
Expand Down Expand Up @@ -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),
Expand Down
Original file line number Diff line number Diff line change
@@ -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 as { skipped?: unknown } | undefined)?.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);
});
});
Loading