diff --git a/.changeset/38876-branch-suspending-subflow-arming.md b/.changeset/38876-branch-suspending-subflow-arming.md new file mode 100644 index 00000000000..d9a9770e060 --- /dev/null +++ b/.changeset/38876-branch-suspending-subflow-arming.md @@ -0,0 +1,26 @@ +--- +'@objectstack/spec': minor +'@objectstack/service-automation': minor +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +fix(automation)!: a triggered flow whose fan-out or earlier branch reaches a subflow or map whose child can suspend is not armed + +Clause-②: no (narrowing) +Metadata-protocol: narrowed +Skills-docs: none — no page under `skills/**` teaches the fan-out or sequential pause shapes or the region decline this sits beside (git grep `suspending_subflow_in_region`, `fans out`: 0 hits); `content/docs/automation/flows.mdx` names the new cause + +**BREAKING** for a flow author: FROM a trigger-declaring flow arming when, on its top-level graph or that of any flow its top-level calls reach (at any depth), a `subflow` or `map` node whose child flow can suspend (the child reaches an `approval`, `approval_revise`, `screen` or `wait` from its start, or calls a flow that does) sits beside another pausing branch of one fan-out, or on a conditioned or `isDefault` branch the engine takes before another out-edge of the same node, TO that flow registered and saved but NOT armed: `GET /api/v1/automation/_status` reads `bound: false` with the new `unboundCause` `suspending_subflow_on_branch` and a reason naming the branching node, the call, the child and where it suspends, and the engine logs one `warn`. The one-line fix: chain the call and the other pausing step onto one branch, or make the call's branch the last one its node takes, or republish the child without a node that suspends; the flow arms the moment the shape is gone. + +Why. A run parks at one place and resumes from it, never back at the node that branched, so such a run loses a branch. The engine already fails it at run time by name, but only after the child's request opened, which is then left pending. The engine holds the child flow, so the arming gate now asks the flow parse's own fan-out and sequential readings with a call whose child can suspend counted as a pausing node, and declines the flow before any run opens a request. The flow parse is unchanged: it still cannot see a call's child (another record), so the flow still registers. + +`@objectstack/spec`: `FLOW_UNBOUND_CAUSES` gains `suspending_subflow_on_branch` (a closed vocabulary: a consumer that switches over it exhaustively gains a case). `concurrentPauseRefusals` and `sequentialPauseRefusals` are now exported from `@objectstack/spec/automation`, and take a list of node types (what the flow parse hands) or a predicate over a node (`FlowPauseReading`); each refusal also carries `shape`, `nodeId`, `branches` and, for the sequential reading, `untaken`. The parse's verdicts and messages do not move. + +`@objectstack/service-automation`: the arming gate's new branch half sits after the region half (a call inside a region body keeps `suspending_subflow_in_region`) and is asked again whenever a flow its calls reach is registered, as the other halves are, so an armed flow is un-armed when a child it calls is registered or republished with a step that suspends. For a `decision` that declares conditions but no fallback edge, the reason names the fix that keeps the routing: mark one branch edge `isDefault: true`. The reading goes down the call chain (maintainer ruling 7360068553): a reusable child flow that holds the shape, with no trigger of its own, declines the triggered flow that calls it, and the reason names the child and the calls that lead to it. Measured before: such a parent armed, and a concurrent shape in the child answered `paused` and then failed the parent even with a `fault` edge on its call node. The region half stays one level deep (its failure is synchronous and routable). Met only by the run-time branch refusal: a run started without a trigger (this is the arming gate); the shape held in a flow reached only through calls inside region bodies (the branch reading follows top-level calls, and a region-body call whose child can suspend is itself declined at arming by the region half); and a pausing node type a plugin registers. + +`@object-ui/app-shell`, `@object-ui/i18n`: the flow run note has a plain-words line for the new unbound cause `suspending_subflow_on_branch` (English and Chinese): a subflow that calls a flow that can pause sits on a branch beside another pausing step, or before other branches of the same step, so the flow does not start until those steps are chained onto one branch or that branch is taken last. + +No conversion rewrites the shape (which rewrite the author meant is not recorded); the ADR-0087 semantic entry `flow-branch-suspending-subflow-not-armed` carries it to the upgrade guide. + + diff --git a/content/docs/automation/flows.mdx b/content/docs/automation/flows.mdx index 46bc7ff3f74..91939c2b4b4 100644 --- a/content/docs/automation/flows.mdx +++ b/content/docs/automation/flows.mdx @@ -1833,6 +1833,28 @@ ones above: chain the steps onto one branch, make the branch that pauses the last one the node takes, or republish the child flow without a step that pauses. +**Declined at activation when the child is already registered.** When a +flow's trigger activates it, the engine asks the same two questions with a +`subflow` or `map` whose child flow it holds counted as a step that pauses (a +child reaching an `approval`, `approval_revise`, `screen` or `wait` from its +start, or calling a flow that does), of the flow itself and of every flow its +calls reach, at any depth: a reusable child that holds the shape declines the +triggered flow that calls it, even though the child has no trigger. A flow of either shape still registers and +saves, but its trigger is not armed: `GET /api/v1/automation/_status` reads +`bound: false` with `unboundCause: suspending_subflow_on_branch` and a reason +naming the branching node, the call and where its child pauses (and, when the +shape is in a called flow, that flow and the calls that lead to it), and the engine +logs one `warn`. For a `decision` that declares conditions but no fallback edge, +the reason says so and names the fix that keeps the routing: mark one branch +edge `isDefault: true`. The question is asked again whenever a flow its calls +reach is registered: the flow arms the moment the shape or the child changes, +and an armed flow is un-armed when a child or grandchild it calls is registered, +or republished, with a step that pauses. Only the run-time error above meets a +run started without a trigger. A call inside a region body keeps its own cause, +`suspending_subflow_in_region`, judged one level deep: a region failure is +always immediate and an error-handler edge can route it, while a branch failure +in a child can arrive after the parent has paused, where nothing routes it. + ### Batch approval — a `map` node, one item at a time "Sign off **every** task in the release, in turn" is a **`map` node**: it runs a diff --git a/packages/plugins/plugin-approvals/src/flow-route.integration.test.ts b/packages/plugins/plugin-approvals/src/flow-route.integration.test.ts index 2ad42cd7a9f..672f6816e2a 100644 --- a/packages/plugins/plugin-approvals/src/flow-route.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/flow-route.integration.test.ts @@ -1534,4 +1534,68 @@ describe('[#38876] a branch whose subflow child parks, where the run cannot park expect((await automation.getRun(parentRunId))?.status).toBe('completed'); expect(await ranNodes(automation, parentRunId)).not.toContain('s_sync'); }); + /** + * The ARMING door (maintainer ruling 「38876 选 A」, record 7336647907): the + * same shapes, record-triggered, are declined when the trigger activates + * them and the child they call is already registered and can park, so no + * run opens a request the refusal above would strand. The engine asks the + * spec's fan-out / sequential readings (`flow-concurrent-pause.ts`) with a + * call whose child can park counted as a pausing node. Each flow here still + * registers; it is left unarmed with `unboundCause` + * `suspending_subflow_on_branch`. The run-time refusal above stays the door + * for a child that registers, or starts to park, after the caller armed. + */ + describe('[#38876] the arming door: the same shapes are declined at trigger activation when the child in hand parks', () => { + const triggered = > }>(flow: F): F => ({ + ...flow, + nodes: flow.nodes.map((n) => (n.id === 'start' + ? { ...n, config: { objectName: 'crm_contract', triggerType: 'record-after-create' } } + : n)), + }); + const arming = (...flows: any[]) => { + const { automation } = bootEngine(); + const bound = new Set(); + automation.registerTrigger({ + type: 'record_change', + start(binding: { flowName: string }) { bound.add(binding.flowName); }, + stop(flowName: string) { bound.delete(flowName); }, + } as any); + for (const flow of flows) automation.registerFlow(flow.name, flow); + const row = (name: string) => automation.getFlowRuntimeStates().find((s) => s.name === name); + return { bound, row }; + }; + const SHAPES: Array<[string, () => any]> = [ + ['CONCURRENT, an approval beside a subflow', () => fanOutToApprovalAndCall('arm_fan_out_subflow')], + ['CONCURRENT, an approval beside a map', () => fanOutToApprovalAndCall('arm_fan_out_map', 'map')], + ['CONCURRENT, two subflows', () => fanOutToTwoCalls('arm_fan_out_two_calls')], + ['SEQUENTIAL, a conditioned edge into the subflow before a conditioned sibling', () => callBeforeConditionedSibling('arm_sequential_conditioned')], + ['SEQUENTIAL, an isDefault edge into the subflow beside an unconditional sibling', () => defaultCallBesideUnconditional('arm_sequential_default')], + ]; + + it.each(SHAPES)('%s: registered, not armed, `suspending_subflow_on_branch`', (_shape, make) => { + const flow = triggered(make()); + const { bound, row } = arming(PARKING_CHILD, WAITING_CHILD, flow); + expect(bound.has(flow.name)).toBe(false); + expect(row(flow.name)).toMatchObject({ enabled: true, bound: false, unboundCause: 'suspending_subflow_on_branch' }); + expect(row(flow.name)?.reason).toContain("calls child flow 'branch_"); + }); + + it.each(SHAPES)('CONTROL, %s, with no child registered: armed (the run-time door stays)', (_shape, make) => { + const flow = triggered(make()); + const { bound, row } = arming(flow); + expect(bound.has(flow.name)).toBe(true); + expect(row(flow.name)?.unboundCause).toBeUndefined(); + }); + + it.each(SHAPES)('CONTROL, %s, whose children run straight through: armed', (_shape, make) => { + const flow = triggered(make()); + const through = (name: string) => ({ + name, label: name, type: 'autolaunched', + nodes: [{ id: 'start', type: 'start', label: 'Start' }, { id: 'ok', type: 'end', label: 'Ok' }], + edges: [{ id: 't1', source: 'start', target: 'ok' }], + }); + const { bound } = arming(through(PARKING_CHILD.name), through(WAITING_CHILD.name), flow); + expect(bound.has(flow.name)).toBe(true); + }); + }); }); diff --git a/packages/services/service-automation/src/engine-enablement-facet.ts b/packages/services/service-automation/src/engine-enablement-facet.ts index a384069afe8..f3b1fb76903 100644 --- a/packages/services/service-automation/src/engine-enablement-facet.ts +++ b/packages/services/service-automation/src/engine-enablement-facet.ts @@ -5,6 +5,7 @@ * `isFlowEnabled`, `describeDisabledFlow`, `subflowTargets`, * `resolvedFlowCallKey`, `declineOntoDisabledSubflows`, * `declineOntoSuspendingSubflowNotice`, `declineOntoRegionSuspendingCall`, + * `declineOntoBranchSuspendingCall` (#38876, added here), * `declineOntoSubflowRetriedCallout`, `toggleFlow`, `toggleFlowSlot`, * `getFlowVersionHistory`, `rollbackFlow` * moved out of `engine.ts` whole. @@ -39,6 +40,7 @@ import { describeDisabledFlow, subflowTargets } from './subflow-guards.js'; import { describeSubflowNoticeTrap, subflowNoticeTrap } from './subflow-notice-guard.js'; import { isSlotKeySpelling, unfiledFlowKey } from './flow-slots.js'; import { describeRegionSuspendingCall, regionSuspendingCall } from './subflow-region-guard.js'; +import { branchSuspendingCall, describeBranchSuspendingCall } from './subflow-branch-guard.js'; import { describeSubflowRetriedCallout, subflowRetriedCallout } from './subflow-retry-guard.js'; import type { AutomationEngine } from './engine.js'; @@ -65,6 +67,7 @@ export interface EnablementHost { readonly resolveFlowKey: AutomationEngine['resolveFlowKey']; readonly resolvedFlowCallKey: AutomationEngine['resolvedFlowCallKey']; readonly servedBareFlowKey: AutomationEngine['servedBareFlowKey']; + readonly subflowBranchDeclinedFlows: AutomationEngine['subflowBranchDeclinedFlows']; readonly subflowDeclinedFlows: AutomationEngine['subflowDeclinedFlows']; readonly subflowNoticeDeclinedFlows: AutomationEngine['subflowNoticeDeclinedFlows']; readonly subflowRegionDeclinedFlows: AutomationEngine['subflowRegionDeclinedFlows']; @@ -322,6 +325,48 @@ export class EnablementFacet { return true; } + /** + * [#38876] The arming gate's branch half, asked by + * {@link activateFlowTrigger} of an enabled flow it is about to arm: does a + * top-level `subflow` / `map` node whose child flow can suspend sit on a + * branch that loses work when it parks ({@link branchSuspendingCall}: the + * spec's fan-out and sequential pause readings, `flow-concurrent-pause.ts`, + * asked with that call counted as a pausing node)? A run parks at one place + * and resumes from it, so such a run would be failed by the branch refusal + * (`branch-suspension-refusal.ts`) the first time the child suspends, after + * its requests opened. Then it is declined: recorded on + * {@link subflowBranchDeclinedFlows} for `/_status` and the binding audit, + * and said once as a `warn` naming the branching node, the call node and + * where the child suspends. + * + * Any flow, packaged or authored here, as the region half; ⛔ a decline, + * never a refusal, for that half's reasons (the child may register after + * this flow). #4632 verdict: FUNCTIONAL, `warn`. Said once per decline + * reason. + * + * @returns `true` when the flow is declined and must not be armed. + */ + static declineOntoBranchSuspendingCall(this: Pick, flowName: string, triggerType: string): boolean { + const trap = branchSuspendingCall(this.flows, flowName, this.flowCallKey); + if (!trap) { + this.subflowBranchDeclinedFlows.delete(flowName); + return false; + } + const why = describeBranchSuspendingCall(trap); + const reason = + `not armed — ${why}, and it is armed; it is also armed once '${trap.child}' is republished without a ` + + `node that suspends`; + const previous = this.subflowBranchDeclinedFlows.get(flowName); + this.subflowBranchDeclinedFlows.set(flowName, reason); + if (previous === reason) return true; + this.logger.warn( + `Flow '${flowName}' is registered but NOT armed on trigger '${triggerType}' — ${why}. It is armed the ` + + `moment the branches of '${trap.holder}' change, or '${trap.child}' is republished without a node ` + + `that suspends.`, + ); + return true; + } + /** * The arming gate's subflow-retry half, asked by * {@link activateFlowTrigger} of an enabled flow it is about to arm: does diff --git a/packages/services/service-automation/src/engine-extensions-facet.ts b/packages/services/service-automation/src/engine-extensions-facet.ts index dd9cf298a3c..2f343b18d9a 100644 --- a/packages/services/service-automation/src/engine-extensions-facet.ts +++ b/packages/services/service-automation/src/engine-extensions-facet.ts @@ -75,6 +75,7 @@ export interface ExtensionsHost { readonly connectorProviders: AutomationEngine['connectorProviders']; readonly connectors: AutomationEngine['connectors']; readonly credentialHandleProviders: AutomationEngine['credentialHandleProviders']; + readonly declineOntoBranchSuspendingCall: AutomationEngine['declineOntoBranchSuspendingCall']; readonly declineOntoDisabledSubflows: AutomationEngine['declineOntoDisabledSubflows']; readonly declineOntoRegionSuspendingCall: AutomationEngine['declineOntoRegionSuspendingCall']; readonly declineOntoSubflowRetriedCallout: AutomationEngine['declineOntoSubflowRetriedCallout']; @@ -143,7 +144,7 @@ export class ExtensionsFacet { * binding, or when no trigger is registered for its type yet — * {@link registerTrigger} re-attempts activation when one arrives. */ - static activateFlowTrigger(this: Pick, flowName: string): void { + static activateFlowTrigger(this: Pick, flowName: string): void { if (this.boundFlowTriggers.has(flowName)) return; // [ADR-0126 §7.2] THE enablement gate for arming — here, at the one // point every arming path crosses, and not in its callers. A flow @@ -301,6 +302,14 @@ export class ExtensionsFacet { // records in the same order, so a record an earlier half's decline // left unasked is never the one reported. if (this.declineOntoRegionSuspendingCall(flowName, resolved.triggerType)) return; + // [#38876] The branch half, a decline for the same reasons: a + // top-level `subflow` / `map` whose child suspends, on a fan-out beside + // another pausing branch or on a branch taken before later edges, loses + // work when it parks; the run-time door (`branch-suspension-refusal.ts`) + // fails such a run after its requests opened. The spec's pause readings, + // asked with the child in hand. After the region half, and + // {@link describeUnboundReason} reads its record after the region's. + if (this.declineOntoBranchSuspendingCall(flowName, resolved.triggerType)) return; // The subflow-retry half, a decline for the same reasons: an // after-record-change run waits for its `subflow` / `map` children, so // an inline outbound call a child retries holds the save through the diff --git a/packages/services/service-automation/src/engine-flow-slots-facet.ts b/packages/services/service-automation/src/engine-flow-slots-facet.ts index a853c6b4b71..32887dc7c59 100644 --- a/packages/services/service-automation/src/engine-flow-slots-facet.ts +++ b/packages/services/service-automation/src/engine-flow-slots-facet.ts @@ -117,6 +117,7 @@ export interface FlowSlotsHost { readonly subflowDeclinedFlows: AutomationEngine['subflowDeclinedFlows']; readonly subflowNoticeDeclinedFlows: AutomationEngine['subflowNoticeDeclinedFlows']; readonly subflowRegionDeclinedFlows: AutomationEngine['subflowRegionDeclinedFlows']; + readonly subflowBranchDeclinedFlows: AutomationEngine['subflowBranchDeclinedFlows']; readonly subflowRetryDeclinedFlows: AutomationEngine['subflowRetryDeclinedFlows']; readonly suspendedRuns: AutomationEngine['suspendedRuns']; } @@ -264,7 +265,7 @@ export class FlowSlotsFacet { * under the old key first and armed under the new one after, through the * one arming gate. */ - static moveFlowRecords(this: Pick, moved: readonly FlowKeyMove[]): void { + static moveFlowRecords(this: Pick, moved: readonly FlowKeyMove[]): void { if (moved.length === 0) return; for (const { from } of moved) { this.deactivateFlowTrigger(from); @@ -281,6 +282,7 @@ export class FlowSlotsFacet { this.subflowDeclinedFlows, this.subflowNoticeDeclinedFlows, this.subflowRegionDeclinedFlows, + this.subflowBranchDeclinedFlows, this.subflowRetryDeclinedFlows, ]; for (const { from, to } of moved) { diff --git a/packages/services/service-automation/src/engine-registration-facet.ts b/packages/services/service-automation/src/engine-registration-facet.ts index 23564504196..fe54ef13c2c 100644 --- a/packages/services/service-automation/src/engine-registration-facet.ts +++ b/packages/services/service-automation/src/engine-registration-facet.ts @@ -104,6 +104,7 @@ export interface RegistrationHost { readonly subflowDeclinedFlows: AutomationEngine['subflowDeclinedFlows']; readonly subflowNoticeDeclinedFlows: AutomationEngine['subflowNoticeDeclinedFlows']; readonly subflowRegionDeclinedFlows: AutomationEngine['subflowRegionDeclinedFlows']; + readonly subflowBranchDeclinedFlows: AutomationEngine['subflowBranchDeclinedFlows']; readonly subflowRetryDeclinedFlows: AutomationEngine['subflowRetryDeclinedFlows']; readonly unknownNodeTypes: AutomationEngine['unknownNodeTypes']; readonly userGrantsResolver: AutomationEngine['userGrantsResolver']; @@ -323,7 +324,7 @@ export class RegistrationFacet { if (key !== undefined) this.withdrawFlowKey(key); } - static withdrawFlowKey(this: Pick, name: string): void { + static withdrawFlowKey(this: Pick, name: string): void { this.sharedSlotTriggerWarned.delete(name); // The body lives in ./flow-definitions.ts (#25222). const host: ThisParameterType = { @@ -335,6 +336,7 @@ export class RegistrationFacet { subflowDeclinedFlows: this.subflowDeclinedFlows, subflowNoticeDeclinedFlows: this.subflowNoticeDeclinedFlows, subflowRegionDeclinedFlows: this.subflowRegionDeclinedFlows, + subflowBranchDeclinedFlows: this.subflowBranchDeclinedFlows, subflowRetryDeclinedFlows: this.subflowRetryDeclinedFlows, flowRefusals: this.flowRefusals, logger: this.logger, diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index e5f5ef04e0f..3db91a52e1f 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -808,6 +808,13 @@ export class AutomationEngine implements IAutomationService { * {@link withdrawFlow}. */ private readonly subflowRegionDeclinedFlows = new Map(); + /** + * [#38876] Flows {@link activateFlowTrigger} declined to arm because a + * top-level `subflow` / `map` node whose child can suspend sits on a branch + * that loses work when it parks, each with the reason `/_status` and the + * binding audit read; kept as {@link subflowRegionDeclinedFlows} is. + */ + private readonly subflowBranchDeclinedFlows = new Map(); /** * Flows {@link activateFlowTrigger} declined to arm because they run after * a record change and a `subflow` / `map` node of theirs reaches an inline @@ -2706,6 +2713,7 @@ export class AutomationEngine implements IAutomationService { subflowDeclinedFlows: this.subflowDeclinedFlows, subflowNoticeDeclinedFlows: this.subflowNoticeDeclinedFlows, subflowRegionDeclinedFlows: this.subflowRegionDeclinedFlows, + subflowBranchDeclinedFlows: this.subflowBranchDeclinedFlows, subflowRetryDeclinedFlows: this.subflowRetryDeclinedFlows, triggers: this.triggers, }; @@ -3968,6 +3976,17 @@ export class AutomationEngine implements IAutomationService { return EnablementFacet.declineOntoRegionSuspendingCall.call(enablementHost.of(this), flowName, triggerType); } + /** + * [#38876] The arming gate's branch half: a top-level `subflow` / `map` + * whose child can suspend, on a fan-out or earlier branch that loses work + * when it parks. The body's docblock is the contract. + * + * @returns `true` when the flow is declined and must not be armed. + */ + private declineOntoBranchSuspendingCall(flowName: string, triggerType: string): boolean { + return EnablementFacet.declineOntoBranchSuspendingCall.call(enablementHost.of(this), flowName, triggerType); + } + /** * The arming gate's subflow-retry half, asked by * {@link activateFlowTrigger} of an enabled flow it is about to arm: does @@ -4021,7 +4040,8 @@ export class AutomationEngine implements IAutomationService { * offered again, both through the one gate. * * [#28897] The region half reads the same children through the same - * calls, so the same callers are re-asked for it, the same way. + * calls, so the same callers are re-asked for it, the same way; so does + * the branch half (#38876). */ private rejudgeSubflowCallers(subflow: string): void { // The body lives in ./subflow-guards.ts (#25222). @@ -4030,6 +4050,7 @@ export class AutomationEngine implements IAutomationService { subflowDeclinedFlows: this.subflowDeclinedFlows, subflowNoticeDeclinedFlows: this.subflowNoticeDeclinedFlows, subflowRegionDeclinedFlows: this.subflowRegionDeclinedFlows, + subflowBranchDeclinedFlows: this.subflowBranchDeclinedFlows, subflowRetryDeclinedFlows: this.subflowRetryDeclinedFlows, flows: this.flows, subflowTargets: (...a) => this.subflowTargets(...a), @@ -7532,6 +7553,7 @@ export class AutomationEngine implements IAutomationService { get connectorProviders() { return engine.connectorProviders; }, get connectors() { return engine.connectors; }, get credentialHandleProviders() { return engine.credentialHandleProviders; }, + declineOntoBranchSuspendingCall: (...a) => engine.declineOntoBranchSuspendingCall(...a), declineOntoDisabledSubflows: (...a) => engine.declineOntoDisabledSubflows(...a), declineOntoRegionSuspendingCall: (...a) => engine.declineOntoRegionSuspendingCall(...a), declineOntoSubflowRetriedCallout: (...a) => engine.declineOntoSubflowRetriedCallout(...a), @@ -7622,6 +7644,7 @@ export class AutomationEngine implements IAutomationService { get subflowDeclinedFlows() { return engine.subflowDeclinedFlows; }, get subflowNoticeDeclinedFlows() { return engine.subflowNoticeDeclinedFlows; }, get subflowRegionDeclinedFlows() { return engine.subflowRegionDeclinedFlows; }, + get subflowBranchDeclinedFlows() { return engine.subflowBranchDeclinedFlows; }, get subflowRetryDeclinedFlows() { return engine.subflowRetryDeclinedFlows; }, get suspendedRuns() { return engine.suspendedRuns; }, })); @@ -7673,6 +7696,7 @@ export class AutomationEngine implements IAutomationService { get subflowDeclinedFlows() { return engine.subflowDeclinedFlows; }, get subflowNoticeDeclinedFlows() { return engine.subflowNoticeDeclinedFlows; }, get subflowRegionDeclinedFlows() { return engine.subflowRegionDeclinedFlows; }, + get subflowBranchDeclinedFlows() { return engine.subflowBranchDeclinedFlows; }, get subflowRetryDeclinedFlows() { return engine.subflowRetryDeclinedFlows; }, unknownNodeTypes: (...a) => engine.unknownNodeTypes(...a), get userGrantsResolver() { return engine.userGrantsResolver; }, @@ -7716,6 +7740,7 @@ export class AutomationEngine implements IAutomationService { get subflowDeclinedFlows() { return engine.subflowDeclinedFlows; }, get subflowNoticeDeclinedFlows() { return engine.subflowNoticeDeclinedFlows; }, get subflowRegionDeclinedFlows() { return engine.subflowRegionDeclinedFlows; }, + get subflowBranchDeclinedFlows() { return engine.subflowBranchDeclinedFlows; }, get subflowRetryDeclinedFlows() { return engine.subflowRetryDeclinedFlows; }, toggleFlowKey: (...a) => engine.toggleFlowKey(...a), })); diff --git a/packages/services/service-automation/src/flow-definitions.ts b/packages/services/service-automation/src/flow-definitions.ts index bef8c73ad1a..96d0d4ae210 100644 --- a/packages/services/service-automation/src/flow-definitions.ts +++ b/packages/services/service-automation/src/flow-definitions.ts @@ -76,6 +76,7 @@ export interface FlowDefinitionsHost { readonly subflowDeclinedFlows: AutomationEngine['subflowDeclinedFlows']; readonly subflowNoticeDeclinedFlows: AutomationEngine['subflowNoticeDeclinedFlows']; readonly subflowRegionDeclinedFlows: AutomationEngine['subflowRegionDeclinedFlows']; + readonly subflowBranchDeclinedFlows: AutomationEngine['subflowBranchDeclinedFlows']; readonly subflowRetryDeclinedFlows: AutomationEngine['subflowRetryDeclinedFlows']; readonly triggers: AutomationEngine['triggers']; readonly flowCredentialSource: AutomationEngine['flowCredentialSource']; @@ -305,7 +306,7 @@ export function getFlowRuntimeStates(this: Pick, + this: Pick, name: string, resolved: { triggerType: string } | undefined, ): { reason: string; cause: FlowUnboundCause } | undefined { @@ -333,6 +334,12 @@ export function describeUnboundReason( // Read last, the gate's own order. const regionDeclined = this.subflowRegionDeclinedFlows.get(name); if (regionDeclined !== undefined) return { reason: regionDeclined, cause: 'suspending_subflow_in_region' }; + // [#38876] The gate's branch half declined it: a top-level `subflow` / + // `map` whose child can suspend sits on a fan-out or earlier branch that + // loses work when it parks. Its own cause, for its own remedy (the author + // chains the branches, or the child stops suspending). The gate's order. + const branchDeclined = this.subflowBranchDeclinedFlows.get(name); + if (branchDeclined !== undefined) return { reason: branchDeclined, cause: 'suspending_subflow_on_branch' }; // The gate's subflow-retry half declined it: it runs after a record change // and a `subflow` / `map` child of it retries an inline outbound call, so // the save would wait through the backoff ladder. Its own cause, for its @@ -451,7 +458,7 @@ export function unregisterConnectorProvider(this: Pick, name: string): void { +export function withdrawFlow(this: Pick, name: string): void { this.deactivateFlowTrigger(name); this.flows.delete(name); // [ADR-0126 §7.2] `flowLedgerDisabled` is deliberately NOT cleared. It @@ -470,6 +477,7 @@ export function withdrawFlow(this: Pick l; + return l; +} + +const declineWarnings = (logger: any, caller: string): string[] => + logger.warn.mock.calls + .map((c: unknown[]) => String(c[0])) + .filter((m: string) => m.includes(`Flow '${caller}'`) && m.includes('NOT armed')); + +function rig() { + const logger = createTestLogger(); + const engine = withLoaderSetFromPull(new AutomationEngine(logger)); + engine.setFlowActivationStore(new InMemoryFlowActivationStore()); + const ctx = { logger: createTestLogger(), getService: () => undefined } as any; + for (const register of [registerSubflowNode, registerMapNode, registerLoopNode, registerWaitNode, registerLogicNodes]) { + (register as (e: AutomationEngine, c: unknown) => void)(engine, ctx); + } + const bound = new Set(); + const trigger: FlowTrigger = { + type: 'record_change', + start(binding: FlowTriggerBinding, _cb: (c: AutomationContext) => Promise) { + bound.add(binding.flowName); + }, + stop(flowName: string) { + bound.delete(flowName); + }, + }; + engine.registerTrigger(trigger); + return { engine, logger, isBound: (n: string) => bound.has(n) }; +} + +const stateOf = (engine: AutomationEngine, name: string) => + engine.getFlowRuntimeStates().find((s) => s.name === name); + +type Node = Record; +type Edge = [string, string, Record?]; + +const START_TRIGGERED: Node = { id: 'start', type: 'start', label: 'Start', config: { objectName: 'lead', triggerType: 'record-after-create' } }; +const START_PLAIN: Node = { id: 'start', type: 'start', label: 'Start', config: {} }; +const end = (id: string): Node => ({ id, type: 'end', label: id }); +const step = (id: string): Node => ({ id, type: 'assignment', label: id, config: {} }); +const wait = (id: string): Node => ({ id, type: 'wait', label: id, waitEventConfig: { eventType: 'timer', timerDuration: 'PT1H' } }); +const call = (id: string, flowName: string, type: 'subflow' | 'map' = 'subflow'): Node => ({ + id, type, label: id, config: { flowName, ...(type === 'map' ? { collection: [1] } : {}) }, +}); + +function flow(name: string, nodes: Node[], edges: Edge[], triggered = true) { + return { + name, label: name, type: 'autolaunched', + nodes: [triggered ? START_TRIGGERED : START_PLAIN, ...nodes], + edges: edges.map(([source, target, extra], i) => ({ id: `e${i}`, source, target, ...(extra ?? {}) })), + }; +} + +/** A child flow that suspends at its `wait` node `child_hold`. */ +const pausingChild = (name: string) => flow(name, [wait('child_hold'), end('done')], [['start', 'child_hold'], ['child_hold', 'done']], false); +/** A child flow that runs straight through. */ +const plainChild = (name: string) => flow(name, [step('work'), end('done')], [['start', 'work'], ['work', 'done']], false); + +/** Fan-out: one branch waits on its own, the other calls `child`. */ +const concurrentCaller = (name: string, child: string, type: 'subflow' | 'map' = 'subflow') => + flow(name, [wait('own_hold'), call('sub', child, type), end('ok'), end('ok2')], [ + ['start', 'own_hold'], ['start', 'sub'], ['own_hold', 'ok'], ['sub', 'ok2'], + ]); +/** Sequential: `x1` takes the call's branch before a later edge. */ +const sequentialCaller = (name: string, child: string, firstEdge: Record, laterEdge: Record) => + flow(name, [step('x1'), call('sub', child), step('s_after'), end('ok'), end('ok2')], [ + ['start', 'x1'], ['x1', 'sub', firstEdge], ['x1', 's_after', laterEdge], ['sub', 'ok'], ['s_after', 'ok2'], + ]); + +describe('the arming gate declines a call whose child can suspend, on a branch that loses work when it parks (#38876)', () => { + it.each(['subflow', 'map'] as const)('a fan-out beside another pausing branch, through a `%s` call: registered, not armed, naming the fork, the call and the pause', async (type) => { + const { engine, logger, isBound } = rig(); + engine.registerFlow('deal_review', pausingChild('deal_review')); + engine.registerFlow('deal_submit', concurrentCaller('deal_submit', 'deal_review', type)); + + expect(await engine.getFlow('deal_submit'), 'the caller is still registered').not.toBeNull(); + expect(isBound('deal_submit')).toBe(false); + const row = stateOf(engine, 'deal_submit'); + expect(row).toMatchObject({ enabled: true, bound: false, unboundCause: 'suspending_subflow_on_branch' }); + expect(row?.reason).toContain("its node 'start' fans out"); + expect(row?.reason).toContain(`\`${type}\` node 'sub' calls child flow 'deal_review', which can suspend the run at \`wait\` node 'child_hold'`); + expect(declineWarnings(logger, 'deal_submit')).toHaveLength(1); + }); + + it('two concurrent calls, each to a child that can suspend', () => { + const { engine, isBound } = rig(); + engine.registerFlow('ask_a', pausingChild('ask_a')); + engine.registerFlow('ask_b', pausingChild('ask_b')); + engine.registerFlow('deal_submit', flow('deal_submit', [call('sub_a', 'ask_a'), call('sub_b', 'ask_b')], [ + ['start', 'sub_a'], ['start', 'sub_b'], + ])); + expect(isBound('deal_submit')).toBe(false); + expect(stateOf(engine, 'deal_submit')?.unboundCause).toBe('suspending_subflow_on_branch'); + }); + + it.each([ + ['an earlier conditioned edge before a later conditioned one', { condition: 'true' }, { condition: 'true' }], + ['an `isDefault` edge before an unconditional sibling', { isDefault: true }, {}], + ['a conditioned edge before an unconditional sibling', { condition: 'true' }, {}], + ])('sequential: %s into the call: not armed, naming the edge it leaves untaken', (_label, firstEdge, laterEdge) => { + const { engine, logger, isBound } = rig(); + engine.registerFlow('deal_review', pausingChild('deal_review')); + engine.registerFlow('deal_submit', sequentialCaller('deal_submit', 'deal_review', firstEdge, laterEdge)); + + expect(isBound('deal_submit')).toBe(false); + const row = stateOf(engine, 'deal_submit'); + expect(row).toMatchObject({ enabled: true, bound: false, unboundCause: 'suspending_subflow_on_branch' }); + expect(row?.reason).toContain("its node 'x1' takes edge 'e1' ('x1' → 'sub') before 'e2' ('x1' → 's_after')"); + expect(row?.reason).toContain('route them through a `decision`'); + expect(declineWarnings(logger, 'deal_submit')).toHaveLength(1); + }); + + it('a `decision` with conditions and no fallback edge, routing to the call and a pausing step: declined with the fix that keeps the routing', () => { + const { engine, logger, isBound } = rig(); + engine.registerFlow('deal_review', pausingChild('deal_review')); + const route = (fallback: boolean) => flow('deal_route', [ + { id: 'route', type: 'decision', label: 'Route', config: { conditions: [ + { label: 'big', expression: 'record.amount > 100' }, { label: 'small', expression: 'record.amount <= 100' }, + ] } }, + call('sub', 'deal_review'), wait('own_hold'), end('ok'), end('ok2'), + ], [ + ['start', 'route'], ['route', 'sub', { label: 'big' }], ['route', 'own_hold', { label: 'small', ...(fallback ? { isDefault: true } : {}) }], + ['sub', 'ok'], ['own_hold', 'ok2'], + ]); + engine.registerFlow('deal_route', route(false)); + expect(isBound('deal_route')).toBe(false); + const row = stateOf(engine, 'deal_route'); + expect(row).toMatchObject({ enabled: true, bound: false, unboundCause: 'suspending_subflow_on_branch' }); + expect(row?.reason).toContain("its `decision` node 'route' declares conditions but no fallback edge"); + expect(row?.reason).toContain("Mark one of 'route''s branch edges isDefault: true"); + expect(row?.reason).not.toContain('Chain'); + expect(declineWarnings(logger, 'deal_route')).toHaveLength(1); + + // CONTROL: the same routing with its fallback edge marked arms (one branch is taken on every run). + engine.registerFlow('deal_route', route(true)); + expect(isBound('deal_route')).toBe(true); + expect(stateOf(engine, 'deal_route')?.unboundCause).toBeUndefined(); + }); + + it('is asked again on every child registration: armed while the child is absent or runs through, declined while it suspends', () => { + const { engine, isBound } = rig(); + engine.registerFlow('deal_submit', concurrentCaller('deal_submit', 'deal_review')); + expect(isBound('deal_submit'), 'no child yet: nothing in hand can suspend').toBe(true); + + engine.registerFlow('deal_review', pausingChild('deal_review')); + expect(isBound('deal_submit')).toBe(false); + expect(stateOf(engine, 'deal_submit')?.unboundCause).toBe('suspending_subflow_on_branch'); + + engine.registerFlow('deal_review', plainChild('deal_review')); + expect(isBound('deal_submit')).toBe(true); + expect(stateOf(engine, 'deal_submit')?.unboundCause).toBeUndefined(); + }); + + it('reads where the child suspends through its own calls, a flow two calls away', () => { + const { engine, isBound } = rig(); + engine.registerFlow('deal_ask', plainChild('deal_ask')); + engine.registerFlow('deal_review', flow('deal_review', [call('inner', 'deal_ask')], [['start', 'inner']], false)); + engine.registerFlow('deal_submit', sequentialCaller('deal_submit', 'deal_review', { condition: 'true' }, { condition: 'true' })); + expect(isBound('deal_submit')).toBe(true); + + engine.registerFlow('deal_ask', pausingChild('deal_ask')); + expect(isBound('deal_submit')).toBe(false); + expect(stateOf(engine, 'deal_submit')?.reason).toContain("at `wait` node 'child_hold' of 'deal_ask'"); + }); + + it('a withdrawn caller takes its decline record with it', () => { + const { engine } = rig(); + engine.registerFlow('deal_review', pausingChild('deal_review')); + engine.registerFlow('deal_submit', concurrentCaller('deal_submit', 'deal_review')); + expect(stateOf(engine, 'deal_submit')?.unboundCause).toBe('suspending_subflow_on_branch'); + engine.unregisterFlow('deal_submit'); + engine.registerFlow('deal_submit', flow('deal_submit', [call('sub', 'deal_review')], [['start', 'sub']])); + expect(stateOf(engine, 'deal_submit')).toMatchObject({ bound: true }); + expect(stateOf(engine, 'deal_submit')?.unboundCause).toBeUndefined(); + }); +}); + +describe('controls: what the branch half leaves armed, or leaves to another door (#38876)', () => { + it('CONTROL: the same fan-out with no child registered arms (nothing in hand can suspend; the run-time door stays)', () => { + const { engine, logger, isBound } = rig(); + engine.registerFlow('deal_submit', concurrentCaller('deal_submit', 'deal_review')); + expect(isBound('deal_submit')).toBe(true); + expect(declineWarnings(logger, 'deal_submit')).toEqual([]); + }); + + it('CONTROL: the same fan-out and sequential shapes whose child does not suspend arm', () => { + const { engine, isBound } = rig(); + engine.registerFlow('deal_review', plainChild('deal_review')); + engine.registerFlow('fan', concurrentCaller('fan', 'deal_review', 'map')); + engine.registerFlow('seq', sequentialCaller('seq', 'deal_review', { condition: 'true' }, { condition: 'true' })); + expect(isBound('fan')).toBe(true); + expect(isBound('seq')).toBe(true); + }); + + it('CONTROL: one pausing call beside a synchronous branch, or taken last, arms (the run parks at one place, nothing after it)', () => { + const { engine, isBound } = rig(); + engine.registerFlow('deal_review', pausingChild('deal_review')); + engine.registerFlow('beside', flow('beside', [call('sub', 'deal_review'), step('s1')], [['start', 'sub'], ['start', 's1']])); + engine.registerFlow('last', sequentialCaller('last', 'deal_review', { condition: 'true' }, { condition: 'true' })); + // `last`'s call is the FIRST conditioned edge; swap it to the last. + engine.registerFlow('last', flow('last', [step('x1'), step('s_after'), call('sub', 'deal_review')], [ + ['start', 'x1'], ['x1', 's_after', { condition: 'true' }], ['x1', 'sub', { condition: 'true' }], + ])); + expect(isBound('beside')).toBe(true); + expect(isBound('last')).toBe(true); + }); + + it('CONTROL: a region-nested call to a suspending child keeps its region cause, also beside a branch the branch half would decline', () => { + const { engine, isBound } = rig(); + engine.registerFlow('deal_review', pausingChild('deal_review')); + const box: Node = { + id: 'box', type: 'loop', label: 'Box', + config: { collection: [1], iteratorVariable: 'item', body: { nodes: [call('inner', 'deal_review')], edges: [] } }, + }; + engine.registerFlow('deal_submit', flow('deal_submit', [box, wait('own_hold'), call('sub', 'deal_review')], [ + ['start', 'box'], ['box', 'own_hold'], ['box', 'sub'], + ])); + expect(isBound('deal_submit')).toBe(false); + expect(stateOf(engine, 'deal_submit')?.unboundCause).toBe('suspending_subflow_in_region'); + }); + + it('CONTROL: a shape the parse refuses (two always-pausing branches) is refused at registerFlow, never declined', async () => { + const { engine, isBound } = rig(); + expect(() => engine.registerFlow('deal_submit', flow('deal_submit', [wait('a_hold'), wait('b_hold')], [ + ['start', 'a_hold'], ['start', 'b_hold'], + ]))).toThrow(/fans out to concurrent branches that each reach a node that parks the run/); + expect(await engine.getFlow('deal_submit')).toBeNull(); + expect(isBound('deal_submit')).toBe(false); + expect(stateOf(engine, 'deal_submit')).toBeUndefined(); + }); +}); + +/** + * [Maintainer ruling 「B 往下查到底(推荐)」, record 7360068553] The branch half + * reads down the call chain: a triggered flow whose top-level calls reach, + * at any depth, a flow that holds the shape is declined, and the reason names + * the flow that holds it and the calls that lead there. Measured before (this + * card's fix round 2): such a parent armed; the concurrent shape answered + * `paused` and failed the parent afterwards even with a `fault` edge on its + * call node; the sequential one failed it at once, or routed through the + * `fault` edge as a success. The region half stays one level deep. + */ +describe('the branch half reads down the call chain (#38876, ruling 7360068553)', () => { + /** `f` as a reusable child: the same graph with a start that declares no trigger. */ + const asChild = (f: ReturnType) => ({ ...f, nodes: f.nodes.map((n) => (n.id === 'start' ? START_PLAIN : n)) }); + /** A triggered parent whose one top-level call reaches `child` (optionally with a `fault` edge on that call). */ + const parent = (name: string, child: string, fault = false) => + flow(name, [call('call_c', child), end('ok'), ...(fault ? [end('handled')] : [])], [ + ['start', 'call_c'], ['call_c', 'ok'], ...(fault ? [['call_c', 'handled', { type: 'fault' }] as Edge] : []), + ]); + /** An untriggered flow whose one top-level call reaches `child`. */ + const relay = (name: string, child: string) => flow(name, [call('call_next', child), end('ok')], [['start', 'call_next'], ['call_next', 'ok']], false); + + it.each([false, true])('a child holding the CONCURRENT shape declines the triggered parent (fault edge on the call: %s), naming the child and the chain', (fault) => { + const { engine, logger, isBound } = rig(); + engine.registerFlow('deal_review', pausingChild('deal_review')); + engine.registerFlow('c_child', asChild(concurrentCaller('c_child', 'deal_review'))); + engine.registerFlow('p_parent', parent('p_parent', 'c_child', fault)); + + expect(isBound('p_parent')).toBe(false); + const row = stateOf(engine, 'p_parent'); + expect(row).toMatchObject({ enabled: true, bound: false, unboundCause: 'suspending_subflow_on_branch' }); + expect(row?.reason).toContain("the flow it calls, 'c_child' (reached through 'p_parent' → 'c_child'): its node 'start' fans out"); + expect(row?.reason).toContain("`subflow` node 'sub' calls child flow 'deal_review', which can suspend the run at `wait` node 'child_hold'"); + expect(declineWarnings(logger, 'p_parent')).toHaveLength(1); + expect(declineWarnings(logger, 'p_parent')[0]).toContain("the branches of 'c_child' change"); + }); + + it('a child holding the SEQUENTIAL shape declines the triggered parent', () => { + const { engine, isBound } = rig(); + engine.registerFlow('deal_review', pausingChild('deal_review')); + engine.registerFlow('c_child', asChild(sequentialCaller('c_child', 'deal_review', { condition: 'true' }, { condition: 'true' }))); + engine.registerFlow('p_parent', parent('p_parent', 'c_child')); + + expect(isBound('p_parent')).toBe(false); + const row = stateOf(engine, 'p_parent'); + expect(row?.unboundCause).toBe('suspending_subflow_on_branch'); + expect(row?.reason).toContain("the flow it calls, 'c_child' (reached through 'p_parent' → 'c_child'): its node 'x1' takes edge 'e1' ('x1' → 'sub')"); + }); + + it('depth three: the shape in a great-grandchild is found, the whole chain named', () => { + const { engine, isBound } = rig(); + engine.registerFlow('deal_review', pausingChild('deal_review')); + engine.registerFlow('d_deep', asChild(concurrentCaller('d_deep', 'deal_review'))); + engine.registerFlow('c_mid', relay('c_mid', 'd_deep')); + engine.registerFlow('p_parent', parent('p_parent', 'c_mid')); + + expect(isBound('p_parent')).toBe(false); + expect(stateOf(engine, 'p_parent')?.reason).toContain("the flow it calls, 'd_deep' (reached through 'p_parent' → 'c_mid' → 'd_deep')"); + }); + + it('is asked again when the GRANDCHILD changes: armed, declined, armed again', () => { + const { engine, isBound } = rig(); + engine.registerFlow('c_child', asChild(concurrentCaller('c_child', 'deal_review'))); + engine.registerFlow('p_parent', parent('p_parent', 'c_child')); + expect(isBound('p_parent'), 'no grandchild yet: the child holds one pausing branch').toBe(true); + + engine.registerFlow('deal_review', pausingChild('deal_review')); + expect(isBound('p_parent')).toBe(false); + expect(stateOf(engine, 'p_parent')?.unboundCause).toBe('suspending_subflow_on_branch'); + + engine.registerFlow('deal_review', plainChild('deal_review')); + expect(isBound('p_parent')).toBe(true); + expect(stateOf(engine, 'p_parent')?.unboundCause).toBeUndefined(); + }); + + it('is asked again when the CHILD changes: armed, declined, armed again', () => { + const { engine, isBound } = rig(); + engine.registerFlow('deal_review', pausingChild('deal_review')); + engine.registerFlow('c_child', asChild(flow('c_child', [call('sub', 'deal_review'), end('ok')], [['start', 'sub'], ['sub', 'ok']]))); + engine.registerFlow('p_parent', parent('p_parent', 'c_child')); + expect(isBound('p_parent'), 'the child calls the waiting flow on one branch').toBe(true); + + engine.registerFlow('c_child', asChild(concurrentCaller('c_child', 'deal_review'))); + expect(isBound('p_parent')).toBe(false); + expect(stateOf(engine, 'p_parent')?.unboundCause).toBe('suspending_subflow_on_branch'); + + engine.registerFlow('c_child', asChild(flow('c_child', [call('sub', 'deal_review'), end('ok')], [['start', 'sub'], ['sub', 'ok']]))); + expect(isBound('p_parent')).toBe(true); + }); + + it('a cycle of calls ends: two flows calling each other, neither holding the shape, arm', () => { + const { engine, isBound } = rig(); + engine.registerFlow('c_child', relay('c_child', 'p_parent')); + engine.registerFlow('p_parent', parent('p_parent', 'c_child')); + expect(isBound('p_parent')).toBe(true); + }); + + it('CONTROL: a child with one `wait` (one pausing branch, nothing after it lost) arms the parent', () => { + const { engine, isBound } = rig(); + engine.registerFlow('c_child', pausingChild('c_child')); + engine.registerFlow('p_parent', parent('p_parent', 'c_child')); + expect(isBound('p_parent')).toBe(true); + expect(stateOf(engine, 'p_parent')?.unboundCause).toBeUndefined(); + }); + + it('CONTROL: a child whose region body calls a suspending flow, the parent routing its failure through a `fault` edge, arms the parent (the region half stays one level deep)', () => { + const { engine, isBound } = rig(); + engine.registerFlow('deal_review', pausingChild('deal_review')); + const box: Node = { + id: 'box', type: 'loop', label: 'Box', + config: { collection: [1], iteratorVariable: 'item', body: { nodes: [call('inner', 'deal_review')], edges: [] } }, + }; + engine.registerFlow('c_child', flow('c_child', [box, end('ok')], [['start', 'box'], ['box', 'ok']], false)); + engine.registerFlow('p_parent', parent('p_parent', 'c_child', true)); + expect(isBound('p_parent')).toBe(true); + expect(stateOf(engine, 'p_parent')?.unboundCause).toBeUndefined(); + }); +}); diff --git a/packages/services/service-automation/src/subflow-branch-guard.ts b/packages/services/service-automation/src/subflow-branch-guard.ts new file mode 100644 index 00000000000..8dc4704bb3f --- /dev/null +++ b/packages/services/service-automation/src/subflow-branch-guard.ts @@ -0,0 +1,237 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38876] The reading behind the arming gate's branch half: does a `subflow` + * / `map` node whose child flow can suspend sit, on the top-level graph of the + * armed flow or of any flow its top-level calls reach, on a branch that loses + * work when it parks? + * + * A run parks at ONE place, and a resumed run continues from the node that + * parked, never back at the node whose out-edges led there. So two shapes + * lose work when a branch pauses (`branch-suspension-refusal.ts` measures + * both, and is the run-time door that fails such a run): + * + * - **concurrent**: two branches of one fan-out (a node's unconditional + * out-edges, run together) each reach a node that parks the run; + * - **sequential**: a conditioned or `isDefault` branch reaches one while the + * same traversal still has an edge to take after it. + * + * The flow parse refuses both shapes for the node types that ALWAYS park + * (`flow-concurrent-pause.ts` in `packages/spec`). It cannot see a `subflow` / + * `map`: whether that node parks is a fact of ANOTHER flow, which may register + * after the caller (ruling D keeps them unjudged by type). The engine holds + * the child, so it asks the SAME two readings here with a wider population — + * those types, or a `subflow` / `map` whose child can suspend + * ({@link suspendingNode}, the #28840 reading the region half reads too) — + * and {@link AutomationEngine.activateFlowTrigger} declines to arm a flow the + * readings refuse because of such a call (maintainer ruling 「38876 选 A」, + * record 7336647907: one traversal model, no engine copy). A shape the + * readings refuse with no call on it is the parse's, which never lets it + * register. + * + * [Maintainer ruling 「B 往下查到底(推荐)」, record 7360068553] The reading + * goes down the call chain: the shape held in the graph of a flow the armed + * flow calls, at any depth, declines the armed flow too, naming the flow that + * holds it and the calls that lead there. Measured before this (parent → + * child holding the shape → grandchild that waits, through `registerFlow` + + * execute): the parent armed; a concurrent shape answered `paused` and then + * failed the parent with or without a `fault` edge on its call node (the late + * failure is not routable); a sequential one failed the parent at once, or + * routed through that `fault` edge and read as success. + * + * A caller is re-judged by {@link AutomationEngine.rejudgeSubflowCallers} + * whenever a flow its calls reach is registered, so a child or grandchild + * that registers, or starts to suspend, after the caller armed un-arms it. + * Not reached here, and met only by the run-time refusal, which fails such a + * run by name: a run that starts without a trigger (this is the arming gate); + * the shape held in a flow reached only through region-body calls (a + * region-body call whose child can suspend is itself declined at arming, by + * the region half, one level deep); and a pausing node type a plugin registers. + */ + +import { + FLOW_PAUSE_CAPABLE_NODE_TYPES, + concurrentPauseRefusals, + sequentialPauseRefusals, +} from '@objectstack/spec/automation'; +import type { ConcurrentPauseRefusal, FlowParsed, FlowPauseEdgeRef, FlowPauseNodeView } from '@objectstack/spec/automation'; +import { describeSuspendingNode, suspendingNode, type FlowCallKey } from './subflow-notice-guard.js'; +import type { SuspendingNode } from './subflow-notice-guard.js'; + +/** A top-level `subflow` / `map` call whose child can suspend, on a branch that loses work when it parks. */ +export interface BranchSuspendingCall { + /** + * Which shape, as the spec reading names it: two pausing branches of one + * fan-out, the same over a `decision` without a fallback edge, or a branch + * that parks before later edges. + */ + readonly shape: ConcurrentPauseRefusal['shape']; + /** The node whose out-edges branch. */ + readonly nodeId: string; + /** Every branch the reading names: the edge it leaves `nodeId` by and the pausing nodes it reaches. */ + readonly branches: ReadonlyArray<{ readonly edge: FlowPauseEdgeRef; readonly pauses: readonly FlowPauseNodeView[] }>; + /** `sequential` only: the edges never taken once that branch parks. */ + readonly untaken: readonly FlowPauseEdgeRef[]; + /** The `subflow` / `map` node. */ + readonly callNode: { readonly id: string; readonly type: string }; + /** The flow that node calls. */ + readonly child: string; + /** Where that child can suspend. */ + readonly suspends: SuspendingNode; + /** + * The flow whose top-level graph holds the shape: the armed flow itself, or + * a flow its calls reach (maintainer ruling 「B 往下查到底(推荐)」, record + * 7360068553). + */ + readonly holder: string; + /** The call chain from the armed flow to {@link holder}, both ends included (`[holder]` when they are one flow). */ + readonly through: readonly string[]; +} + +/** The trap {@link branchSuspendingCall} reads in ONE flow's own top-level graph, before the holder is known. */ +type OwnTrap = Omit; + +/** + * The first top-level `subflow` / `map` call of `name` that the fan-out or + * sequential pause reading refuses in `name`'s OWN top-level graph, judged + * with "an always-pausing type, or a call whose child can suspend" as the + * pausing population; `undefined` when none does. + */ +function ownBranchSuspendingCall( + flows: ReadonlyMap, + name: string, + callKey?: FlowCallKey, +): OwnTrap | undefined { + const flow = flows.get(name); + if (!flow) return undefined; + const children = new Map(); + const childOf = (node: FlowPauseNodeView): { child: string; suspends: SuspendingNode | undefined } | undefined => { + if (node.type !== 'subflow' && node.type !== 'map') return undefined; + const child = (node.config as { flowName?: unknown } | undefined)?.flowName; + if (typeof child !== 'string') return undefined; + let read = children.get(node.id); + if (!read) { + const key = callKey ? callKey(name, child) : child; + read = { child, suspends: suspendingNode(flows, key, undefined, callKey) }; + children.set(node.id, read); + } + return read; + }; + const pauses = (node: FlowPauseNodeView): boolean => + FLOW_PAUSE_CAPABLE_NODE_TYPES.includes(node.type) || childOf(node)?.suspends !== undefined; + + for (const refusal of [...concurrentPauseRefusals(flow, pauses), ...sequentialPauseRefusals(flow, pauses)]) { + for (const branch of refusal.branches) { + for (const pause of branch.pauses) { + const call = childOf(pause); + if (!call?.suspends) continue; + return { + shape: refusal.shape, + nodeId: refusal.nodeId, + branches: refusal.branches, + untaken: refusal.untaken ?? [], + callNode: { id: pause.id, type: pause.type }, + child: call.child, + suspends: call.suspends, + }; + } + } + } + return undefined; +} + +/** + * The keys of the flows `name`'s top-level `subflow` / `map` nodes call, in + * declaration order, reachable from its start or not: following a call no run + * can reach is a deliberate over-approximation, the parse's any-path reading. + */ +function topLevelCallKeys(flows: ReadonlyMap, name: string, callKey?: FlowCallKey): string[] { + const nodes = (flows.get(name) as { nodes?: unknown } | undefined)?.nodes; + const keys: string[] = []; + for (const node of Array.isArray(nodes) ? nodes : []) { + const n = node as { type?: unknown; config?: { flowName?: unknown } } | null; + if (!n || (n.type !== 'subflow' && n.type !== 'map') || typeof n.config?.flowName !== 'string') continue; + keys.push(callKey ? callKey(name, n.config.flowName) : n.config.flowName); + } + return keys; +} + +/** + * The first branch trap of `name`: in its own top-level graph, else in the + * top-level graph of a flow its top-level calls reach, at any depth, depth + * first in declaration order (maintainer ruling 「B 往下查到底(推荐)」, record + * 7360068553, staged to this branch half only). Each flow is read once, keyed + * through `callKey` as a run dispatches the call, so a cycle of calls ends. + * `undefined` when no flow on the walk holds the shape. A call inside a region + * body is not followed here: the region half owns region-nested calls, one + * level deep (`subflow-region-guard.ts`). + */ +export function branchSuspendingCall( + flows: ReadonlyMap, + name: string, + callKey?: FlowCallKey, +): BranchSuspendingCall | undefined { + const seen = new Set(); + const walk = (key: string, through: readonly string[]): BranchSuspendingCall | undefined => { + if (seen.has(key)) return undefined; + seen.add(key); + if (!flows.has(key)) return undefined; + const own = ownBranchSuspendingCall(flows, key, callKey); + if (own) return { ...own, holder: key, through }; + for (const next of topLevelCallKeys(flows, key, callKey)) { + const found = walk(next, [...through, next]); + if (found) return found; + } + return undefined; + }; + return walk(name, [name]); +} + +const edgeName = (edge: FlowPauseEdgeRef): string => + edge.id !== undefined ? `'${edge.id}' ('${edge.source}' → '${edge.target}')` : `'${edge.source}' → '${edge.target}'`; + +/** + * The sentence the warn and the `/_status` reason share: the branching node, + * the branches, the call and where its child suspends, why the run would fail, + * and the move that makes the flow armable. + */ +export function describeBranchSuspendingCall(trap: BranchSuspendingCall): string { + const { shape, nodeId, branches, untaken, callNode, child, suspends, holder, through } = trap; + // Nested: the shape sits in a flow the armed flow calls; the sentence names it and the calls that lead there. + const its = through.length > 1 + ? `the flow it calls, '${holder}' (reached through ${through.map((f) => `'${f}'`).join(' → ')}): its` + : 'its'; + const call = + `\`${callNode.type}\` node '${callNode.id}' calls child flow '${child}', which can suspend the run at ` + + describeSuspendingNode(child, suspends); + const reached = branches + .map(({ edge, pauses }) => `edge ${edgeName(edge)} reaches ${pauses.map((p) => `'${p.id}'`).join(', ')}`) + .join('; '); + if (shape === 'decision_without_fallback') { + return ( + `${its} \`decision\` node '${nodeId}' declares conditions but no fallback edge (none labelled 'default' or ` + + `marked isDefault: true), and its branches reach steps that park the run (${reached}); its ${call}. A ` + + `run that matches none of the conditions takes every branch together, and a run parks at one place ` + + `only, so that run would be failed by name the first time that child suspends. Mark one of ` + + `'${nodeId}''s branch edges isDefault: true (or label it 'default'), so a run that matches no ` + + `condition takes exactly one branch` + ); + } + if (shape === 'concurrent') { + return ( + `${its} node '${nodeId}' fans out to branches that run together and that each reach a step that parks the ` + + `run (${reached}), and its ${call}. A run parks at one place only, so the run would be failed by name the ` + + `first time that child suspends, after the requests on both branches opened. Chain '${callNode.id}' and ` + + `the other pausing step one after another on a single branch` + ); + } + const [{ edge }] = branches; + return ( + `${its} node '${nodeId}' takes edge ${edgeName(edge)} before ${untaken.map(edgeName).join(', ')}, that ` + + `edge's branch reaches '${callNode.id}', and its ${call}. A resumed run continues from where it parked, ` + + `never back at '${nodeId}', so the run would be failed by name the first time that child suspends, and ` + + `the later edges would never be taken. Make that branch the last one '${nodeId}' takes, or chain the work ` + + `after it onto that branch, or, where only one of the branches should run, route them through a ` + + `\`decision\`, which takes only the first edge whose condition holds` + ); +} diff --git a/packages/services/service-automation/src/subflow-guards.ts b/packages/services/service-automation/src/subflow-guards.ts index ef71c1394ae..0a299e99660 100644 --- a/packages/services/service-automation/src/subflow-guards.ts +++ b/packages/services/service-automation/src/subflow-guards.ts @@ -20,6 +20,7 @@ import { describeTurnedOffPackagedItem } from '@objectstack/types'; import type { AutomationEngine } from './engine.js'; import { subflowNoticeTrap, transitiveSubflowCallers } from './subflow-notice-guard.js'; import { regionSuspendingCall, subflowCalls } from './subflow-region-guard.js'; +import { branchSuspendingCall } from './subflow-branch-guard.js'; import { subflowRetriedCallout } from './subflow-retry-guard.js'; /** @@ -46,6 +47,7 @@ export interface SubflowGuardsHost { readonly subflowDeclinedFlows: AutomationEngine['subflowDeclinedFlows']; readonly subflowNoticeDeclinedFlows: AutomationEngine['subflowNoticeDeclinedFlows']; readonly subflowRegionDeclinedFlows: AutomationEngine['subflowRegionDeclinedFlows']; + readonly subflowBranchDeclinedFlows: AutomationEngine['subflowBranchDeclinedFlows']; readonly subflowRetryDeclinedFlows: AutomationEngine['subflowRetryDeclinedFlows']; readonly packagedSubflowCallers: AutomationEngine['packagedSubflowCallers']; readonly deactivateFlowTrigger: AutomationEngine['deactivateFlowTrigger']; @@ -249,12 +251,13 @@ export function describeDisabledSubflows( } /** The body of {@link AutomationEngine.rejudgeSubflowCallers}; that method's docblock is its contract. */ -export function rejudgeSubflowCallers(this: Pick, subflow: string): void { +export function rejudgeSubflowCallers(this: Pick, subflow: string): void { if ( this.boundFlowTriggers.size === 0 && this.subflowDeclinedFlows.size === 0 && this.subflowNoticeDeclinedFlows.size === 0 && this.subflowRegionDeclinedFlows.size === 0 && + this.subflowBranchDeclinedFlows.size === 0 && this.subflowRetryDeclinedFlows.size === 0 ) return; const reoffered = new Set(); @@ -270,15 +273,18 @@ export function rejudgeSubflowCallers(this: Pick r.path)).toEqual([['edges', 1]]); }); }); + +/** + * [#38876] The predicate-parameterised form, one traversal model for two + * callers: the flow parse hands the always-pausing types, and the engine's + * arming gate a predicate that also counts a `subflow` / `map` whose child it + * holds can suspend (maintainer ruling 「38876 选 A」, record 7336647907). The + * parse's verdicts do not move: every case above still runs through + * `FlowSchema`, and the list form equals the predicate that reads the same + * types over every shape here. + */ +describe('the pause readings judge a type list or a node predicate over one traversal (#38876)', () => { + const X1: FlowNode = step('x1'); + const sub = (id: string, flowName = 'child'): FlowNode => ({ id, type: 'subflow', label: id, config: { flowName } }); + const suspendingChild = new Set(['child']); + /** The engine's population: an always-pausing type, or a `subflow` whose child (by name here) can suspend. */ + const withCalls = (node: { type: string; config?: unknown }): boolean => + FLOW_PAUSE_CAPABLE_NODE_TYPES.includes(node.type) + || (node.type === 'subflow' && suspendingChild.has(String((node.config as { flowName?: unknown } | undefined)?.flowName))); + const sameTypes = (node: { type: string }): boolean => FLOW_PAUSE_CAPABLE_NODE_TYPES.includes(node.type); + + const SHAPES: Flow[] = [ + flowOf([approval('a_review'), approval('b_review')], [['start', 'a_review'], ['start', 'b_review']]), + flowOf([approval('a_review'), wait('hold'), step('s1')], [['start', 's1'], ['s1', 'a_review'], ['start', 'hold']]), + flowOf([{ id: 'route', type: 'decision', label: 'Route', config: { conditions: [{ label: 'a', expression: 'x == 1' }] } }, approval('a_review'), screen('ask')], [ + ['start', 'route'], ['route', 'a_review', { label: 'a' }], ['route', 'ask', { label: 'b' }], + ]), + flowOf([X1, approval('a_review'), step('s1')], [['start', 'x1'], ['x1', 'a_review', { condition: 'true' }], ['x1', 's1', { condition: 'true' }]]), + flowOf([X1, approval('a_review'), step('s1')], [['start', 'x1'], ['x1', 'a_review', { isDefault: true }], ['x1', 's1']]), + flowOf([X1, approval('a_review'), step('s1')], [['start', 'x1'], ['x1', 's1', { condition: 'true' }], ['x1', 'a_review', { condition: 'true' }]]), + flowOf([approval('a_review'), sub('sub'), end('ok')], [['start', 'a_review'], ['start', 'sub'], ['a_review', 'ok', { label: 'approve' }]]), + ]; + + it('a type list and the predicate reading the same types give the same refusals, shape by shape', () => { + for (const flow of SHAPES) { + expect(concurrentPauseRefusals(flow, sameTypes)).toEqual(concurrentPauseRefusals(flow, FLOW_PAUSE_CAPABLE_NODE_TYPES)); + expect(sequentialPauseRefusals(flow, sameTypes)).toEqual(sequentialPauseRefusals(flow, FLOW_PAUSE_CAPABLE_NODE_TYPES)); + } + // Not vacuous: the shapes hold refusals of both readings under the list. + expect(SHAPES.flatMap((f) => concurrentPauseRefusals(f, FLOW_PAUSE_CAPABLE_NODE_TYPES)).length).toBeGreaterThan(0); + expect(SHAPES.flatMap((f) => sequentialPauseRefusals(f, FLOW_PAUSE_CAPABLE_NODE_TYPES)).length).toBeGreaterThan(0); + }); + + it('a refusal says structurally what its message says: the node, each pausing branch and what it reaches', () => { + const [refusal] = concurrentPauseRefusals(SHAPES[0], FLOW_PAUSE_CAPABLE_NODE_TYPES); + expect(refusal).toMatchObject({ + shape: 'concurrent', + nodeId: 'start', + path: ['edges', 1], + branches: [ + { edge: { id: 'e0', source: 'start', target: 'a_review' }, pauses: [{ id: 'a_review', type: 'approval' }] }, + { edge: { id: 'e1', source: 'start', target: 'b_review' }, pauses: [{ id: 'b_review', type: 'approval' }] }, + ], + }); + // A `decision` with conditions and no fallback edge is its own group: its fix keeps the routing. + const [unclaimed] = concurrentPauseRefusals(SHAPES[2], FLOW_PAUSE_CAPABLE_NODE_TYPES); + expect(unclaimed).toMatchObject({ shape: 'decision_without_fallback', nodeId: 'route' }); + expect(unclaimed.message).toContain('declares `config.conditions` but no fallback edge'); + const withFallback = flowOf([{ id: 'route', type: 'decision', label: 'Route', config: { conditions: [{ label: 'a', expression: 'x == 1' }] } }, approval('a_review'), screen('ask')], [ + ['start', 'route'], ['route', 'a_review', { label: 'a' }], ['route', 'ask', { label: 'b', isDefault: true }], + ]); + expect(concurrentPauseRefusals(withFallback, FLOW_PAUSE_CAPABLE_NODE_TYPES)).toEqual([]); + const [dropped] = sequentialPauseRefusals(SHAPES[3], FLOW_PAUSE_CAPABLE_NODE_TYPES); + expect(dropped).toMatchObject({ + shape: 'sequential', + nodeId: 'x1', + branches: [{ edge: { id: 'e1', source: 'x1', target: 'a_review' }, pauses: [{ id: 'a_review' }] }], + untaken: [{ id: 'e2', source: 'x1', target: 's1' }], + }); + }); + + it('a predicate that counts a `subflow` whose child suspends refuses the fan-out the parse accepts', () => { + const flow = flowOf([approval('a_review'), sub('sub'), end('ok'), end('ok2')], [ + ['start', 'a_review'], ['start', 'sub'], ['a_review', 'ok', { label: 'approve' }], ['sub', 'ok2'], + ]); + expect(parses(flow)).toBe(true); + expect(concurrentPauseRefusals(flow, FLOW_PAUSE_CAPABLE_NODE_TYPES)).toEqual([]); + const refusals = concurrentPauseRefusals(flow, withCalls); + expect(refusals).toHaveLength(1); + expect(refusals[0]).toMatchObject({ shape: 'concurrent', nodeId: 'start', path: ['edges', 1] }); + expect(refusals[0].branches.map((b) => b.pauses.map((p) => p.id))).toEqual([['a_review'], ['sub']]); + // The predicate is handed the node with its `config`, so it can read the child it names. + expect(concurrentPauseRefusals( + flowOf([approval('a_review'), sub('sub', 'plain'), end('ok')], [['start', 'a_review'], ['start', 'sub'], ['a_review', 'ok', { label: 'approve' }]]), + withCalls, + )).toEqual([]); + }); + + it('and the sequential twin: an earlier conditioned or `isDefault` branch into such a call, naming the edges it leaves', () => { + const conditioned = flowOf([X1, sub('sub'), step('s1'), end('ok')], [ + ['start', 'x1'], ['x1', 'sub', { condition: 'true' }], ['x1', 's1', { condition: 'true' }], ['sub', 'ok'], + ]); + const byDefault = flowOf([X1, sub('sub'), step('s1')], [['start', 'x1'], ['x1', 'sub', { isDefault: true }], ['x1', 's1']]); + for (const flow of [conditioned, byDefault]) { + expect(parses(flow)).toBe(true); + expect(sequentialPauseRefusals(flow, FLOW_PAUSE_CAPABLE_NODE_TYPES)).toEqual([]); + const [refusal, ...rest] = sequentialPauseRefusals(flow, withCalls); + expect(rest).toEqual([]); + expect(refusal).toMatchObject({ + shape: 'sequential', nodeId: 'x1', branches: [{ pauses: [{ id: 'sub', type: 'subflow' }] }], untaken: [{ target: 's1' }], + }); + } + // CONTROL: the call's branch is the last one taken. + expect(sequentialPauseRefusals( + flowOf([X1, sub('sub'), step('s1')], [['start', 'x1'], ['x1', 's1', { condition: 'true' }], ['x1', 'sub', { condition: 'true' }]]), + withCalls, + )).toEqual([]); + }); +}); diff --git a/packages/spec/src/automation/flow-concurrent-pause.ts b/packages/spec/src/automation/flow-concurrent-pause.ts index bb1506e7703..88f6970d6f9 100644 --- a/packages/spec/src/automation/flow-concurrent-pause.ts +++ b/packages/spec/src/automation/flow-concurrent-pause.ts @@ -149,11 +149,16 @@ * * ## Boundaries, declared rather than discovered * - * - The population is the caller's {@link FLOW_PAUSE_CAPABLE_NODE_TYPES}: the - * four types that park on EVERY execution. `subflow` and `map` pause only - * when the child flow they name does (a different record), and are ⛔ not - * judged by type here, by the same ruling the region rule keeps; a fan-out - * to a `subflow` whose child pauses is met only at run time. + * - The population is the caller's ({@link FlowPauseReading}). The parse + * hands {@link FLOW_PAUSE_CAPABLE_NODE_TYPES}: the four types that park on + * EVERY execution. `subflow` and `map` pause only when the child flow they + * name does (a different record), and are ⛔ not judged by type here, by + * the same ruling the region rule keeps. The engine's arming gate (#38876) + * hands a predicate instead — those four, or a `subflow` / `map` whose + * child flow it holds can suspend — and so declines to arm a flow whose + * fan-out or earlier branch reaches such a call, over this same traversal + * model, never a copy of it; a child the engine does not hold yet is met + * at run time. * - A plugin-registered pausing type is invisible to a parse (ADR-0018). * - The top-level graph only: a region body may not hold a pausing node at * all (the region rule), so a fan-out inside one cannot reach one. @@ -172,13 +177,53 @@ import { APPROVAL_NODE_TYPE, APPROVAL_REVISE_NODE_TYPE } from './approval.zod'; import { FLOW_DECISION_DEFAULT_BRANCH_LABEL } from './flow-altitude'; -/** One refusal, anchored on the edge that opens a further pausing branch. */ +/** A node as the pause readings see it: its `id`, `type` and `config`, read defensively from the parsed flow. */ +export interface FlowPauseNodeView { readonly id: string; readonly type: string; readonly config?: unknown } + +/** + * Which nodes park the run, for {@link concurrentPauseRefusals} and + * {@link sequentialPauseRefusals}: a list of node types, or a predicate over a + * node. The flow parse hands {@link FLOW_PAUSE_CAPABLE_NODE_TYPES}; the + * engine's arming gate hands "one of those types, or a `subflow` / `map` whose + * child flow can suspend", which only it can answer (#38876). One traversal + * model, judged over either population. + */ +export type FlowPauseReading = readonly string[] | ((node: FlowPauseNodeView) => boolean); + +/** An out-edge a refusal names: its `id` when it has one, its `source` and its `target`. */ +export interface FlowPauseEdgeRef { readonly id?: string; readonly source: string; readonly target: string } + +/** + * One refusal, anchored on the edge that opens a further pausing branch + * (`concurrent`, `decision_without_fallback`) or on the first branch that + * parks before later edges of its traversal (`sequential`). `path` and + * `message` are the parse issue. The other fields carry the facts a caller + * needs to compose its own sentence (the engine's arming gate): which reading + * and which group refused, the node, the branches and what each reaches, and + * the edges left untaken. They are not the message: its prescription is + * derived from `shape` and the node, never stored here. + */ export interface ConcurrentPauseRefusal { readonly path: ReadonlyArray; readonly message: string; + /** + * Which reading and group refused: `concurrent`, two pausing branches among a + * node's out-edges that run together; `decision_without_fallback`, the same + * reading over a `decision` that declares `config.conditions` and no fallback + * edge, whose branches run together only on a run matching none of them + * (its fix keeps the routing: mark one branch edge `isDefault: true`); + * `sequential`, a branch that parks before later edges of its traversal. + */ + readonly shape: 'concurrent' | 'decision_without_fallback' | 'sequential'; + /** The node whose out-edges are read. */ + readonly nodeId: string; + /** Each branch that reaches a pausing node: the edge it leaves `nodeId` by, and the pausing nodes it reaches. */ + readonly branches: ReadonlyArray<{ readonly edge: FlowPauseEdgeRef; readonly pauses: readonly FlowPauseNodeView[] }>; + /** `sequential` only: the edges of the same traversal that are never taken after that branch parks. */ + readonly untaken?: readonly FlowPauseEdgeRef[]; } -interface NodeView { readonly id: string; readonly type: string; readonly config?: unknown } +type NodeView = FlowPauseNodeView; interface EdgeView { readonly index: number; readonly id?: string; @@ -263,6 +308,15 @@ function concurrentGroups(node: NodeView, outEdges: readonly EdgeView[]): Concur return groups; } +const edgeRef = (edge: EdgeView): FlowPauseEdgeRef => + ({ ...(edge.id !== undefined ? { id: edge.id } : {}), source: edge.source, target: edge.target }); + +/** `pauses` as a predicate over a node, the one form the walk reads. */ +function pausePredicate(pauses: FlowPauseReading): (node: NodeView) => boolean { + if (typeof pauses === 'function') return pauses; + return (node) => pauses.includes(node.type); +} + const named = (edge: EdgeView): string => edge.id !== undefined ? `\`${edge.id}\` (\`${edge.source}\` → \`${edge.target}\`)` : `\`${edge.source}\` → \`${edge.target}\``; @@ -274,10 +328,10 @@ interface PauseGraph { readonly pausesFrom: (target: string) => NodeView[]; } -/** `flow`'s top-level graph, or `undefined` when no node of `pauseCapableTypes` is in it (nothing to judge). */ -function pauseGraph(flow: { nodes?: unknown; edges?: unknown }, pauseCapableTypes: readonly string[]): PauseGraph | undefined { +/** `flow`'s top-level graph, or `undefined` when no node of it pauses by `isPause` (nothing to judge). */ +function pauseGraph(flow: { nodes?: unknown; edges?: unknown }, isPause: (node: NodeView) => boolean): PauseGraph | undefined { const nodes = (Array.isArray(flow.nodes) ? flow.nodes : []).map(nodeView).filter((n) => n !== undefined); - if (!nodes.some((n) => pauseCapableTypes.includes(n.type))) return undefined; + if (!nodes.some(isPause)) return undefined; const byId = new Map(nodes.map((n) => [n.id, n] as const)); const outEdges = new Map(); (Array.isArray(flow.edges) ? flow.edges : []).forEach((raw, index) => { @@ -298,7 +352,7 @@ function pauseGraph(flow: { nodes?: unknown; edges?: unknown }, pauseCapableType seen.add(id); const node = byId.get(id); if (!node) continue; - if (pauseCapableTypes.includes(node.type)) { + if (isPause(node)) { found.push(node); continue; } @@ -311,15 +365,16 @@ function pauseGraph(flow: { nodes?: unknown; edges?: unknown }, pauseCapableType /** * Every fan-out of `flow`'s top-level graph whose concurrent edges lead two or - * more branches to a node whose type is in `pauseCapableTypes`, one refusal per - * fan-out group, anchored at the second such branch's edge. + * more branches to a node that pauses by `pauses` (a type list or a predicate, + * {@link FlowPauseReading}), one refusal per fan-out group, anchored at the + * second such branch's edge. */ export function concurrentPauseRefusals( flow: { nodes?: unknown; edges?: unknown }, - pauseCapableTypes: readonly string[], + pauses: FlowPauseReading, ): ConcurrentPauseRefusal[] { const out: ConcurrentPauseRefusal[] = []; - const graph = pauseGraph(flow, pauseCapableTypes); + const graph = pauseGraph(flow, pausePredicate(pauses)); if (!graph) return out; const { nodes, outEdges, pausesFrom } = graph; @@ -331,11 +386,17 @@ export function concurrentPauseRefusals( .filter((branch) => branch.pauses.length > 0); if (pausing.length < 2) continue; const branches = pausing - .map(({ edge, pauses }) => - `edge ${named(edge)} reaches ${pauses.map((p) => `\`${p.id}\` (\`${p.type}\`)`).join(', ')}`) + .map(({ edge, pauses: reached }) => + `edge ${named(edge)} reaches ${reached.map((p) => `\`${p.id}\` (\`${p.type}\`)`).join(', ')}`) .join('; '); + const structured = { + shape: unclaimedDefault ? 'decision_without_fallback' as const : 'concurrent' as const, + nodeId: node.id, + branches: pausing.map(({ edge, pauses: reached }) => ({ edge: edgeRef(edge), pauses: reached })), + }; if (unclaimedDefault) { out.push({ + ...structured, path: ['edges', pausing[1].edge.index], message: `Decision \`${node.id}\` declares \`config.conditions\` but no fallback edge — none of its out-edges is ` @@ -352,6 +413,7 @@ export function concurrentPauseRefusals( continue; } out.push({ + ...structured, path: ['edges', pausing[1].edge.index], message: `Node \`${node.id}\` fans out to concurrent branches that each reach a node that parks the run — ` @@ -431,16 +493,17 @@ function awaitedBefore(node: NodeView, pass: readonly EdgeView[]): Array<{ edge: /** * Every node of `flow`'s top-level graph that takes an out-edge reaching a - * node whose type is in `pauseCapableTypes` BEFORE other out-edges of the same - * traversal, which then never run (#38875). One refusal per traversal pass, - * anchored at the first such edge, naming the edges it leaves untaken. + * node that pauses by `pauses` (a type list or a predicate, + * {@link FlowPauseReading}) BEFORE other out-edges of the same traversal, + * which then never run (#38875). One refusal per traversal pass, anchored at + * the first such edge, naming the edges it leaves untaken. */ export function sequentialPauseRefusals( flow: { nodes?: unknown; edges?: unknown }, - pauseCapableTypes: readonly string[], + pauses: FlowPauseReading, ): ConcurrentPauseRefusal[] { const out: ConcurrentPauseRefusal[] = []; - const graph = pauseGraph(flow, pauseCapableTypes); + const graph = pauseGraph(flow, pausePredicate(pauses)); if (!graph) return out; const { nodes, outEdges, pausesFrom } = graph; @@ -449,17 +512,21 @@ export function sequentialPauseRefusals( for (const pass of traversalPasses(node, outEdges.get(node.id) ?? [])) { for (const { edge, after } of awaitedBefore(node, pass)) { if (after.length === 0) continue; - const pauses = pausesFrom(edge.target); - if (pauses.length === 0) continue; + const reached = pausesFrom(edge.target); + if (reached.length === 0) continue; // The first pausing edge of the pass leaves every edge after it untaken; one refusal says so. if (anchored.has(edge.index)) break; anchored.add(edge.index); const inclusive = node.type === 'decision' && !takesFirstConditionOnly(node); out.push({ + shape: 'sequential', + nodeId: node.id, + branches: [{ edge: edgeRef(edge), pauses: reached }], + untaken: after.map(edgeRef), path: ['edges', edge.index], message: `Node \`${node.id}\` takes edge ${named(edge)} before ${after.map(named).join(', ')}, and that edge's ` - + `branch reaches ${pauses.map((p) => `\`${p.id}\` (\`${p.type}\`)`).join(', ')}, a node that parks the ` + + `branch reaches ${reached.map((p) => `\`${p.id}\` (\`${p.type}\`)`).join(', ')}, a node that parks the ` + 'run. The engine takes a node\'s conditioned out-edges one after another in the order they are ' + 'declared, then its `isDefault` edge when no condition held, then its unconditional edges together; ' + `when the run parks inside an earlier branch it later resumes from the node it parked at, never back at ` diff --git a/packages/spec/src/automation/index.ts b/packages/spec/src/automation/index.ts index e5e66b53e93..30d344ce191 100644 --- a/packages/spec/src/automation/index.ts +++ b/packages/spec/src/automation/index.ts @@ -108,6 +108,10 @@ export * from './flow-text-slot-template'; // option-collision parse refusal, `translateFlow`, the reference lint and the // i18n extractor alike. export * from './flow-screen-option-key'; +// [#38876] The fan-out / sequential pause readings, over a type list or a node +// predicate: the flow parse judges the always-pausing types, and the engine's +// arming gate the same traversal with a `subflow` / `map` whose child suspends. +export * from './flow-concurrent-pause'; // [#35928] The record-change trigger's token grammar — the one reading of a // `triggerType` the trigger binds by and the record-update preview asks. export * from './record-change-trigger-events'; diff --git a/packages/spec/src/contracts/automation-service.test.ts b/packages/spec/src/contracts/automation-service.test.ts index 72bbef566c7..b8b9771da0c 100644 --- a/packages/spec/src/contracts/automation-service.test.ts +++ b/packages/spec/src/contracts/automation-service.test.ts @@ -69,7 +69,7 @@ export type FlowRuntimeStateUnboundCauseIsTheClosedTuple = Assert< */ export type FlowRuntimeStateCarriesAnOptionalPackageId = Assert>; export type FlowUnboundCauseIsTheTupleUnion = Assert< - Eq + Eq >; describe('Automation Service Contract', () => { diff --git a/packages/spec/src/contracts/automation-service.ts b/packages/spec/src/contracts/automation-service.ts index efcb8e29f89..60d68f7af65 100644 --- a/packages/spec/src/contracts/automation-service.ts +++ b/packages/spec/src/contracts/automation-service.ts @@ -1102,6 +1102,25 @@ export interface FlowRuntimeState { * at the region boundary the first time that child suspends. Author remedy: * move the call onto the top-level graph, or republish the child without a * node that suspends, and the flow arms. + * - `suspending_subflow_on_branch` — the arming gate declined the flow because, + * on its top-level graph or that of any flow its top-level calls reach (at + * any depth; the reason names that flow and the calls that lead there), a + * `subflow` / `map` node whose child flow can suspend sits on a branch that + * loses work when it parks (#38876): two + * branches of one fan-out (a node's unconditional out-edges, which run + * together) each reach a node that parks the run, one of them such a call; + * or a conditioned or `isDefault` branch reaches such a call while the same + * traversal still has an edge to take after it. A run parks at one place and + * resumes from it, never back at the node that branched, so the run would be + * failed by the engine's branch refusal the first time that child suspends, + * after its request opened. The same traversal the flow parse refuses for the + * node types that always park (`flow-concurrent-pause.ts`), judged with the + * child in hand. Author remedy: chain the call and the other pausing step + * onto one branch, or make the call's branch the last one its node takes, + * or route alternatives through a `decision`; for a `decision` that declares + * conditions but no fallback edge (its branches run together only on a run + * matching none of them), mark one branch edge `isDefault: true`; or + * republish the child without a node that suspends, and the flow arms. * - `retried_callout_in_subflow` — the arming gate declined the flow because it * runs after a record change and a `subflow` / `map` node of it reaches a * child flow holding an inline outbound call (`http` without `durable: true`, @@ -1121,6 +1140,7 @@ export const FLOW_UNBOUND_CAUSES = [ 'disabled_subflow', 'notice_after_suspending_subflow', 'suspending_subflow_in_region', + 'suspending_subflow_on_branch', 'retried_callout_in_subflow', 'missing_trigger', 'binding_failure', diff --git a/packages/spec/src/migrations/entries/semantic/19.flow-branch-suspending-subflow-not-armed.ts b/packages/spec/src/migrations/entries/semantic/19.flow-branch-suspending-subflow-not-armed.ts new file mode 100644 index 00000000000..4c4a3de93a2 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/19.flow-branch-suspending-subflow-not-armed.ts @@ -0,0 +1,68 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// A trigger-declaring flow whose fan-out or earlier branch reaches a `subflow` +// / `map` whose child flow can suspend is registered but no longer armed. A +// structured TODO, not a D2 conversion: whether the author meant every branch +// to run (then the call goes last, or the steps are chained) or only one (then +// a `decision` chooses) is not recorded, and the platform does not guess. +export const entry: SemanticMigration = { + id: 'flow-branch-suspending-subflow-not-armed', + surface: + 'Every flow that declares a trigger (a record-change, schedule or other triggered start), judged by the ' + + 'automation engine when the trigger activates it and again whenever a flow its calls reach is ' + + 'registered, over its own top-level graph AND the top-level graph of every flow its top-level `subflow` ' + + '/ `map` calls reach, at any depth: a `subflow` or `map` node whose child flow (the flow its ' + + '`config.flowName` names, as registered) can suspend the run — the child reaches an `approval`, ' + + '`approval_revise`, `screen` or `wait` node from its start, or a top-level call of its own whose child ' + + 'can, transitively — sitting on a branch of the two shapes the flow parse already refuses for those ' + + 'four node types: (1) two or more of a node\'s unconditional out-edges (run together) each reach a node ' + + 'that parks the run, that call among them; (2) a conditioned or `isDefault` out-edge reaches that call ' + + 'while the engine would take another out-edge of the same node after it in the same traversal. The ' + + 'same traversal as `flow-concurrent-branch-durable-pause-refused` and ' + + '`flow-sequential-branch-durable-pause-refused`, with the call counted as a node that parks the run. A ' + + 'called flow need not declare a trigger of its own: the shape in it declines the trigger-declaring flow ' + + 'that calls it. A call inside a region body is the region decline\'s (`suspending_subflow_in_region`, ' + + 'one level deep), not this one.', + replacement: + 'Where every branch should run, chain the call and the other pausing step one after another on a single ' + + 'branch, or make the call\'s branch the LAST one its node takes (declare its edge after its conditioned ' + + 'siblings, with no unconditional sibling beside it), so the work after the pause runs on resume. Where ' + + 'only one branch should run, route them through a `decision` (exclusive by default) whose fallback edge ' + + 'is marked `isDefault: true`. Or republish the child without a node that suspends. The flow arms the ' + + 'moment the shape is gone; nothing else is needed. For a `decision` that declares `config.conditions` but ' + + 'no fallback edge, the fix that keeps the routing is to mark one of its branch edges `isDefault: true` (or ' + + 'label it `default`), so a run that matches no condition takes exactly one branch.', + reason: + 'A run parks at ONE place, and a resumed run continues from the node that parked, never back at the node ' + + 'whose out-edges led there. The engine already fails such a run at run time, by name (the branch ' + + 'refusal), but only after it has opened the child\'s request, which is then left pending. Since the ' + + 'engine holds the child flow, the arming gate now asks the parse\'s own two readings (fan-out and ' + + 'sequential) with a call whose child can suspend counted as a pausing node, and declines to arm the ' + + 'flow, by the maintainer\'s ruling: one traversal model, no engine copy. The flow parse still ' + + 'accepts the flow, because whether the call suspends is a fact of another record (ruling D), so it ' + + 'still registers and saves; only its trigger is not armed. A flow that armed before and has this shape ' + + 'stops arming: this is a narrowing. ⛔ NOT losslessly convertible: the rewrite is a graph rewrite whose ' + + 'intended shape no artifact records, so this is a D3 structured TODO. Reached by this gate: a flow is ' + + 're-judged whenever a flow its calls reach is registered, so an armed flow is un-armed when a child it ' + + 'calls is registered, or republished, with a node that suspends. Not reached by it, and met at run time ' + + 'only, where the engine fails the run by name: a run started without a trigger (this is the arming ' + + 'gate); the shape held in a flow reached only through calls inside region bodies (this reading follows ' + + 'top-level calls; a region-body call whose child can suspend is itself declined at arming, by the region ' + + 'decline, one level deep); and a pausing node type contributed by a plugin, invisible to both. The gate reads the whole call chain because, measured, ' + + 'a calling flow whose child holds the concurrent shape answers `paused` and is failed afterwards even ' + + 'with a `fault` edge on its call node (not routable, and lost unsaid if the engine restarts in that ' + + 'window), while the sequential shape fails it at once or routes through that `fault` edge as a success.', + acceptanceCriteria: + 'No trigger-declaring flow of the stack, and no flow its top-level calls reach at any depth, has a ' + + 'top-level `subflow` / `map` node whose child can suspend on a fan-out beside another branch that reaches a pausing node, or on a conditioned / `isDefault` branch ' + + 'that the engine takes before another out-edge of the same node. `GET /api/v1/automation/_status` (and ' + + 'the engine\'s trigger binding audit) shows every such flow `bound: true`; a flow still carrying the ' + + 'shape reads `enabled: true, bound: false, unboundCause: \'suspending_subflow_on_branch\'`, with a ' + + '`reason` naming the branching node, the call node, the child and where it suspends (and, when the ' + + 'shape is in a called flow, that flow and the calls that lead to it), and the engine ' + + 'logs one `warn` (`Flow \'…\' is registered but NOT armed on trigger \'…\' — …`). Behaviour to re-check ' + + 'after the rewrite, because it changes on purpose: the branch that used to be dropped now runs (before ' + + 'the pause, or after it on resume), or a `decision` now takes exactly one branch.', +}; diff --git a/scripts/tenant-audit-census.mjs b/scripts/tenant-audit-census.mjs index 5fb0533bb66..ca7bb3dbbfa 100644 --- a/scripts/tenant-audit-census.mjs +++ b/scripts/tenant-audit-census.mjs @@ -1781,6 +1781,12 @@ export const UNTYPED_RECEIVERS = [ engine: false, what: 'the automation engine\'s own in-memory `Map` field `subflowRegionDeclinedFlows` (`AutomationEngine[\'subflowRegionDeclinedFlows\']`, read through the facet host) -- `delete(key)` drops an entry from it', }, + { + file: 'packages/services/service-automation/src/engine-enablement-facet.ts', + receiver: 'this.subflowBranchDeclinedFlows', + engine: false, + what: 'the automation engine\'s own in-memory `Map` field `subflowBranchDeclinedFlows` (`AutomationEngine[\'subflowBranchDeclinedFlows\']`, read through the facet host) -- `delete(key)` drops an entry from it', + }, { file: 'packages/services/service-automation/src/engine-enablement-facet.ts', receiver: 'this.subflowRetryDeclinedFlows', diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/flow-problems.ts b/ui/packages/app-shell/src/views/metadata-admin/previews/flow-problems.ts index eadf661e958..04e19862c3f 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/flow-problems.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/flow-problems.ts @@ -501,6 +501,7 @@ const UNBOUND_CAUSE_KEYS: Readonly> = { disabled_subflow: 'engine.studio.auto.unboundCause.disabled_subflow', notice_after_suspending_subflow: 'engine.studio.auto.unboundCause.notice_after_suspending_subflow', suspending_subflow_in_region: 'engine.studio.auto.unboundCause.suspending_subflow_in_region', + suspending_subflow_on_branch: 'engine.studio.auto.unboundCause.suspending_subflow_on_branch', retried_callout_in_subflow: 'engine.studio.auto.unboundCause.retried_callout_in_subflow', missing_trigger: 'engine.studio.auto.unboundCause.missing_trigger', binding_failure: 'engine.studio.auto.unboundCause.binding_failure', diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index 66a931a27c0..eb43937127f 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -2861,6 +2861,8 @@ const STUDIO_EN: Record = { 'A save notice in this flow comes after a subflow that can pause, so this flow does not start. Move the save notice ahead of that step, or use a notify step.', 'engine.studio.auto.unboundCause.suspending_subflow_in_region': 'A subflow inside a loop, parallel branch or error handler calls a flow that can pause, so this flow does not start. Move that call onto the main path of the flow.', + 'engine.studio.auto.unboundCause.suspending_subflow_on_branch': + 'A subflow that calls a flow that can pause sits on a branch that runs beside another pausing step, or before other branches of the same step, so work would be lost when it pauses. This flow does not start. Chain those steps onto one branch, or make that branch the last one taken.', 'engine.studio.auto.unboundCause.retried_callout_in_subflow': 'This flow runs after a record is saved, and a subflow it calls retries a call to an outside service, so a save could wait through every retry. This flow does not start. In that subflow, send the request in the background or remove the retry.', 'engine.studio.auto.unboundCause.missing_trigger': diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index b759c452128..9015bce5545 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -2562,6 +2562,8 @@ const STUDIO_ZH: Record = { '该流程中的保存提示位于一个可能暂停的子流程之后,所以该流程不会启动。把保存提示移到那一步之前,或改用通知步骤。', 'engine.studio.auto.unboundCause.suspending_subflow_in_region': '循环、并行分支或异常处理里的子流程调用了一个可能暂停的流程,所以该流程不会启动。把这个调用移到流程的主路径上。', + 'engine.studio.auto.unboundCause.suspending_subflow_on_branch': + '一个调用了可能暂停的流程的子流程,位于与另一个暂停步骤并行的分支上,或位于同一步骤其他分支之前,暂停时会丢失后面的工作,所以该流程不会启动。把这些步骤串到同一条分支上,或让这条分支最后执行。', 'engine.studio.auto.unboundCause.retried_callout_in_subflow': '该流程在记录保存后运行,而它调用的子流程会重试对外部服务的调用,保存可能要等完所有重试,所以该流程不会启动。在那个子流程里改为后台发送请求,或去掉重试。', 'engine.studio.auto.unboundCause.missing_trigger':