Skip to content

Commit 26d6b3a

Browse files
committed
fix(service-automation): a declared lookup is grafted into a new top-level record, so the caller's record is never written
expandDeclaredLookups no longer assigns into the record it is given: it sets a new top-level record as runContext.record, built from the record's own enumerable properties and then the grafted relations. A record that is not a plain object, which the run's copy hands back as it is, now keeps what the caller handed, and the run still reads the expanded relation. Pins: a class-instance record with a start node that declares expand; and, for the two other paths that seed from the resolved run context, a retried run (every attempt reads the expanded relation) and a dry run. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017xRBcW9L8Noz9BxEwjwiov
1 parent d2273ab commit 26d6b3a

3 files changed

Lines changed: 101 additions & 12 deletions

File tree

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

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8197,11 +8197,14 @@ 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 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
8203-
* (the template then renders the scalar id) — expansion must never break the
8204-
* flow it feeds.
8200+
* untouched. Never writes into `record`: a graft sets a NEW top-level
8201+
* record as `runContext.record` — the own enumerable properties of the one
8202+
* it replaces, then the grafted relations — so neither the caller's object
8203+
* nor the run context's copy of it ({@link resolveRunContext} takes it
8204+
* first, and the run's variables are seeded after) is changed, a record
8205+
* that is not a plain object included. Best-effort: any failure leaves
8206+
* `record` unexpanded (the template then renders the scalar id) —
8207+
* expansion must never break the flow it feeds.
82058208
*/
82068209
private expandDeclaredLookups(flow: FlowParsed, runContext: AutomationContext): Promise<void> {
82078210
// The body lives in ./run-resume.ts (#25222).

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

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ import { carriedRefusalOfResult, readCarriedRefusal } from './inner-refusal.js';
2828
import { summarizeRun } from './run-summary.js';
2929
import { dropEventsOf, foldDropEvents } from './run-dropped-fields.js';
3030
import { noteTenantCurrencyReadFault } from './builtin/template.js';
31-
import { HeldValueCycleError, RESERVED_VARIABLE_KEY_REFUSAL, copyHeldValue } from './scope-key-segments.js';
31+
import { HeldValueCycleError, RESERVED_VARIABLE_KEY_REFUSAL, copyHeldValue, scopeContainer } from './scope-key-segments.js';
3232
import { mapItemCancelledVariable, type MapItemCancelledMarker } from './builtin/map-node.js';
3333
// The values below (`buildRunTrigger`, `FlowRefusalSignal`, `isRefusalSignal`,
3434
// `isSuspendSignal`, `isRetryableResumeRefusal`, `carriesSubflowChildOutput`,
@@ -141,9 +141,10 @@ export async function resolveRunContext(this: Pick<RunResumeHost, 'seedRunGrants
141141
};
142142
// The run's own copy of the record it was handed (`copyHeldValue`), taken
143143
// 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
144+
// declares (`expandDeclaredLookups`, at the end) are grafted into a new
145+
// top-level record that replaces it, and the run's variables are seeded
146+
// from that, so nothing the run does reaches the caller's object, a record
147+
// that is not a plain object included. A record that contains itself throws
147148
// `HeldValueCycleError` here, which `execute()` answers as a failed run.
148149
if (context?.record) runContext.record = copyHeldValue(context.record) as Record<string, unknown>;
149150

@@ -479,7 +480,21 @@ function decisionImpersonatorOf(signal: ResumeSignal): string | undefined {
479480
return trimmed ? trimmed : undefined;
480481
}
481482

482-
/** The body of {@link AutomationEngine.expandDeclaredLookups}, moved unedited; that method's docblock is its contract. */
483+
/**
484+
* A NEW top-level record: the own enumerable properties of `record`, then each
485+
* grafted relation. `record` itself is never written, so a record that is not
486+
* a plain object (one `copyHeldValue` hands back as it is) keeps what it was
487+
* handed. A record with no prototype gets a result with none.
488+
*/
489+
function withGraftedRelations(record: Record<string, unknown>, grafts: ReadonlyArray<[string, unknown]>): Record<string, unknown> {
490+
const out: Record<string, unknown> = Object.getPrototypeOf(record) === null ? scopeContainer() : {};
491+
for (const [key, value] of [...Object.entries(record), ...grafts]) {
492+
Object.defineProperty(out, key, { value, enumerable: true, writable: true, configurable: true });
493+
}
494+
return out;
495+
}
496+
497+
/** The body of {@link AutomationEngine.expandDeclaredLookups}; that method's docblock is its contract. */
483498
export async function expandDeclaredLookups(this: Pick<RunResumeHost, 'recordExpander' | 'logger'>, flow: FlowParsed, runContext: AutomationContext): Promise<void> {
484499
if (!this.recordExpander) return;
485500
const record = runContext.record as Record<string, unknown> | undefined;
@@ -502,15 +517,17 @@ export async function expandDeclaredLookups(this: Pick<RunResumeHost, 'recordExp
502517
try {
503518
const full = await this.recordExpander(object, id, expandFields, runContext);
504519
if (full && typeof full === 'object') {
520+
const grafts: Array<[string, unknown]> = [];
505521
for (const field of expandFields) {
506522
const expanded = (full as Record<string, unknown>)[field];
507523
// Graft only a genuinely expanded relation (object/array); a
508524
// scalar means the field is not a resolvable lookup — leave the
509525
// raw id in place rather than overwrite it.
510526
if (expanded !== null && typeof expanded === 'object') {
511-
record[field] = expanded;
527+
grafts.push([field, expanded]);
512528
}
513529
}
530+
if (grafts.length) runContext.record = withGraftedRelations(record, grafts);
514531
}
515532
} catch (err) {
516533
// #6499 — the expander's thrown text (transitively the

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

Lines changed: 70 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,9 @@
1010
* the next run reading the original.
1111
* - **The trigger record.** `record` and `$record` start as the same record;
1212
* a `record.x` write is the run's own value, so `$record.x` and the
13-
* trigger's object keep what they were handed.
13+
* trigger's object keep what they were handed. The lookups a start node
14+
* declares are read by every attempt of a retried run and by a dry run,
15+
* and the caller's record, a class instance included, stays as handed.
1416
* - **A paused run.** With no durable store, the paused run is held in
1517
* memory; its resume works on its own copy, as a stored run's does, so
1618
* nothing it writes reaches a value the run was handed.
@@ -219,6 +221,73 @@ describe('the trigger record is the run\'s own copy', () => {
219221
expect(trigger).toEqual({ id: 'd1', account: 'a1' });
220222
});
221223

224+
it('a start node that declares expand, under the retry strategy: every attempt reads the expanded relation, and the caller\'s record object is unchanged', async () => {
225+
const engine = makeEngine();
226+
engine.setRecordExpander(async (_object, id) => ({ id, account: { id: 'a1', name: 'Acme' } }));
227+
// Fails on its first call and succeeds after; each call notes the
228+
// relation name its attempt reads.
229+
const seenByAttempt: unknown[] = [];
230+
engine.registerNodeExecutor({
231+
type: 'flaky',
232+
descriptor: defineActionDescriptor({ type: 'flaky', version: '1.0.0', name: 'flaky' }),
233+
async execute(_node: any, variables: Map<string, unknown>) {
234+
const account = (variables.get('record') as Record<string, any> | undefined)?.account;
235+
seenByAttempt.push(account && typeof account === 'object' ? account.name : account);
236+
return seenByAttempt.length === 1 ? { success: false, error: 'first attempt fails' } : { success: true };
237+
},
238+
} as never);
239+
const flow = chain('iso_expand_retry', [
240+
{ type: 'flaky' },
241+
assign({ seen: cel('record.account.name') }),
242+
], [{ name: 'seen', type: 'text', isOutput: true }]);
243+
flow.runAs = 'system';
244+
flow.nodes[0].config = { expand: ['account'] };
245+
flow.errorHandling = { strategy: 'retry', maxRetries: 2, backoffMs: 0 };
246+
engine.registerFlow('iso_expand_retry', flow);
247+
const trigger = { id: 'd1', account: 'a1' };
248+
const run = await engine.execute('iso_expand_retry', { object: 'deal', record: trigger } as any);
249+
expect(run.success, JSON.stringify(run)).toBe(true);
250+
expect(seenByAttempt).toEqual(['Acme', 'Acme']);
251+
expect((run.output as any).seen).toBe('Acme');
252+
expect(trigger).toEqual({ id: 'd1', account: 'a1' });
253+
});
254+
255+
it('a start node that declares expand, in a dry run: the run reads the expanded relation, and the caller\'s record object is unchanged', async () => {
256+
const engine = makeEngine();
257+
engine.setRecordExpander(async (_object, id) => ({ id, account: { id: 'a1', name: 'Acme' } }));
258+
const flow = chain('iso_expand_dry', [
259+
assign({ seen: cel('record.account.name') }),
260+
], [{ name: 'seen', type: 'text', isOutput: true }]);
261+
flow.nodes[0].config = { expand: ['account'] };
262+
const trigger = { id: 'd1', account: 'a1' };
263+
const result = await engine.dryRun(flow, { userId: 'usr_maker', object: 'deal', record: trigger });
264+
expect(result.status, JSON.stringify(result)).toBe('completed');
265+
expect(result.steps.find((s) => s.nodeId === 'n1')).toMatchObject({ kind: 'assignment', values: { seen: 'Acme' } });
266+
expect(trigger).toEqual({ id: 'd1', account: 'a1' });
267+
});
268+
269+
it('a start node that declares expand, with a record that is not a plain object: the run reads the expanded relation, and the caller\'s instance is unchanged', async () => {
270+
const engine = makeEngine();
271+
engine.setRecordExpander(async (_object, id) => ({ id, account: { id: 'a1', name: 'Acme' } }));
272+
const flow = chain('iso_expand_instance', [
273+
assign({ seen: cel('record.account.name') }),
274+
], [{ name: 'seen', type: 'text', isOutput: true }]);
275+
flow.runAs = 'system';
276+
flow.nodes[0].config = { expand: ['account'] };
277+
engine.registerFlow('iso_expand_instance', flow);
278+
class DealRow {
279+
id = 'd1';
280+
account: unknown = 'a1';
281+
}
282+
const trigger = new DealRow();
283+
const run = await engine.execute('iso_expand_instance', { object: 'deal', record: trigger } as any);
284+
expect(trigger).toBeInstanceOf(DealRow);
285+
expect(trigger.account).toBe('a1');
286+
expect({ ...trigger }).toEqual({ id: 'd1', account: 'a1' });
287+
expect(run.success, JSON.stringify(run)).toBe(true);
288+
expect((run.output as any).seen).toBe('Acme');
289+
});
290+
222291
it('a node that changes previous in place leaves the caller\'s previous object as handed', async () => {
223292
const engine = makeEngine();
224293
engine.registerFlow('iso_previous', chain('iso_previous', [

0 commit comments

Comments
 (0)