Skip to content

Commit 8f49499

Browse files
fix(approvals): a recall or subflow-parent strand reports the hook refusal that stranded the run (#34999)
Fixes #34638 Clause-②: yes Metadata-protocol: none ## 维护者速读 - 改了什么:审批「撤回」这扇门,以及子流程把父流程卡住的那条路,以前在成功响应里用 `resumeFailure` 报告「运行卡住了」,但不带原因。现在 `resumeFailure` 带上 `innerRefusal`(拒绝码与原文)和 `userMessage`(钩子声明的、按发起该运行的人的语言给出的那句话;无人发起的运行给出原文),与决策门抛出的 `RESUME_FAILED` 用同样的字段名和形状。 - 为什么改:同一种「被钩子拒绝而卡住」,从决策门进来能看到原因,从撤回门或子流程进来却看不到,审批人只知道卡住、不知道为什么。 - 风险与回滚:只新增两个可选字段(拒绝时才出现,故障时不出现),`code` / `repairable` 的读法不变;是对已发布类型 `ResumeFailureReport` 的放宽(`Clause-②: yes`),落地前欠一次契约审核。回滚即 revert。 - 先看:`packages/spec/src/contracts/approval-service.ts`(`ResumeFailureReport` 两个新字段与文档块)、`packages/plugins/plugin-approvals/src/approval-service.ts`(撤回门与子流程父流程的填充点)、`packages/services/service-automation/src/engine.ts`(`takeSubflowParentStrand` 带回拒绝)。 - 两分钟验证:`pnpm --filter @objectstack/plugin-approvals exec vitest run src/resume-failure-refusal.test.ts`,预期全部通过。 - 需要你做的:无,席位落地;落地前席位路由一次契约审核(L2)。 ## What changes 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` (#34579, PR #34619). 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. - `ResumeFailureReport` (`packages/spec/src/contracts/approval-service.ts`) gains two optional members, `innerRefusal` (`{ code, message }`, the engine's `AutomationResult.innerRefusal`) and `userMessage`. The names and shapes are the thrown `RESUME_FAILED`'s. `innerRefusal` is absent when the strand met no refusal; `userMessage` can ride alone. Both are read the way the thrown `RESUME_FAILED` reads them: an `innerRefusal` outside its declared shape and a blank or non-string `userMessage` are dropped. `userMessage` is in the run's locale (`AutomationContext.locale`, the starter's). `ResumeFailureDetailsSchema` is unchanged: on the resume door these members already ride the error envelope. - `packages/services/service-automation/src/engine.ts`: `takeSubflowParentStrand` returns the stranded parent's `innerRefusal` / `userMessage` beside `runId`, `repairable` and `error`, read from the parent's own result (`inner-refusal.ts` docblock kept true). - `packages/plugins/plugin-approvals/src/approval-service.ts`: the recall door's own strand, the batch resume's strand and the subflow-parent sites (now built by one helper) fill both members when the strand met a refusal. Both members are read once, through `recognisedRefusal` (the spec `FlowInnerRefusalSchema` plus `declaredUserMessage`), in `serviceResume` and `parentStrandReport` (L2 S2). - `scripts/engine-double-contract.pinned.json`: the gate-required ledger row for the new test's engine double. ## Tests - `packages/plugins/plugin-approvals/src/resume-failure-refusal.test.ts` (new): recall into a refusing hook, and the subflow-parent strand through `decide` and `recall`, each carry `innerRefusal` and the marked `userMessage`; a CONTROL strand that met no refusal carries neither (absent, not empty). - `packages/services/service-automation/src/resume-failure-refusal.test.ts` (new): the engine's subflow-parent strand carries the parent's refusal. - `packages/spec/src/contracts/resume-failure-report.pin.test.ts`: the type pin restated for the two optional members. - `resume-failure-refusal.test.ts` (L2 round): a plugin node's malformed pair (blank `userMessage`, unregistered code, non-string members) reaches recall's `resumeFailure` without those members, on the own strand and the parent strand; a well-formed pair rides whole (CONTROL). - `batch-item-recall-resumes-batch.test.ts`: a refused batch resume carries the pair (N3). ## Acceptance notes - Opened by the seat on the maintainer's order (「#34638、#34756 由席位代开 PR」): the cloud dev session `session_012MmDsNmJFXm6DALa3xPdkp` pushed this branch, and its own permission classifier refused its relay `pr_create`. This body is the seat's, written from the pushed commits and changeset. - The dev's open question, where the pair is declared, goes to the contract review: on `ResumeFailureReport` only (as pushed; the contracts interface), or on `ResumeFailureDetailsSchema` (the shared zod schema). The dev recommends the former, so nothing is declared that a channel does not fill. - Out of the claim's listed surface: `inner-refusal.ts` (a docblock in the same package) and `scripts/engine-double-contract.pinned.json` (written by the gate's `--write`). ## Verification L2 fix round, final head 8c0b7ce (origin/main merged, no conflict), under the shared verify lock: plugin-approvals 124/124 files, 1766/1766 tests; spec 855/855 files, 27365 passed + 1 todo; service-automation 289/289 files, 4184/4184 tests; all three typechecks exit 0. Ablations: the `serviceResume` read reverted, 3 red (the malformed shapes on the recall's own strand); the `parentStrandReport` read reverted, 3 red (the parent strand); the batch arm's spread removed, 1 red (N3); CONTROL green throughout, restore checked by hash. `dispatch-gates --commands`: 103 derived, 100 exit 0, 3 NOT MEASURED locally (need a full workspace build; green in CI). Overlap-check clean. CI on 8c0b7ce: 58 success, 11 skipped, 0 failed. Earlier round, superseded: Reported by the dev at 9b417c9 (origin/main e9f65a3 merged in): spec, service-automation and plugin-approvals typecheck exit 0; plugin-approvals 123 / 123 files, 1731 / 1731 tests; service-automation 288 / 288 files, 4134 / 4134 tests; spec 848 / 848 files; `dispatch-gates --commands` 103 derived, 103 run, all exit 0; overlap-check clean. Ablations: the recall spread removed (2 red), the pair removed from the parent-strand helper (4 red), the engine carry removed (the engine pin red, and after a rebuild the approvals pins 4 red); controls held. CI on this PR is the seat's to read. --- _Generated by [Claude Code](https://claude.ai/code/session_012MmDsS4GoHCgYwA2uv3n3C)_ <!-- signed: repo:objectstack#4 · os-lizheng · session_012MmDsS4GoHCgYwA2uv3n3C --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent e6e5224 commit 8f49499

10 files changed

Lines changed: 766 additions & 62 deletions

File tree

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
---
2+
'@objectstack/spec': patch
3+
'@objectstack/service-automation': patch
4+
'@objectstack/plugin-approvals': patch
5+
---
6+
7+
fix(approvals): a recall or subflow-parent strand reports the hook refusal that stranded the run
8+
9+
Clause-②: yes
10+
Metadata-protocol: none
11+
12+
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.
13+
14+
- `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.
15+
- `AutomationEngine.takeSubflowParentStrand` now returns the stranded parent's `innerRefusal` / `userMessage` beside `runId`, `repairable` and `error`, read from the parent's own result.
16+
- 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.
17+
18+
No migration: the change only adds optional members, and a caller that ignores them reads exactly what it read before.

‎packages/plugins/plugin-approvals/src/approval-service.ts‎

Lines changed: 85 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ import {
2525
type ObjectSchemaReadDelegate,
2626
type RecordOrganizationResolver,
2727
} from '@objectstack/metadata-core';
28-
import { isObjectAbsentError, keysetWalk, strandedDecisionFailure, type StrandedDecisionDetails } from '@objectstack/types';
28+
import { declaredUserMessage, isObjectAbsentError, keysetWalk, strandedDecisionFailure, type StrandedDecisionDetails } from '@objectstack/types';
2929
// [#15981 / #16166] Every built-in identity NAME is deliberately absent here:
3030
// both arms of `isOverrideActor` read an ADR-0095 capability rung, never a name.
3131
// `BUILTIN_IDENTITY_PLATFORM_ADMIN` went with the platform arm's name read and
@@ -61,6 +61,7 @@ import type {
6161
// what forced this file to cast its way out of its own contract to read
6262
// fields the caller had already supplied.
6363
import type { ExecutionContext } from '@objectstack/spec/kernel';
64+
import { FlowInnerRefusalSchema } from '@objectstack/spec/api';
6465
import { RESUME_AUTHORITY_SERVICE } from '@objectstack/spec/contracts';
6566
import type { IOwnershipQueueService } from '@objectstack/spec/contracts';
6667
import {
@@ -441,10 +442,17 @@ export interface ApprovalResumeSurface {
441442
* run a caller of `decide`/`resumeRecordedOutcome` was resuming. Optional:
442443
* an engine that predates this member simply never reports a bubbled
443444
* strand, exactly as before this card.
445+
*
446+
* [#34638] `innerRefusal` / `userMessage` are the refusal the PARENT's
447+
* downstream step met, when it met one — carried onto
448+
* {@link ResumeFailureReport} so the strand is told with its reason.
444449
*/
445-
takeSubflowParentStrand?(childRunId: string): { runId: string; repairable: boolean; error: string } | undefined;
450+
takeSubflowParentStrand?(childRunId: string): SubflowParentStrandReport | undefined;
446451
}
447452

453+
/** The subflow-parent strand {@link ApprovalResumeSurface.takeSubflowParentStrand} hands back. */
454+
type SubflowParentStrandReport = { runId: string; repairable: boolean; error: string } & ResumeRefusal;
455+
448456
/** A run parked at a `map` node on one item, as {@link ApprovalResumeSurface.suspendedMapParentOf} answers it. */
449457
type BatchParent = { runId: string; flowName: string; nodeId: string; correlation?: string };
450458

@@ -5987,7 +5995,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
59875995
private async serviceResume(
59885996
runId: string,
59895997
signal: { output?: Record<string, unknown>; branchLabel?: string; resumedBy?: string; impersonatedBy?: string },
5990-
): Promise<{ runId: string; repairable: boolean; error: string } | undefined> {
5998+
): Promise<SubflowParentStrandReport | undefined> {
59915999
const result = await this.automation!.resume!(runId, { ...signal, [RESUME_AUTHORITY_SERVICE]: true });
59926000
const reported = result as
59936001
| ({ success?: boolean; code?: string; error?: string; status?: string } & ResumeRefusal)
@@ -6005,14 +6013,13 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
60056013
// (`AutomationResult.innerRefusal` / `.userMessage`, ruling B′ on
60066014
// #24914) — kept beside the code and status instead of being dropped
60076015
// here, one line before the envelope is built, which is where #13807
6008-
// found `status` too. Copied as reported; the recogniser in
6009-
// `@objectstack/types` validates it before anything reaches the wire.
6010-
if (reported.innerRefusal !== undefined || reported.userMessage !== undefined) {
6011-
err.resumeRefusal = {
6012-
...(reported.innerRefusal !== undefined ? { innerRefusal: reported.innerRefusal } : {}),
6013-
...(reported.userMessage !== undefined ? { userMessage: reported.userMessage } : {}),
6014-
};
6015-
}
6016+
// found `status` too. [#34638] Read here, once, through
6017+
// {@link recognisedRefusal}: two channels read this value — the thrown
6018+
// envelope (whose recogniser in `@objectstack/types` reads it again)
6019+
// and the success channel's own strand reports (`recall`,
6020+
// `resumeBatchOfRecalledItem`), which have no recogniser after this line.
6021+
const refusal = ApprovalService.recognisedRefusal(reported);
6022+
if (refusal.innerRefusal !== undefined || refusal.userMessage !== undefined) err.resumeRefusal = refusal;
60166023
throw err;
60176024
}
60186025
return this.automation?.takeSubflowParentStrand?.(runId);
@@ -6046,12 +6053,61 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
60466053
* (#34579). A third sibling of {@link resumeCodeOf} and
60476054
* {@link resumeStatusOf}: `code` says why a resume was refused, `status`
60486055
* how the run ended, and this what the continuation's own data call was
6049-
* refused with. Only the stranded-decision envelope reads it.
6056+
* refused with. Read by the stranded-decision envelope and, on the success
6057+
* channel, by the recall door's own strand report (#34638).
60506058
*/
60516059
private static resumeRefusalOf(err: unknown): ResumeRefusal {
60526060
return (err as { resumeRefusal?: ResumeRefusal } | undefined)?.resumeRefusal ?? {};
60536061
}
60546062

6063+
/**
6064+
* [#34638] The refusal pair an engine result or a subflow-parent strand
6065+
* carries, read the way the thrown `RESUME_FAILED` reads it
6066+
* (`strandedDecisionDetails`, `@objectstack/types`), so the two approvals
6067+
* channels answer one engine result the same way. The engine relays what
6068+
* a node executor returned unchecked, and node types are open to plugins:
6069+
*
6070+
* - `innerRefusal` is kept only in its declared shape, read by the spec's
6071+
* own `FlowInnerRefusalSchema` — a `code` in the closed ADR-0112 set and
6072+
* a string `message`; anything else is dropped, never relayed;
6073+
* - `userMessage` is kept only as `declaredUserMessage` reads a marking —
6074+
* a blank or non-string value is no marking.
6075+
*
6076+
* A member that fails its read is dropped and the strand is still told.
6077+
* Applied where the pair is built for the success channel:
6078+
* {@link serviceResume} (a rejected resume) and {@link parentStrandReport}.
6079+
*/
6080+
private static recognisedRefusal(source: { innerRefusal?: unknown; userMessage?: unknown }): ResumeRefusal {
6081+
const innerRefusal = source.innerRefusal === undefined
6082+
? undefined
6083+
: FlowInnerRefusalSchema.safeParse(source.innerRefusal);
6084+
const userMessage = declaredUserMessage(source);
6085+
return {
6086+
...(innerRefusal?.success ? { innerRefusal: innerRefusal.data } : {}),
6087+
...(userMessage !== undefined ? { userMessage } : {}),
6088+
};
6089+
}
6090+
6091+
/**
6092+
* [#34638] The {@link ResumeFailureReport} for a subflow PARENT that
6093+
* stranded behind a resume this door issued — built in ONE place for the
6094+
* three doors that read such a strand (`resumeRecordedOutcome`, `recall`,
6095+
* `resumeBatchOfRecalledItem`), so they cannot drift on what the report
6096+
* carries: the parent's `runId` and `repairable`, and the refusal the
6097+
* parent's downstream step met when it met one (`{}` otherwise, so a
6098+
* fault-stranded parent reports neither member), read through
6099+
* {@link recognisedRefusal}.
6100+
*/
6101+
private static parentStrandReport(strand: SubflowParentStrandReport): ResumeFailureReport {
6102+
return {
6103+
code: 'RESUME_FAILED',
6104+
runId: strand.runId,
6105+
status: 'stranded',
6106+
repairable: strand.repairable,
6107+
...ApprovalService.recognisedRefusal(strand),
6108+
};
6109+
}
6110+
60556111
/**
60566112
* A decision or a comment attaches only files its caller uploaded.
60576113
*
@@ -6306,12 +6362,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
63066362
`RESUME_FAILED: ${what} was recorded on request ${requestId} and its own flow run '${runId}' ` +
63076363
`resumed, but the subflow parent above it — run '${bubbleStrand.runId}' — consumed its ` +
63086364
`suspension and is now stranded: ${bubbleStrand.error}`,
6309-
resumeFailure: {
6310-
code: 'RESUME_FAILED',
6311-
runId: bubbleStrand.runId,
6312-
status: 'stranded',
6313-
repairable: bubbleStrand.repairable,
6314-
},
6365+
resumeFailure: ApprovalService.parentStrandReport(bubbleStrand),
63156366
};
63166367
}
63176368
return { resumed: true };
@@ -6732,12 +6783,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
67326783
`RESUME_FAILED: the recall was recorded on request ${requestId} and its own flow run ` +
67336784
`'${runId}' resumed, but the subflow parent above it — run '${bubbleStrand.runId}' — ` +
67346785
`consumed its suspension and is now stranded: ${bubbleStrand.error}`;
6735-
resumeFailure = {
6736-
code: 'RESUME_FAILED',
6737-
runId: bubbleStrand.runId,
6738-
status: 'stranded',
6739-
repairable: bubbleStrand.repairable,
6740-
};
6786+
resumeFailure = ApprovalService.parentStrandReport(bubbleStrand);
67416787
}
67426788
} catch (err: any) {
67436789
resumeError = err?.message ?? String(err);
@@ -6765,7 +6811,14 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
67656811
// legitimate by the member's own docblock ("An absent member means
67666812
// no report was made, never that no run is stranded") and is what
67676813
// `resumeRecordedOutcome` answers on those same exits.
6768-
resumeFailure = { code: 'RESUME_FAILED', runId, status: 'stranded', repairable: true };
6814+
//
6815+
// [#34638] …and it tells the refusal the continuation met, when
6816+
// it met one — the pair the decision doors' thrown envelope
6817+
// carries since #34579, under the same names; `{}` for a fault.
6818+
resumeFailure = {
6819+
code: 'RESUME_FAILED', runId, status: 'stranded', repairable: true,
6820+
...ApprovalService.resumeRefusalOf(err),
6821+
};
67696822
await this.journalStrandedContinuation(requestId, {
67706823
branchLabel: APPROVAL_BRANCH_LABELS.reject,
67716824
output: { decision: 'recall', requestId },
@@ -6859,7 +6912,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
68596912
`RESUME_FAILED: the recall was recorded on request ${requestId} and cancelled its run '${itemRunId}', ` +
68606913
`and the batch run '${batchRunId}' above it resumed, but the subflow parent above that — run ` +
68616914
`'${bubbleStrand.runId}' — consumed its suspension and is now stranded: ${bubbleStrand.error}`,
6862-
resumeFailure: { code: 'RESUME_FAILED', runId: bubbleStrand.runId, status: 'stranded', repairable: bubbleStrand.repairable },
6915+
resumeFailure: ApprovalService.parentStrandReport(bubbleStrand),
68636916
};
68646917
} catch (err: any) {
68656918
const message = err?.message ?? String(err);
@@ -6871,7 +6924,12 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
68716924
resumeError: `the recall was recorded on request ${requestId} and cancelled its run '${itemRunId}', but ${at} failed: ${message}`,
68726925
// Only the engine's own stranded exit is told in fields, as in `recall`.
68736926
...(batchRunId && ApprovalService.resumeStatusOf(err) === 'stranded'
6874-
? { resumeFailure: { code: 'RESUME_FAILED' as const, runId: batchRunId, status: 'stranded' as const, repairable: true } }
6927+
? {
6928+
resumeFailure: {
6929+
code: 'RESUME_FAILED' as const, runId: batchRunId, status: 'stranded' as const, repairable: true,
6930+
...ApprovalService.resumeRefusalOf(err),
6931+
},
6932+
}
68756933
: {}),
68766934
};
68776935
}

‎packages/plugins/plugin-approvals/src/batch-item-recall-resumes-batch.test.ts‎

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ function wireReplica(
173173
fake: ReturnType<typeof makeFakeEngine>,
174174
store: InMemorySuspendedRunStore | ObjectStoreSuspendedRunStore,
175175
clock: { now: () => Date },
176-
onPeek: (seen: { results: unknown; count: unknown }) => void,
176+
onPeek: (seen: { results: unknown; count: unknown }) => void | Record<string, unknown>,
177177
) {
178178
const service = new ApprovalService({ engine: fake as any, logger: silentLogger(), clock });
179179
const automation = new AutomationEngine(silentLogger(), store);
@@ -189,8 +189,8 @@ function wireReplica(
189189
automation.registerNodeExecutor({
190190
type: 'peek',
191191
async execute(_node: any, variables: Map<string, unknown>) {
192-
onPeek({ results: variables.get('signoffResults'), count: variables.get('signoffs.count') });
193-
return { success: true };
192+
// A peek may answer a failure of its own (#34638's refused batch resume).
193+
return onPeek({ results: variables.get('signoffResults'), count: variables.get('signoffs.count') }) ?? { success: true };
194194
},
195195
} as never);
196196
automation.registerFlow('task_signoff', TASK_SIGNOFF as never);
@@ -505,3 +505,26 @@ describe('a revise-window recall finds its batch past the first page of parked r
505505
expect(await storedRun(fan.runId!)).toMatchObject({ node_id: 'fan', correlation: `map:${req.flow_run_id}`, status: 'paused' });
506506
});
507507
});
508+
509+
describe('#34638 — a refused batch resume after a revise-window recall tells the refusal on resumeFailure', () => {
510+
it('the batch strands on its next step\'s refusal: resumeFailure names the batch run and carries the pair', async () => {
511+
const fake = makeFakeEngine();
512+
const refusal = { innerRefusal: { code: 'VALIDATION_FAILED', message: 'over capacity' }, userMessage: 'Capacity is already taken.' };
513+
const { automation, service } = wireReplica(fake, new InMemorySuspendedRunStore(), tickingClock(),
514+
() => ({ success: false, error: 'peek refused', ...refusal }));
515+
const paused = await automation.execute('release_signoff', {
516+
userId: 'submitter', params: { items: [{ id: 't1', title: 'Task t1' }] },
517+
} as never);
518+
const batchRunId = paused.runId!;
519+
const item = (await fake.find('sys_approval_request', { where: { record_id: 't1', status: 'pending' } }))[0];
520+
await service.sendBack(item.id, { actorId: 'u1' }, asUser('u1'));
521+
522+
const out = await service.recall(item.id, { actorId: 'submitter' }, asUser('submitter'));
523+
524+
expect(out.request.status).toBe('recalled');
525+
expect(out.resumeError, 'the batch resume is the failure told').toContain(`resuming the batch run '${batchRunId}'`);
526+
expect(out.resumeFailure).toEqual({
527+
code: 'RESUME_FAILED', runId: batchRunId, status: 'stranded', repairable: true, ...refusal,
528+
});
529+
});
530+
});

0 commit comments

Comments
 (0)