Skip to content

Commit d858719

Browse files
committed
fix(service-automation): a run's record copy is taken before its context resolves, previous is copied too, and a value that contains itself fails the run
- resolveRunContext takes the run's own copy of the handed record before anything writes onto it; the start node's declared lookups are grafted onto that copy, and the run's variables are seeded from the resolved context, so the caller's record object is left as handed. - previous is bound as the run's own copy, by the same rule as the record. - A value handed to execute that contains itself is answered as a failed run (status 'failed', the copy's named error, one failed history row) instead of a rejection out of execute. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017xRBcW9L8Noz9BxEwjwiov
1 parent b1d5a7f commit d858719

5 files changed

Lines changed: 134 additions & 17 deletions

File tree

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

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1302,7 +1302,8 @@ export function seedRunVariables(
13021302
if (!variables.has(k)) variables.set(k, v);
13031303
}
13041304
}
1305-
variables.set('previous', context?.previous ?? null);
1305+
// `previous` is the run's own copy too, by the same rule as the record.
1306+
variables.set('previous', copyHeldValue(context?.previous ?? null));
13061307
variables.set('$runId', runId);
13071308
variables.set('$flowName', flowName);
13081309
variables.set('$flowLabel', flow.label ?? flowName);
@@ -1404,10 +1405,10 @@ export async function executeWithoutRetry(
14041405
// `flowRunId` is stamped here too (#3456). [#31696] And the slot, as
14051406
// `execute()` stamps it.
14061407
const runContext = await this.resolveRunContext(flow, context, runId);
1407-
// Seeded AFTER the context resolves: the run takes its own copy of the
1408-
// trigger record, so the lookups the start node declares (`expand`, grafted
1409-
// while the context resolves) must already be on it.
1410-
const variables = this.seedRunVariables(flow, flowName, context, runId);
1408+
// Seeded AFTER the context resolves, from the resolved context: its record
1409+
// is the run's own copy, carrying the lookups the start node declares
1410+
// (`expand`, grafted while the context resolves).
1411+
const variables = this.seedRunVariables(flow, flowName, runContext, runId);
14111412
stampFlowRunSlot(runContext, flowName, runPackage);
14121413
// [ADR-0162 item 7] Each attempt is a run of its own, and its own root
14131414
// when it has no parent, as `execute()` stamps it.

‎packages/services/service-automation/src/dry-run.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -797,9 +797,10 @@ export async function dryRun(this: DryRunHost, definition: unknown, options: Flo
797797
...(options.locale !== undefined ? { locale: options.locale } : {}),
798798
};
799799
const runContext = await this.resolveRunContext({ ...flow, runAs: 'user' }, start);
800-
// Seeded after the context resolves, as a run is: the run's own copy of the
801-
// record carries the lookups its start node declares.
802-
const variables: Map<string, unknown> = this.seedRunVariables(flow, flow.name, start, '');
800+
// Seeded after the context resolves, from the resolved context, as a run
801+
// is: its record is the run's own copy, carrying the lookups its start
802+
// node declares.
803+
const variables: Map<string, unknown> = this.seedRunVariables(flow, flow.name, runContext, '');
803804
variables.delete('$runId');
804805

805806
const startNode = flow.nodes.find((n) => n.type === 'start')!;

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

Lines changed: 77 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ export const DEFAULT_BRANCH_LABEL = 'default';
6565

6666
import { runTriggerUserId, type SeededRunContext } from './runtime-identity.js';
6767
import { flowContentChecksum } from './flow-identity.js';
68-
import { hasReservedVariableKeySegment } from './scope-key-segments.js';
68+
import { HeldValueCycleError, hasReservedVariableKeySegment } from './scope-key-segments.js';
6969
import { carriedRefusalOfResult, readCarriedRefusal, type CarriedRefusal } from './inner-refusal.js';
7070
import { summarizeRun } from './run-summary.js';
7171
import { withDroppedFields } from './run-dropped-fields.js';
@@ -8197,8 +8197,9 @@ export class AutomationEngine implements IAutomationService {
81978197
* ONLY the declared relation keys, and only when the re-read actually returned
81988198
* an object/array, so bare lookup ids and #1872 multi-lookup arrays on other
81998199
* relations — and the formula fields the trigger already hydrated — stay
8200-
* untouched. Mutates `record` in place (the same object the run's variable map
8201-
* already references). Best-effort: any failure leaves `record` unexpanded
8200+
* untouched. Mutates `record` in place: the run context's own copy of the
8201+
* record ({@link resolveRunContext} takes it first, and the run's variables
8202+
* are seeded from it after), never the object the caller handed. Best-effort: any failure leaves `record` unexpanded
82028203
* (the template then renders the scalar id) — expansion must never break the
82038204
* flow it feeds.
82048205
*/
@@ -8232,6 +8233,61 @@ export class AutomationEngine implements IAutomationService {
82328233
return this.executeKey(resolved.key, context, startTime);
82338234
}
82348235

8236+
/**
8237+
* The answer {@link executeKey} gives a run that fails while its values
8238+
* are seeded, before its first node: a value it was handed contains itself
8239+
* ({@link HeldValueCycleError}), so the run cannot take its own copy. The
8240+
* failed-run shape of `execute()`'s failure exit — `status: 'failed'`
8241+
* (the run was dispatched and failed), `error`, `durationMs`, `summary`,
8242+
* `flowLabel` — with one `failed` history row, and no `errorMessage`
8243+
* (there are no run variables to render the author's text over). Never
8244+
* retried: the same value fails the same way on every attempt.
8245+
*/
8246+
private failRunBeforeFirstNode(run: {
8247+
runId: string; flowName: string; flow: FlowParsed; startedAt: string; startTime: number;
8248+
context: AutomationContext | undefined; error: string;
8249+
}): AutomationResult {
8250+
const { runId, flowName, flow, startedAt, context, error } = run;
8251+
const durationMs = Date.now() - run.startTime;
8252+
const steps: StepLogEntry[] = [];
8253+
let logged: ExecutionLogEntry | undefined;
8254+
try {
8255+
logged = this.recordLog({
8256+
id: runId,
8257+
flowName,
8258+
flowVersion: flow.version,
8259+
status: 'failed',
8260+
startedAt,
8261+
completedAt: new Date().toISOString(),
8262+
durationMs,
8263+
waitMs: 0,
8264+
trigger: buildRunTrigger(context),
8265+
steps,
8266+
error,
8267+
}, context);
8268+
} catch (bookkeeping) {
8269+
// DURABILITY, so `error`, as at `execute()`'s failure exit: the
8270+
// caller is told the run failed, and the history row is lost.
8271+
this.logger.error(
8272+
`[Automation] run '${runId}' of flow '${flowName}' FAILED before its first node and its run-history ` +
8273+
`bookkeeping threw, so its terminal 'failed' row never landed — nothing retries the write, and ` +
8274+
`this run is invisible to the Runs surfaces. The caller was answered status 'failed' carrying ` +
8275+
`the run's error, so nothing needs re-driving on account of this line. Fix the history failure ` +
8276+
`in this record's meta.`,
8277+
undefined,
8278+
describeThrownForLog(bookkeeping),
8279+
);
8280+
}
8281+
return {
8282+
success: false,
8283+
error,
8284+
durationMs,
8285+
status: 'failed',
8286+
flowLabel: flow.label,
8287+
summary: logged?.summary ?? summarizeRun(steps),
8288+
};
8289+
}
8290+
82358291
/**
82368292
* [#31696] {@link execute} for the flow filed under the slot key
82378293
* `flowName`, already resolved. Every record of the run is keyed by it.
@@ -8319,11 +8375,23 @@ export class AutomationEngine implements IAutomationService {
83198375
// and resolves the triggering user's real grants for `runAs:'user'` (#3356).
83208376
// Also stamps `flowRunId` so this run's data writes are attributable to it
83218377
// (#3456).
8322-
const runContext = await this.resolveRunContext(flow, context, runId);
8323-
// Seeded AFTER the context resolves: the run takes its own copy of the
8324-
// trigger record, so the lookups the start node declares (`expand`,
8325-
// grafted while the context resolves) must already be on it.
8326-
const variables = this.seedRunVariables(flow, flowName, context, runId);
8378+
let runContext: AutomationContext;
8379+
let variables: Map<string, unknown>;
8380+
try {
8381+
runContext = await this.resolveRunContext(flow, context, runId);
8382+
// Seeded AFTER the context resolves, from the resolved context: its
8383+
// record is the run's own copy, carrying the lookups the start node
8384+
// declares (`expand`, grafted while the context resolves).
8385+
variables = this.seedRunVariables(flow, flowName, runContext, runId);
8386+
} catch (err) {
8387+
// A value the run is handed that contains itself (the record,
8388+
// `previous`) has no copy for the run to take: the run fails
8389+
// before its first node, answered in the failed-run shape below
8390+
// and recorded as such, never a throw out of `execute()`. Any
8391+
// other throw is unchanged.
8392+
if (!(err instanceof HeldValueCycleError)) throw err;
8393+
return this.failRunBeforeFirstNode({ runId, flowName, flow, startedAt, startTime, context, error: err.message });
8394+
}
83278395
stampFlowRunSlot(runContext, flowName, runPackage);
83288396
// [ADR-0162 item 7] The run's root run: itself, or its parent's.
83298397
stampRootRun(runContext, { runId, flowName, startedAt });
@@ -12140,7 +12208,7 @@ export class AutomationEngine implements IAutomationService {
1214012208
* create leg (#3427). Binding it only when truthy left `previous` an
1214112209
* unknown CEL variable on insert, so ANY reference to it (even
1214212210
* `previous == null`) threw "Unknown variable: previous" and failed the
12143-
* whole condition;
12211+
* whole condition. Like the record, it is the run's OWN copy;
1214412212
* 4. `$runId`, so a pausing node (e.g. Approval) can map its external
1214512213
* state back to this run for resume (ADR-0019), and `$flowName` /
1214612214
* `$flowLabel`, so externalized state carries a human-readable origin.

‎packages/services/service-automation/src/run-resume.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,13 @@ export async function resolveRunContext(this: Pick<RunResumeHost, 'seedRunGrants
139139
flowName: flow.name,
140140
...(runId ? { flowRunId: runId } : {}),
141141
};
142+
// The run's own copy of the record it was handed (`copyHeldValue`), taken
143+
// before anything below writes onto it: the lookups the start node
144+
// declares (`expandDeclaredLookups`, at the end) are grafted onto this
145+
// copy, and the run's variables are seeded from it, so nothing the run
146+
// does reaches the caller's object. A record that contains itself throws
147+
// `HeldValueCycleError` here, which `execute()` answers as a failed run.
148+
if (context?.record) runContext.record = copyHeldValue(context.record) as Record<string, unknown>;
142149

143150
// #3356 (follow-up to #1888) — a `runAs:'user'` run must enforce its data
144151
// ops as the TRIGGERING user's real authorization. Most trigger surfaces

‎packages/services/service-automation/src/run-values-isolation.test.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,9 +202,49 @@ describe('the trigger record is the run\'s own copy', () => {
202202
expect(run.output).toMatchObject({ seen: 'touched', seen_trigger: 'touched' });
203203
expect(trigger).toEqual({ mode: 'a', nested: { n: 1 } });
204204
});
205+
206+
it('a start node that declares expand: the run reads the expanded relation, and the caller\'s record object is unchanged', async () => {
207+
const engine = makeEngine();
208+
engine.setRecordExpander(async (_object, id) => ({ id, account: { id: 'a1', name: 'Acme' } }));
209+
const flow = chain('iso_expand', [
210+
assign({ seen: cel('record.account.name') }),
211+
], [{ name: 'seen', type: 'text', isOutput: true }]);
212+
flow.runAs = 'system';
213+
flow.nodes[0].config = { expand: ['account'] };
214+
engine.registerFlow('iso_expand', flow);
215+
const trigger = { id: 'd1', account: 'a1' };
216+
const run = await engine.execute('iso_expand', { object: 'deal', record: trigger } as any);
217+
expect(run.success, JSON.stringify(run)).toBe(true);
218+
expect((run.output as any).seen).toBe('Acme');
219+
expect(trigger).toEqual({ id: 'd1', account: 'a1' });
220+
});
221+
222+
it('a node that changes previous in place leaves the caller\'s previous object as handed', async () => {
223+
const engine = makeEngine();
224+
engine.registerFlow('iso_previous', chain('iso_previous', [
225+
{ type: 'touch', config: { target: 'previous' } },
226+
assign({ seen: cel('previous.mode') }),
227+
], [{ name: 'seen', type: 'text', isOutput: true }]));
228+
const previous = { mode: 'p', nested: { n: 1 } };
229+
const run = await engine.execute('iso_previous', { record: { mode: 'a' }, previous } as any);
230+
expect(run.success, JSON.stringify(run)).toBe(true);
231+
expect((run.output as any).seen).toBe('touched');
232+
expect(previous).toEqual({ mode: 'p', nested: { n: 1 } });
233+
});
205234
});
206235

207236
describe('a value that contains itself', () => {
237+
it('handed to execute as the record: the run is answered failed, naming the refusal, and execute does not reject', async () => {
238+
const engine = makeEngine();
239+
engine.registerFlow('iso_ring_record', chain('iso_ring_record', [
240+
assign({ seen: cel('record.label') }),
241+
], [{ name: 'seen', type: 'text', isOutput: true }]));
242+
const ring: Record<string, unknown> = { label: 'ring' };
243+
ring.self = ring;
244+
const run = await engine.execute('iso_ring_record', { record: ring } as any);
245+
expect(run).toMatchObject({ success: false, status: 'failed', error: new HeldValueCycleError().message });
246+
});
247+
208248
it('is refused by the copy with a named error', () => {
209249
const ring: Record<string, unknown> = { label: 'ring' };
210250
ring.self = ring;

0 commit comments

Comments
 (0)