Skip to content
Merged
10 changes: 10 additions & 0 deletions .changeset/29333-region-refusal-deeper-chain-cancel.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@objectstack/service-automation': patch
---

fix(service-automation): the region refusal names the deeper suspended run it could not read instead of leaving it parked in silence

Clause-②: no
Metadata-protocol: none

When a `subflow` or `map` call inside a `loop` body, a `parallel` branch or a `try_catch` slot starts a child flow that suspends, the run fails at the region boundary and cancels the child run with every run it is parked on. That walk read each link through a best-effort read, so a link deeper in the chain that the suspended-run store could not read stopped the walk with only a `warn`: that run, and every run below it, stayed parked. The walk now reads through the strict loader that `cancelRun` uses. It cancels every link it read, still cancels the link it could not read through `cancelRun` (which records its own `error` if the store is still unreadable), and logs one `error` naming that run, because any run below it was never reached and may still be parked. The refusal itself, its text and its un-routability are unchanged.
44 changes: 30 additions & 14 deletions packages/services/service-automation/src/dag-traversal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ export interface DagTraversalHost {
readonly persistSuspendedRun: AutomationEngine['persistSuspendedRun'];
readonly flowChecksumOf: AutomationEngine['flowChecksumOf'];
readonly renderFlowTerminalMessage: AutomationEngine['renderFlowTerminalMessage'];
readonly resolveSuspensionChain: AutomationEngine['resolveSuspensionChain'];
readonly resolveSuspensionChainForCancel: AutomationEngine['resolveSuspensionChainForCancel'];
readonly cancelRun: AutomationEngine['cancelRun'];
}

