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
18 changes: 18 additions & 0 deletions .changeset/34638-resume-failure-refusal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
'@objectstack/spec': patch
'@objectstack/service-automation': patch
'@objectstack/plugin-approvals': patch
---

fix(approvals): a recall or subflow-parent strand reports the hook refusal that stranded the run

Clause-②: yes
Metadata-protocol: none

When an approval decision strands its flow run because the next step was refused (a record hook's declared refusal, a validation rule, a permission), the thrown `RESUME_FAILED` already carries `innerRefusal` and the refusal's marked `userMessage`. Two doors report a stranded run on a success answer instead, through `resumeFailure`: the recall door, whose own resume stranded, and a subflow parent that stranded after the run this door resumed advanced (through `decide` and through `recall`). Those reports carried `code`, `runId`, `status` and `repairable` only, so the approver saw a stranded run with no reason.

- `ResumeFailureReport` (`@objectstack/spec/contracts`) gains two optional members, `innerRefusal` (`{ code, message }`, the engine's `AutomationResult.innerRefusal`) and `userMessage` (the declared sentence in the language of whoever started the run, since a resumed leg keeps the starter's locale; the authored message when no person started the run). The names and shapes are the ones the thrown `RESUME_FAILED` uses. `innerRefusal` is absent when the strand met no refusal (a fault), and `userMessage` is absent unless the failure carried a marked end-user text, so it can ride alone; neither changes how `code` and `repairable` are read. `ResumeFailureDetailsSchema` is unchanged. On the resume door these members already ride the error envelope.
- `AutomationEngine.takeSubflowParentStrand` now returns the stranded parent's `innerRefusal` / `userMessage` beside `runId`, `repairable` and `error`, read from the parent's own result.
- The approvals recall door and the subflow-parent strand fill both members whenever the strand met a refusal, read the way the thrown `RESUME_FAILED` reads them: an `innerRefusal` whose `code` is outside the registered error codes or whose `message` is not a string, and a blank or non-string `userMessage`, are dropped, so a node that returns a malformed pair answers the same on the success channel as on the thrown one.

No migration: the change only adds optional members, and a caller that ignores them reads exactly what it read before.
112 changes: 85 additions & 27 deletions packages/plugins/plugin-approvals/src/approval-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import {
type ObjectSchemaReadDelegate,
type RecordOrganizationResolver,
} from '@objectstack/metadata-core';
import { isObjectAbsentError, keysetWalk, strandedDecisionFailure, type StrandedDecisionDetails } from '@objectstack/types';
import { declaredUserMessage, isObjectAbsentError, keysetWalk, strandedDecisionFailure, type StrandedDecisionDetails } from '@objectstack/types';
// [#15981 / #16166] Every built-in identity NAME is deliberately absent here:
// both arms of `isOverrideActor` read an ADR-0095 capability rung, never a name.
// `BUILTIN_IDENTITY_PLATFORM_ADMIN` went with the platform arm's name read and
Expand Down Expand Up @@ -61,6 +61,7 @@ import type {
// what forced this file to cast its way out of its own contract to read
// fields the caller had already supplied.
import type { ExecutionContext } from '@objectstack/spec/kernel';
import { FlowInnerRefusalSchema } from '@objectstack/spec/api';
import { RESUME_AUTHORITY_SERVICE } from '@objectstack/spec/contracts';
import type { IOwnershipQueueService } from '@objectstack/spec/contracts';
import {
Expand Down Expand Up @@ -441,10 +442,17 @@ export interface ApprovalResumeSurface {
* run a caller of `decide`/`resumeRecordedOutcome` was resuming. Optional:
* an engine that predates this member simply never reports a bubbled
* strand, exactly as before this card.
*
* [#34638] `innerRefusal` / `userMessage` are the refusal the PARENT's
* downstream step met, when it met one — carried onto
* {@link ResumeFailureReport} so the strand is told with its reason.
*/
takeSubflowParentStrand?(childRunId: string): { runId: string; repairable: boolean; error: string } | undefined;
takeSubflowParentStrand?(childRunId: string): SubflowParentStrandReport | undefined;
}

/** The subflow-parent strand {@link ApprovalResumeSurface.takeSubflowParentStrand} hands back. */
type SubflowParentStrandReport = { runId: string; repairable: boolean; error: string } & ResumeRefusal;

/** A run parked at a `map` node on one item, as {@link ApprovalResumeSurface.suspendedMapParentOf} answers it. */
type BatchParent = { runId: string; flowName: string; nodeId: string; correlation?: string };

Expand Down Expand Up @@ -5987,7 +5995,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
private async serviceResume(
runId: string,
signal: { output?: Record<string, unknown>; branchLabel?: string; resumedBy?: string; impersonatedBy?: string },
): Promise<{ runId: string; repairable: boolean; error: string } | undefined> {
): Promise<SubflowParentStrandReport | undefined> {
const result = await this.automation!.resume!(runId, { ...signal, [RESUME_AUTHORITY_SERVICE]: true });
const reported = result as
| ({ success?: boolean; code?: string; error?: string; status?: string } & ResumeRefusal)
Expand All @@ -6005,14 +6013,13 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
// (`AutomationResult.innerRefusal` / `.userMessage`, ruling B′ on
// #24914) — kept beside the code and status instead of being dropped
// here, one line before the envelope is built, which is where #13807
// found `status` too. Copied as reported; the recogniser in
// `@objectstack/types` validates it before anything reaches the wire.
if (reported.innerRefusal !== undefined || reported.userMessage !== undefined) {
err.resumeRefusal = {
...(reported.innerRefusal !== undefined ? { innerRefusal: reported.innerRefusal } : {}),
...(reported.userMessage !== undefined ? { userMessage: reported.userMessage } : {}),
};
}
// found `status` too. [#34638] Read here, once, through
// {@link recognisedRefusal}: two channels read this value — the thrown
// envelope (whose recogniser in `@objectstack/types` reads it again)
// and the success channel's own strand reports (`recall`,
// `resumeBatchOfRecalledItem`), which have no recogniser after this line.
const refusal = ApprovalService.recognisedRefusal(reported);
if (refusal.innerRefusal !== undefined || refusal.userMessage !== undefined) err.resumeRefusal = refusal;
throw err;
}
return this.automation?.takeSubflowParentStrand?.(runId);
Expand Down Expand Up @@ -6046,12 +6053,61 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
* (#34579). A third sibling of {@link resumeCodeOf} and
* {@link resumeStatusOf}: `code` says why a resume was refused, `status`
* how the run ended, and this what the continuation's own data call was
* refused with. Only the stranded-decision envelope reads it.
* refused with. Read by the stranded-decision envelope and, on the success
* channel, by the recall door's own strand report (#34638).
*/
private static resumeRefusalOf(err: unknown): ResumeRefusal {
return (err as { resumeRefusal?: ResumeRefusal } | undefined)?.resumeRefusal ?? {};
}

/**
* [#34638] The refusal pair an engine result or a subflow-parent strand
* carries, read the way the thrown `RESUME_FAILED` reads it
* (`strandedDecisionDetails`, `@objectstack/types`), so the two approvals
* channels answer one engine result the same way. The engine relays what
* a node executor returned unchecked, and node types are open to plugins:
*
* - `innerRefusal` is kept only in its declared shape, read by the spec's
* own `FlowInnerRefusalSchema` — a `code` in the closed ADR-0112 set and
* a string `message`; anything else is dropped, never relayed;
* - `userMessage` is kept only as `declaredUserMessage` reads a marking —
* a blank or non-string value is no marking.
*
* A member that fails its read is dropped and the strand is still told.
* Applied where the pair is built for the success channel:
* {@link serviceResume} (a rejected resume) and {@link parentStrandReport}.
*/
private static recognisedRefusal(source: { innerRefusal?: unknown; userMessage?: unknown }): ResumeRefusal {
const innerRefusal = source.innerRefusal === undefined
? undefined
: FlowInnerRefusalSchema.safeParse(source.innerRefusal);
const userMessage = declaredUserMessage(source);
return {
...(innerRefusal?.success ? { innerRefusal: innerRefusal.data } : {}),
...(userMessage !== undefined ? { userMessage } : {}),
};
}

/**
* [#34638] The {@link ResumeFailureReport} for a subflow PARENT that
* stranded behind a resume this door issued — built in ONE place for the
* three doors that read such a strand (`resumeRecordedOutcome`, `recall`,
* `resumeBatchOfRecalledItem`), so they cannot drift on what the report
* carries: the parent's `runId` and `repairable`, and the refusal the
* parent's downstream step met when it met one (`{}` otherwise, so a
* fault-stranded parent reports neither member), read through
* {@link recognisedRefusal}.
*/
private static parentStrandReport(strand: SubflowParentStrandReport): ResumeFailureReport {
return {
code: 'RESUME_FAILED',
runId: strand.runId,
status: 'stranded',
repairable: strand.repairable,
...ApprovalService.recognisedRefusal(strand),
};
}

/**
* A decision or a comment attaches only files its caller uploaded.
*
Expand Down Expand Up @@ -6306,12 +6362,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
`RESUME_FAILED: ${what} was recorded on request ${requestId} and its own flow run '${runId}' ` +
`resumed, but the subflow parent above it — run '${bubbleStrand.runId}' — consumed its ` +
`suspension and is now stranded: ${bubbleStrand.error}`,
resumeFailure: {
code: 'RESUME_FAILED',
runId: bubbleStrand.runId,
status: 'stranded',
repairable: bubbleStrand.repairable,
},
resumeFailure: ApprovalService.parentStrandReport(bubbleStrand),
};
}
return { resumed: true };
Expand Down Expand Up @@ -6732,12 +6783,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
`RESUME_FAILED: the recall was recorded on request ${requestId} and its own flow run ` +
`'${runId}' resumed, but the subflow parent above it — run '${bubbleStrand.runId}' — ` +
`consumed its suspension and is now stranded: ${bubbleStrand.error}`;
resumeFailure = {
code: 'RESUME_FAILED',
runId: bubbleStrand.runId,
status: 'stranded',
repairable: bubbleStrand.repairable,
};
resumeFailure = ApprovalService.parentStrandReport(bubbleStrand);
}
} catch (err: any) {
resumeError = err?.message ?? String(err);
Expand Down Expand Up @@ -6765,7 +6811,14 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
// legitimate by the member's own docblock ("An absent member means
// no report was made, never that no run is stranded") and is what
// `resumeRecordedOutcome` answers on those same exits.
resumeFailure = { code: 'RESUME_FAILED', runId, status: 'stranded', repairable: true };
//
// [#34638] …and it tells the refusal the continuation met, when
// it met one — the pair the decision doors' thrown envelope
// carries since #34579, under the same names; `{}` for a fault.
resumeFailure = {
code: 'RESUME_FAILED', runId, status: 'stranded', repairable: true,
...ApprovalService.resumeRefusalOf(err),
};
await this.journalStrandedContinuation(requestId, {
branchLabel: APPROVAL_BRANCH_LABELS.reject,
output: { decision: 'recall', requestId },
Expand Down Expand Up @@ -6859,7 +6912,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
`RESUME_FAILED: the recall was recorded on request ${requestId} and cancelled its run '${itemRunId}', ` +
`and the batch run '${batchRunId}' above it resumed, but the subflow parent above that — run ` +
`'${bubbleStrand.runId}' — consumed its suspension and is now stranded: ${bubbleStrand.error}`,
resumeFailure: { code: 'RESUME_FAILED', runId: bubbleStrand.runId, status: 'stranded', repairable: bubbleStrand.repairable },
resumeFailure: ApprovalService.parentStrandReport(bubbleStrand),
};
} catch (err: any) {
const message = err?.message ?? String(err);
Expand All @@ -6871,7 +6924,12 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
resumeError: `the recall was recorded on request ${requestId} and cancelled its run '${itemRunId}', but ${at} failed: ${message}`,
// Only the engine's own stranded exit is told in fields, as in `recall`.
...(batchRunId && ApprovalService.resumeStatusOf(err) === 'stranded'
? { resumeFailure: { code: 'RESUME_FAILED' as const, runId: batchRunId, status: 'stranded' as const, repairable: true } }
? {
resumeFailure: {
code: 'RESUME_FAILED' as const, runId: batchRunId, status: 'stranded' as const, repairable: true,
...ApprovalService.resumeRefusalOf(err),
},
}
: {}),
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ function wireReplica(
fake: ReturnType<typeof makeFakeEngine>,
store: InMemorySuspendedRunStore | ObjectStoreSuspendedRunStore,
clock: { now: () => Date },
onPeek: (seen: { results: unknown; count: unknown }) => void,
onPeek: (seen: { results: unknown; count: unknown }) => void | Record<string, unknown>,
) {
const service = new ApprovalService({ engine: fake as any, logger: silentLogger(), clock });
const automation = new AutomationEngine(silentLogger(), store);
Expand All @@ -189,8 +189,8 @@ function wireReplica(
automation.registerNodeExecutor({
type: 'peek',
async execute(_node: any, variables: Map<string, unknown>) {
onPeek({ results: variables.get('signoffResults'), count: variables.get('signoffs.count') });
return { success: true };
// A peek may answer a failure of its own (#34638's refused batch resume).
return onPeek({ results: variables.get('signoffResults'), count: variables.get('signoffs.count') }) ?? { success: true };
},
} as never);
automation.registerFlow('task_signoff', TASK_SIGNOFF as never);
Expand Down Expand Up @@ -505,3 +505,26 @@ describe('a revise-window recall finds its batch past the first page of parked r
expect(await storedRun(fan.runId!)).toMatchObject({ node_id: 'fan', correlation: `map:${req.flow_run_id}`, status: 'paused' });
});
});

describe('#34638 — a refused batch resume after a revise-window recall tells the refusal on resumeFailure', () => {
it('the batch strands on its next step\'s refusal: resumeFailure names the batch run and carries the pair', async () => {
const fake = makeFakeEngine();
const refusal = { innerRefusal: { code: 'VALIDATION_FAILED', message: 'over capacity' }, userMessage: 'Capacity is already taken.' };
const { automation, service } = wireReplica(fake, new InMemorySuspendedRunStore(), tickingClock(),
() => ({ success: false, error: 'peek refused', ...refusal }));
const paused = await automation.execute('release_signoff', {
userId: 'submitter', params: { items: [{ id: 't1', title: 'Task t1' }] },
} as never);
const batchRunId = paused.runId!;
const item = (await fake.find('sys_approval_request', { where: { record_id: 't1', status: 'pending' } }))[0];
await service.sendBack(item.id, { actorId: 'u1' }, asUser('u1'));

const out = await service.recall(item.id, { actorId: 'submitter' }, asUser('submitter'));

expect(out.request.status).toBe('recalled');
expect(out.resumeError, 'the batch resume is the failure told').toContain(`resuming the batch run '${batchRunId}'`);
expect(out.resumeFailure).toEqual({
code: 'RESUME_FAILED', runId: batchRunId, status: 'stranded', repairable: true, ...refusal,
});
});
});
Loading
Loading