Expand Down Expand Up @@ -751,7 +751,7 @@ export async function traverseNext(

/** The body of {@link AutomationEngine.runRegion}; that method's docblock is its contract. */
export async function runRegion(
this: Pick<DagTraversalHost, 'executeNode' | 'resolveSuspensionChain' | 'cancelRun' | 'logger'>,
this: Pick<DagTraversalHost, 'executeNode' | 'resolveSuspensionChainForCancel' | 'cancelRun' | 'logger'>,
region: FlowRegionParsed,
variables: Map<string, unknown>,
context: AutomationContext,
Expand Down Expand Up @@ -858,19 +858,35 @@ export async function runRegion(
const childRunId = nestedChildRunId(err.correlation);
if (childRunId !== undefined) {
try {
const chain = await this.resolveSuspensionChain(childRunId);
// [#29333] The chain is read through the STRICT loader,
// the read `cancelRun` itself takes. The degrading one
// answered an unreadable link as "nothing suspended", so
// the walk stopped there and every run below that link
// stayed parked with only a `warn` said (#29166 covered
// the case where the unreadable link is the child itself).
const { chain, unreadable } = await this.resolveSuspensionChainForCancel(childRunId);
const reason = `the run that started it failed at a region boundary: ${refusal.message}`;
if (chain.length === 0) {
// [#29166] The chain is read through the DEGRADING
// loader, so a store it cannot read reads as "nothing
// suspended" and walking it cancelled nothing, with
// only that loader's `warn` said, while the child run
// stayed parked. The child id is known here, so it is
// cancelled once anyway: `cancelRun` reads through the
// STRICT loader and owns the `error` record when the
// store is still unreadable, and it is a no-op when
// there really is no suspension under that id.
await this.cancelRun(childRunId, reason);
if (unreadable) {
// The deepest link the walk knows of. Its id is known
// (the link above names it, or it is the child), so it
// is cancelled anyway, deepest first: `cancelRun`
// reads it again and owns the `error` record for THAT
// run when the store still cannot be read, and it is a
// no-op when the run is in fact gone.
await this.cancelRun(unreadable.runId, reason);
// What `cancelRun` cannot say: the walk never read
// this link, so a run it is itself parked on was never
// reached and may still be parked. #4632 verdict:
// DURABILITY, `error`.
this.logger.error(
`[automation] node '${err.nodeId}' suspended inside region '${refusal.regionNodeId}', and ` +
`the suspended run '${unreadable.runId}' in the chain of the child run '${childRunId}' could not be ` +
`read while cancelling that chain, so any run '${unreadable.runId}' is itself parked on ` +
`was not reached and may still be parked. Once the suspended-run store answers, cancel ` +
`each with cancelRun(runId). The read failure is in this record's meta.`,
undefined,
describeThrownForLog(unreadable.cause),
);
}
for (const run of [...chain].reverse()) await this.cancelRun(run.runId, reason);
} catch (cancelErr) {
Expand Down
47 changes: 43 additions & 4 deletions packages/services/service-automation/src/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7045,10 +7045,49 @@ export class AutomationEngine implements IAutomationService {
* walk starts, so a corrupt correlation cycle back to it ends the chain
* there instead of listing the caller's run again as its own child.
*/
private async resolveSuspensionChain(runId: string): Promise<SuspendedRun[]> {
private resolveSuspensionChain(runId: string): Promise<SuspendedRun[]> {
return this.walkSuspensionChain(runId, (id) => this.loadSuspendedRun(id));
}

/**
* [#29333] {@link resolveSuspensionChain} for a caller that is about to
* CANCEL the chain, read through the STRICT loader
* ({@link loadSuspendedRunStrict}, the read {@link cancelRun} itself takes).
*
* The degrading walk answers a link it cannot read as "nothing suspended
* there" and stops, which is right for the incidental readers (the resume
* gate) and wrong for a cancel: the runs below that link are left parked
* and nothing at `error` says so. This walk stops at the same place but
* says WHY: `unreadable` names the link whose read threw, with the cause,
* so the caller can still cancel what it read and record the rest. A link
* that is simply not found ends the chain as it does in the degrading walk.
*
* Same walk, same bounds: only the loader differs.
*/
private async resolveSuspensionChainForCancel(
runId: string,
): Promise<{ chain: SuspendedRun[]; unreadable?: { runId: string; cause: unknown } }> {
let unreadable: { runId: string; cause: unknown } | undefined;
const chain = await this.walkSuspensionChain(runId, async (id) => {
try {
return await this.loadSuspendedRunStrict(id);
} catch (cause) {
unreadable = { runId: id, cause };
return null;
}
});
return unreadable ? { chain, unreadable } : { chain };
}

/** The one chain walk behind {@link resolveSuspensionChain} and
* {@link resolveSuspensionChainForCancel}; `load` answers `null` to stop. */
private async walkSuspensionChain(
runId: string,
load: (runId: string) => Promise<SuspendedRun | null>,
): Promise<SuspendedRun[]> {
const seen = new Set<string>([runId]);
const chain: SuspendedRun[] = [];
let run = await this.loadSuspendedRun(runId);
let run = await load(runId);
for (let depth = 0; run && depth < AutomationEngine.MAX_SUSPENSION_CHAIN_DEPTH; depth++) {
chain.push(run);
const correlation = run.correlation;
Expand All @@ -7059,7 +7098,7 @@ export class AutomationEngine implements IAutomationService {
const childRunId = correlation!.slice(prefix.length);
if (!childRunId || seen.has(childRunId)) return chain;
seen.add(childRunId);
run = await this.loadSuspendedRun(childRunId);
run = await load(childRunId);
}
// The depth bound stopped the walk on a run it loaded but never read.
if (run) chain.push(run);
Expand Down Expand Up @@ -9357,7 +9396,7 @@ export class AutomationEngine implements IAutomationService {
// The body lives in ./dag-traversal.ts (#25222).
const host: ThisParameterType<typeof runRegion> = {
executeNode: (...a) => this.executeNode(...a),
resolveSuspensionChain: (...a) => this.resolveSuspensionChain(...a),
resolveSuspensionChainForCancel: (...a) => this.resolveSuspensionChainForCancel(...a),
cancelRun: (...a) => this.cancelRun(...a),
logger: this.logger,
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -361,3 +361,64 @@ describe('the region refusal still cancels the child run when its suspension cha
expect(runs.map((r: any) => r.status)).toEqual(['cancelled']);
});
});

describe('the region refusal cancels what it can read of a deeper suspension chain and names the link it cannot (#29333)', () => {
/** caller --loop--> deal_review --subflow--> deal_mid --subflow--> deal_ask (parks at `wait`). */
function threeRunRig(store: InMemorySuspendedRunStore) {
const r = rig();
r.engine.setSuspendedRunStore(store);
r.engine.registerFlow('deal_ask', pausingChild('deal_ask'));
r.engine.registerFlow('deal_mid', chain('deal_mid', [start(false), call('deal_ask', 'subflow', 'ask'), END]));
r.engine.registerFlow('deal_review', chain('deal_review', [start(false), call('deal_mid', 'subflow', 'mid'), END]));
r.engine.registerFlow('deal_submit', regionCaller('deal_submit', 'deal_review', 'loop', 'subflow', false));
const cancel = vi.spyOn(r.engine, 'cancelRun');
return { ...r, cancel };
}

const chainErrors = (logger: any): string[] =>
logger.error.mock.calls
.map((c: unknown[]) => String(c[0]))
.filter((m: string) => m.includes('could not be read while cancelling that chain'));

it('the middle link cannot be read: the child is cancelled, one `error` record names the middle run, and the refusal is still thrown', async () => {
const store = new ChildLoadFailingStore('deal_mid', 'always');
const { engine, logger, cancel } = threeRunRig(store);

const result: any = await engine.execute('deal_submit', {} as any);
// The refusal itself is unchanged.
expect(result.success).toBe(false);
expect(String(result.error)).toContain(
`durable pause inside a structured region: node 'step' (sub-flow 'deal_review') suspended`,
);

expect((await engine.listRuns('deal_review')).map((r: any) => r.status), 'the readable link is cancelled').toEqual(['cancelled']);
const parked = await store.list();
// deal_mid cannot be read, and deal_ask is only reachable through deal_mid's row.
expect(parked.map((r) => r.flowName).sort()).toEqual(['deal_ask', 'deal_mid']);
const midRunId = parked.find((r) => r.flowName === 'deal_mid')!.runId;

const errors = chainErrors(logger);
expect(errors, 'one record names the unreadable link').toHaveLength(1);
expect(errors[0]).toContain(`the suspended run '${midRunId}'`);

// Deepest first: the unreadable link, then the child.
const childRunId = (await engine.listRuns('deal_review'))[0].id;
expect(cancel.mock.calls.map((c) => c[0])).toEqual([midRunId, childRunId]);
});

it('CONTROL: an all-readable three-run chain is cancelled whole, deepest first, with nothing at `error`', async () => {
const { engine, logger, cancel } = threeRunRig(new InMemorySuspendedRunStore());

const result: any = await engine.execute('deal_submit', {} as any);
expect(result.success).toBe(false);
expect(await engine.listSuspendedRunsDurable(), 'no run is left parked').toEqual([]);
const ids: string[] = [];
for (const name of ['deal_ask', 'deal_mid', 'deal_review']) {
const runs = await engine.listRuns(name);
expect(runs.map((r: any) => r.status), name).toEqual(['cancelled']);
ids.push(runs[0].id);
}
expect(cancel.mock.calls.map((c) => c[0])).toEqual(ids);
expect(logger.error).not.toHaveBeenCalled();
});
});
Loading