diff --git a/.changeset/33019-flow-answer-delegated-dropped-fields.md b/.changeset/33019-flow-answer-delegated-dropped-fields.md new file mode 100644 index 00000000000..8c58928edca --- /dev/null +++ b/.changeset/33019-flow-answer-delegated-dropped-fields.md @@ -0,0 +1,13 @@ +--- +'@objectstack/spec': patch +'@objectstack/service-automation': patch +--- + +fix(automation): a flow's answer also names the read-only fields its `map` items and its paused-then-resumed `subflow` children dropped + +Clause-②: yes (widening) +Metadata-protocol: none + +- **`@objectstack/service-automation`**: the run answer's `droppedFields` (#32861) now rolls up every child run that `summary` credits on completion. A `map` node folds the drop events of each item that completed, on its synchronous exit and on the exit that pauses; a `subflow` or `map` child that paused and then completed hands its drop events to the parent's awaiting step, whether the caller resumed the parent (the delegated leg) or the child's own run id (the up-bubble). This lifts the delegated limit #32861's note states for those two shapes. One fold serves every leg, one event per object and reason as before. +- The fold is now total: a list or event that is not well-typed (a host-registered executor's malformed `droppedFields`) is skipped, and a completed run is never turned into a failed or retried one over it. +- **`@objectstack/spec`**: the `AutomationResult.droppedFields` jsdoc and the `TriggerFlowResponseSchema.data.droppedFields` describe state the rule as built. What remains: a child run that failed answers no drops, so where a `try_catch` or `fault` edge contains that failure an absent member is not proof the failed child dropped nothing; and a `map` item whose paused run an operator cancelled answers none either (the map goes on with the cancelled marker in that item's `results` slot). The member's shape is unchanged. diff --git a/content/docs/references/api/automation-api.mdx b/content/docs/references/api/automation-api.mdx index 841f608deba..732dfca51c7 100644 --- a/content/docs/references/api/automation-api.mdx +++ b/content/docs/references/api/automation-api.mdx @@ -1141,7 +1141,7 @@ const result = AutomationApiErrorCode.parse(data); | **flowLabel** | `string` | optional | The flow definition's authored `label`, copied verbatim so a runner can name the flow (header, completion toast) and translate it against `flows..label`. Set on every result of an evaluation of a registered flow (paused and terminal alike); absent on a refusal carrying `code`. For a subflow chain it is the addressed (parent) run's flow. Never defaulted to the API name | | **refusalMessage** | `string` | optional | Rendered refusal, set when `status` is `refused` - the `end` node's `message` template interpolated against the run's variables, so it names the record. Authored per-record text (not a flow-level copy like the two above); absent on every other status. A runner shows it with Close only | | **summary** | `{ selected: integer; acted: integer; skipped: integer; unmeasured?: integer; … }` | optional | What the run did - records selected / acted on, gate skips, per-node status. Set on a TERMINAL result (a paused run has not finished doing it yet). | -| **droppedFields** | `{ object: string; fields: string[]; reason: Enum<'readonly' \| 'readonly_when' \| 'primary_key' \| 'computed' \| 'stored_expression'> }[]` | optional | Caller-supplied field values a write step of the run did not store (e.g. a `readonly` field an `update_record` step wrote): the data engine's own drop events, one per object and reason in first-seen order; a field named means at least one write dropped it, not every write. The steps still succeeded and the run's outcome is unchanged - this tells the caller which values never landed. Set on a terminal success only, and only when a field was dropped. Delegated writes: a `subflow` child that completes without pausing rolls its drops up here; a child that paused, and a `map` item's run, do not yet, so an absent member is not proof that a delegated write dropped nothing. | +| **droppedFields** | `{ object: string; fields: string[]; reason: Enum<'readonly' \| 'readonly_when' \| 'primary_key' \| 'computed' \| 'stored_expression'> }[]` | optional | Caller-supplied field values a write step of the run did not store (e.g. a `readonly` field an `update_record` step wrote): the data engine's own drop events, one per object and reason in first-seen order; a field named means at least one write dropped it, not every write. The steps still succeeded and the run's outcome is unchanged - this tells the caller which values never landed. Set on a terminal success only, and only when a field was dropped. Delegated writes roll up here too: a `subflow` child's run and each `map` item's run, whether it completed without pausing or paused and resumed. A child run that failed answers no drops, so where a `try_catch` or `fault` edge contains that failure an absent member is not proof the failed child dropped nothing. A `map` item whose paused run an operator cancelled answers none either (its slot in `results` holds the cancelled marker). | --- diff --git a/packages/services/service-automation/src/builtin/map-node.ts b/packages/services/service-automation/src/builtin/map-node.ts index 2b3656173a5..a6ab215e4c8 100644 --- a/packages/services/service-automation/src/builtin/map-node.ts +++ b/packages/services/service-automation/src/builtin/map-node.ts @@ -6,6 +6,7 @@ import type { MapConfigParsed } from '@objectstack/spec/automation'; import type { AutomationContext } from '@objectstack/spec/contracts'; import type { AutomationEngine } from '../engine.js'; import { refuseNode } from '../guard-refusal.js'; +import { foldDropEvents } from '../run-dropped-fields.js'; import { carriedRefusalOfResult } from '../inner-refusal.js'; import { parseNodeConfig } from './parse-config.js'; import { collectionNotAList, resolveCollectionSlot, resolveValueSlotMap } from './value-slot-map.js'; @@ -206,6 +207,19 @@ export function registerMapNode(engine: AutomationEngine, ctx: PluginContext): v let failures = 0; let failuresTracked = false; const rolledFailures = (): { failures?: number } => (failuresTracked ? { failures } : {}); + // #33019 — the drop events of the items that COMPLETED during this + // entry, rolled onto this step beside their totals and through the one + // fold, so the parent's answer (`AutomationResult.droppedFields`, folded + // from its steps) names a value an item's write did not store. Same + // per-entry rule as the totals: a PAUSED item's drops are credited to + // this step by the engine when its run bubbles back + // (AutomationEngine.creditChildRun). A failed or refused item's answer + // carries none. + const itemDrops: unknown[] = []; + const rolledDrops = () => { + const droppedFields = foldDropEvents(itemDrops); + return droppedFields ? { droppedFields } : {}; + }; // Drive items in order. Synchronous items advance inline; a pausing item // suspends the run and is resumed via re-entry. @@ -261,6 +275,7 @@ export function registerMapNode(engine: AutomationEngine, ctx: PluginContext): v // item's own totals to this same step when its child run bubbles // back (AutomationEngine.creditChildRun). metrics: { selected, acted, ...(unmeasured ? { unmeasuredEffect: true } : {}), ...rolledFailures() }, + ...rolledDrops(), }; } if (!child.success) { @@ -287,6 +302,10 @@ export function registerMapNode(engine: AutomationEngine, ctx: PluginContext): v ...(unmeasured || child.summary?.unmeasured ? { unmeasuredEffect: true } : {}), ...rolledFailures(), }, + // The items that completed before it keep their drops too: a + // `try_catch` or `fault` edge that contains this failure lets the + // run complete, and its answer folds this step. + ...rolledDrops(), }; } if (child.status === 'refused') { @@ -330,6 +349,7 @@ export function registerMapNode(engine: AutomationEngine, ctx: PluginContext): v ? { failures: failures + child.summary.failed } : rolledFailures()), }, + ...rolledDrops(), }; } // Synchronous completion — record and advance. @@ -340,6 +360,7 @@ export function registerMapNode(engine: AutomationEngine, ctx: PluginContext): v // One uncountable effect anywhere in the batch makes the batch's // `acted` incomplete — the flag rides out with this entry's metrics. if (child.summary?.unmeasured) unmeasured = true; + itemDrops.push(child.droppedFields); // #15617 — this item went on and contained its failures, so they are // this run's to answer for. `undefined` is "the child tracked no // count", so it neither adds nor flips the presence bit. @@ -379,6 +400,7 @@ export function registerMapNode(engine: AutomationEngine, ctx: PluginContext): v // slot in `results` but is never counted as a run (#27971). output: { results: state.results, count: state.results.filter(r => !isMapItemCancelledMarker(r)).length }, metrics: { selected, acted, ...(unmeasured ? { unmeasuredEffect: true } : {}), ...rolledFailures() }, + ...rolledDrops(), }; }, }); diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index f8c74eba373..5aa9bdaf19e 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -8573,10 +8573,21 @@ export class AutomationEngine implements IAutomationService { * `!childRes.success` before reaching here — which is what lets #15617's * `failures` ride this seam under exactly its declared rule: the contained * failures of a child that COMPLETED, never a failed child's own `failed`. + * + * #33019 — the same seam carries the child's `droppedFields` (its own + * answer's), folded onto that awaiting step through the one fold + * (`foldDropEvents`), so the parent's terminal answer — folded from its + * steps — reports a paused child's or a `map` item's dropped values + * wherever this method credits its totals. A failed child answers none. */ - private creditChildRun(steps: StepLogEntry[], nodeId: string, child: FlowRunSummary | undefined): void { + private creditChildRun( + steps: StepLogEntry[], + nodeId: string, + child: FlowRunSummary | undefined, + childDroppedFields?: readonly DroppedFieldsEvent[], + ): void { // The body lives in ./run-resume.ts (#25222). - creditChildRun(steps, nodeId, child); + creditChildRun(steps, nodeId, child, childDroppedFields); } /** @@ -8592,6 +8603,11 @@ export class AutomationEngine implements IAutomationService { * because it is engine-internal control flow, not data the parent's * variable map should ever see — the reserved-name guard * (`applyResumeSignal`) polices that map, and a refusal is not a variable. + * @param childDroppedFields - #33019: the drop events of the child run + * whose completion triggered this resume (the up-bubble path), folded + * onto the awaiting step beside `childSummary`. A parameter for the same + * reason: the parent's answer reads them from its steps, never from its + * variable map. */ private resumeInternal( runId: string, @@ -8604,6 +8620,7 @@ export class AutomationEngine implements IAutomationService { skipBubble: boolean, childSummary?: FlowRunSummary, childRefusal?: ChildRunRefusal, + childDroppedFields?: readonly DroppedFieldsEvent[], ): Promise { // The body lives in ./run-resume.ts (#25222). const host: ThisParameterType = { @@ -8635,7 +8652,7 @@ export class AutomationEngine implements IAutomationService { failAncestors: (...a) => this.failAncestors(...a), renderFlowTerminalMessage: (...a) => this.renderFlowTerminalMessage(...a), }; - return resumeInternal.call(host, runId, signal, skipBubble, childSummary, childRefusal); + return resumeInternal.call(host, runId, signal, skipBubble, childSummary, childRefusal, childDroppedFields); } /** @@ -8807,6 +8824,11 @@ export class AutomationEngine implements IAutomationService { * control flow, not a variable. */ refusal?: ChildRunRefusal, + /** + * #33019 — this child's drop events (the ones its own terminal answer + * carries), credited to the parent's awaiting step beside `summary`. + */ + droppedFields?: readonly DroppedFieldsEvent[], ): Promise { const ctx = run.context as Record | undefined; const parentRunId = ctx?.$parentRunId; @@ -8821,7 +8843,7 @@ export class AutomationEngine implements IAutomationService { // the one writer allowed to set them (#3853 follow-up). ? engineBuilt({ variables: { [`${mapNode}.$mapItemOutput`]: output ?? null, [`${mapNode}.$mapItemDone`]: true } }) : this.buildSubflowResumeSignal(run.context, output); - const parentRes = await this.resumeInternal(parentRunId, sig, false, summary, refusal); + const parentRes = await this.resumeInternal(parentRunId, sig, false, summary, refusal, droppedFields); if (!parentRes.success) { // #6499 — `parentRes.error` is the envelope field that carries // a failing node's / driver's text VERBATIM (#5912 left it diff --git a/packages/services/service-automation/src/run-dropped-fields.test.ts b/packages/services/service-automation/src/run-dropped-fields.test.ts index 931c364a922..b510f64e40f 100644 --- a/packages/services/service-automation/src/run-dropped-fields.test.ts +++ b/packages/services/service-automation/src/run-dropped-fields.test.ts @@ -21,7 +21,8 @@ import type { NodeExecutor, StepLogEntry } from './engine.js'; import { InMemorySuspendedRunStore } from './suspended-run-store.js'; import { registerCrudNodes } from './builtin/crud-nodes.js'; import { registerSubflowNode } from './builtin/subflow-node.js'; -import { dropEventsOf } from './run-dropped-fields.js'; +import { registerMapNode } from './builtin/map-node.js'; +import { dropEventsOf, foldDropEvents } from './run-dropped-fields.js'; type Drop = { object: string; fields: string[]; reason: 'readonly' | 'readonly_when' | 'primary_key' | 'computed' | 'stored_expression' }; @@ -56,9 +57,40 @@ function makeEngine() { const engine = new AutomationEngine(logger, new InMemorySuspendedRunStore()); registerCrudNodes(engine, ctx); registerSubflowNode(engine, ctx); + registerMapNode(engine, ctx); + engine.registerNodeExecutor({ + type: 'hold', + descriptor: defineActionDescriptor({ type: 'hold', version: '1.0.0', name: 'Hold', supportsPause: true, resumeAuthority: 'any' }), + async execute() { return { success: true, suspend: true, correlation: 'held' }; }, + } as NodeExecutor); return engine; } +/** `start → NODES… → end`, edges in order. */ +function chain(name: string, nodes: Array>) { + const all = [{ id: 'start', type: 'start', label: 'Start' }, ...nodes, { id: 'end', type: 'end', label: 'End' }]; + return { + name, label: name, type: 'autolaunched', runAs: 'user', + nodes: all, + edges: all.slice(1).map((n, i) => ({ id: `e${i}`, source: all[i].id, target: n.id })), + } as never; +} + +/** A child that pauses FIRST and writes the read-only `status` only once resumed. */ +const PAUSE_THEN_SUBMIT = chain('pause_then_submit', [ + { id: 'hold', type: 'hold', label: 'Hold' }, + { id: 'submit', type: 'update_record', label: 'Submit', config: { objectName: 'expense_report', filter: { id: 'r1' }, fields: { status: 'submitted' } } }, +]); + +const STATUS_DROP = [{ object: 'expense_report', fields: ['status'], reason: 'readonly' }]; + +/** The child run a parent parked on its `subflow` / `map` node waits for. */ +async function childRunOf(engine: AutomationEngine, parentRunId: string, prefix: 'subflow:' | 'map:'): Promise { + const parked = await engine.suspensionOf(parentRunId); + expect(parked?.correlation?.startsWith(prefix)).toBe(true); + return parked!.correlation!.slice(prefix.length); +} + /** start → update_record(expense_report, `fields`) → end: the #32666 shape. */ function submitFlow(name: string, fields: Record) { return { @@ -124,11 +156,6 @@ describe('AutomationResult.droppedFields (#32861)', () => { it('a drop before a pause reaches the answer the resumed run finally gives', async () => { const engine = makeEngine(); - engine.registerNodeExecutor({ - type: 'hold', - descriptor: defineActionDescriptor({ type: 'hold', version: '1.0.0', name: 'Hold', supportsPause: true, resumeAuthority: 'any' }), - async execute() { return { success: true, suspend: true, correlation: 'held' }; }, - } as NodeExecutor); engine.registerFlow('submit_then_confirm', { name: 'submit_then_confirm', label: 'submit_then_confirm', type: 'autolaunched', runAs: 'user', nodes: [ @@ -212,6 +239,240 @@ describe('AutomationResult.droppedFields (#32861)', () => { }); }); +describe('delegated writes roll their drops up onto the parent\'s answer (#33019)', () => { + it('map: items that each drop `status` answer one event on the parent, beside the items\' credited writes', async () => { + const engine = makeEngine(); + engine.registerFlow('child_submit', submitFlow('child_submit', { status: 'submitted', note: 'n' })); + engine.registerFlow('submit_each', chain('submit_each', [ + { id: 'each', type: 'map', label: 'Each', config: { flowName: 'child_submit', collection: ['a', 'b', 'c'] } }, + ])); + + const res = await engine.execute('submit_each', CALLER); + + expect(res.success).toBe(true); + expect(res.summary?.acted).toBe(3); // what `summary` already credited + expect(res.droppedFields).toEqual(STATUS_DROP); + }); + + it('map: an item that paused and was resumed through its own run id rolls its drop up', async () => { + const engine = makeEngine(); + engine.registerFlow('pause_then_submit', PAUSE_THEN_SUBMIT); + // `confirm` parks the parent once more after the map completes, so the + // parent's own answer — given on its resume — is observable. + engine.registerFlow('approve_each', chain('approve_each', [ + { id: 'each', type: 'map', label: 'Each', config: { flowName: 'pause_then_submit', collection: ['a'] } }, + { id: 'confirm', type: 'hold', label: 'Confirm' }, + ])); + + const parked = await engine.execute('approve_each', CALLER); + expect(parked.status).toBe('paused'); + const item = await childRunOf(engine, parked.runId!, 'map:'); + + const itemDone = await engine.resume(item); + expect(itemDone.droppedFields).toEqual(STATUS_DROP); // the item's own answer + + const done = await engine.resume(parked.runId!); + expect(done.success).toBe(true); + expect(done.summary?.acted).toBe(1); + expect(done.droppedFields).toEqual(STATUS_DROP); + }); + + it('map: an item that completed BEFORE a later item paused keeps its drop (the map\'s paused exit)', async () => { + const engine = makeEngine(); + // Item `a` drops synchronously; item `b` pauses and, resumed, drops + // nothing — so the parent can only learn of `a`'s drop from the step + // the map wrote when `b` suspended it. + engine.registerNodeExecutor({ + type: 'item_step', + descriptor: defineActionDescriptor({ type: 'item_step', version: '1.0.0', name: 'Item step', supportsPause: true, resumeAuthority: 'any' }), + async execute(_node: unknown, _vars: unknown, context: AutomationContext) { + if ((context as { params?: { tag?: string } }).params?.tag === 'b') return { success: true, suspend: true, correlation: 'held' }; + return { success: true, droppedFields: [{ object: 'expense_line', fields: ['amount'], reason: 'readonly' }] }; + }, + } as NodeExecutor); + engine.registerFlow('one_item', chain('one_item', [{ id: 'step', type: 'item_step', label: 'Step' }])); + engine.registerFlow('process_each', chain('process_each', [ + { id: 'each', type: 'map', label: 'Each', config: { flowName: 'one_item', collection: ['a', 'b'], input: { tag: { dialect: 'cel', source: 'item' } } } }, + { id: 'confirm', type: 'hold', label: 'Confirm' }, + ])); + + const parked = await engine.execute('process_each', CALLER); + expect(parked.status).toBe('paused'); + const itemB = await childRunOf(engine, parked.runId!, 'map:'); + const itemDone = await engine.resume(itemB); + expect('droppedFields' in itemDone).toBe(false); // `b` itself dropped nothing + + const done = await engine.resume(parked.runId!); + expect(done.success).toBe(true); + expect(done.droppedFields).toEqual([{ object: 'expense_line', fields: ['amount'], reason: 'readonly' }]); + }); + + it('map: an earlier item\'s drop survives a later item\'s failure that a `fault` edge contains (the map\'s failure exit)', async () => { + const engine = makeEngine(); + engine.registerNodeExecutor({ + type: 'item_step', + async execute(_node: unknown, _vars: unknown, context: AutomationContext) { + if ((context as { params?: { tag?: string } }).params?.tag === 'b') return { success: false, error: 'row b refused by the remote' }; + return { success: true, droppedFields: [{ object: 'expense_line', fields: ['amount'], reason: 'readonly' }] }; + }, + } as never); + engine.registerNodeExecutor({ type: 'noop', async execute() { return { success: true }; } } as never); + engine.registerFlow('one_item', chain('one_item', [{ id: 'step', type: 'item_step', label: 'Step' }])); + engine.registerFlow('process_each', { + name: 'process_each', label: 'process_each', type: 'autolaunched', runAs: 'user', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'each', type: 'map', label: 'Each', config: { flowName: 'one_item', collection: ['a', 'b'], input: { tag: { dialect: 'cel', source: 'item' } } } }, + { id: 'handler', type: 'noop', label: 'Handler' }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'each' }, + { id: 'e2', source: 'each', target: 'end' }, + { id: 'e_fault', source: 'each', target: 'handler', type: 'fault' }, + { id: 'e3', source: 'handler', target: 'end' }, + ], + } as never); + + const res = await engine.execute('process_each', CALLER); + + // The fault edge contained item `b`'s failure, so the run completed — + // and item `a`'s drop rides only on the map's failed step. + expect(res.success).toBe(true); + expect(res.status).toBeUndefined(); + expect(res.droppedFields).toEqual([{ object: 'expense_line', fields: ['amount'], reason: 'readonly' }]); + }); + + it('a paused child\'s drops MERGE with the drops its awaiting step already holds (creditChildRun)', async () => { + const engine = makeEngine(); + const tagOf = (context: AutomationContext) => (context as { params?: { tag?: string } }).params?.tag; + // Item `a` drops `amount` synchronously; item `b` pauses at `gate` + // and, resumed, drops `memo` at `late` — so the map step that `b` + // suspended already holds `a`'s event when `b`'s is credited onto it. + engine.registerNodeExecutor({ + type: 'gate_step', + descriptor: defineActionDescriptor({ type: 'gate_step', version: '1.0.0', name: 'Gate', supportsPause: true, resumeAuthority: 'any' }), + async execute(_node: unknown, _vars: unknown, context: AutomationContext) { + if (tagOf(context) === 'b') return { success: true, suspend: true, correlation: 'held' }; + return { success: true, droppedFields: [{ object: 'expense_line', fields: ['amount'], reason: 'readonly' }] }; + }, + } as NodeExecutor); + engine.registerNodeExecutor({ + type: 'late_step', + async execute(_node: unknown, _vars: unknown, context: AutomationContext) { + return tagOf(context) === 'b' + ? { success: true, droppedFields: [{ object: 'expense_line', fields: ['memo'], reason: 'readonly' }] } + : { success: true }; + }, + } as never); + engine.registerFlow('one_item', chain('one_item', [ + { id: 'gate', type: 'gate_step', label: 'Gate' }, + { id: 'late', type: 'late_step', label: 'Late' }, + ])); + engine.registerFlow('process_each', chain('process_each', [ + { id: 'each', type: 'map', label: 'Each', config: { flowName: 'one_item', collection: ['a', 'b'], input: { tag: { dialect: 'cel', source: 'item' } } } }, + { id: 'confirm', type: 'hold', label: 'Confirm' }, + ])); + + const parked = await engine.execute('process_each', CALLER); + expect(parked.status).toBe('paused'); + const itemB = await childRunOf(engine, parked.runId!, 'map:'); + const itemDone = await engine.resume(itemB); + expect(itemDone.droppedFields).toEqual([{ object: 'expense_line', fields: ['memo'], reason: 'readonly' }]); + + const done = await engine.resume(parked.runId!); + expect(done.success).toBe(true); + expect(done.droppedFields).toEqual([{ object: 'expense_line', fields: ['amount', 'memo'], reason: 'readonly' }]); + }); + + it('subflow: a child that paused, resumed through the PARENT\'s run id (the delegated leg), rolls its drop up', async () => { + const engine = makeEngine(); + engine.registerFlow('pause_then_submit', PAUSE_THEN_SUBMIT); + engine.registerFlow('wizard', chain('wizard', [ + { id: 'sub', type: 'subflow', label: 'Sub', config: { flowName: 'pause_then_submit' } }, + ])); + + const parked = await engine.execute('wizard', CALLER); + expect(parked.status).toBe('paused'); + await childRunOf(engine, parked.runId!, 'subflow:'); + + const done = await engine.resume(parked.runId!); + + expect(done.success).toBe(true); + expect(done.status).toBeUndefined(); + expect(done.summary?.acted).toBe(1); + expect(done.droppedFields).toEqual(STATUS_DROP); + }); + + it('subflow: a child that paused, resumed through its OWN run id (the up-bubble), rolls its drop up', async () => { + const engine = makeEngine(); + engine.registerFlow('pause_then_submit', PAUSE_THEN_SUBMIT); + engine.registerFlow('wizard_then_confirm', chain('wizard_then_confirm', [ + { id: 'sub', type: 'subflow', label: 'Sub', config: { flowName: 'pause_then_submit' } }, + { id: 'confirm', type: 'hold', label: 'Confirm' }, + ])); + + const parked = await engine.execute('wizard_then_confirm', CALLER); + expect(parked.status).toBe('paused'); + const child = await childRunOf(engine, parked.runId!, 'subflow:'); + + const childDone = await engine.resume(child); + expect(childDone.droppedFields).toEqual(STATUS_DROP); + // The bubble moved the parent on to `confirm`. + expect((await engine.suspensionOf(parked.runId!))?.nodeId).toBe('confirm'); + + const done = await engine.resume(parked.runId!); + expect(done.success).toBe(true); + expect(done.summary?.acted).toBe(1); + expect(done.droppedFields).toEqual(STATUS_DROP); + }); + + it('a host-registered executor\'s malformed `droppedFields` is skipped — the run still completes, the well-typed event still answers', async () => { + const engine = makeEngine(); + engine.registerNodeExecutor({ + type: 'sloppy_write', + async execute() { + return { + success: true, + droppedFields: [ + null, + 'status', + { object: 'expense_report', fields: 'status', reason: 'readonly' }, + { object: 'expense_report', fields: ['status'], reason: 'no_such_reason' }, + { object: 'expense_line', fields: ['amount'], reason: 'readonly' }, + ], + }; + }, + } as never); + engine.registerFlow('sloppy', chain('sloppy', [{ id: 'w', type: 'sloppy_write', label: 'W' }])); + + const res = await engine.execute('sloppy', CALLER); + + expect(res.success).toBe(true); + expect(res.status).toBeUndefined(); + expect(res.droppedFields).toEqual([{ object: 'expense_line', fields: ['amount'], reason: 'readonly' }]); + }); + + it('a malformed `droppedFields` that is not even a list leaves the run completed with no member', async () => { + const engine = makeEngine(); + engine.registerNodeExecutor({ + type: 'sloppy_write', + // Array-LIKE, not an array: it has a `length`, so it reaches the + // step, and it is not iterable, so an unguarded fold would throw. + async execute() { + return { success: true, droppedFields: { length: 1, 0: { object: 'expense_report', fields: ['status'], reason: 'readonly' } } }; + }, + } as never); + engine.registerFlow('sloppy', chain('sloppy', [{ id: 'w', type: 'sloppy_write', label: 'W' }])); + + const res = await engine.execute('sloppy', CALLER); + + expect(res.success).toBe(true); + expect(res.status).toBeUndefined(); + expect('droppedFields' in res).toBe(false); + }); +}); + describe('dropEventsOf — the fold over the step log', () => { const AT = '2026-11-13T00:00:00.000Z'; const step = (nodeId: string, droppedFields?: Drop[]): StepLogEntry => ({ @@ -235,4 +496,17 @@ describe('dropEventsOf — the fold over the step log', () => { it('answers undefined, not [], for a log with no drop', () => { expect(dropEventsOf([step('a'), step('b', [])])).toBeUndefined(); }); + + it('foldDropEvents is total: what is not well-typed is skipped, never thrown over, and no input is mutated', () => { + const held: Drop[] = [{ object: 'expense_report', fields: ['status'], reason: 'readonly' }]; + const lists: unknown[] = [ + undefined, null, 42, 'status', { object: 'x' }, + [undefined, { object: 'expense_report' }, { object: 'expense_report', fields: [1], reason: 'readonly' }], + held, + [{ object: 'expense_report', fields: ['approved_at'], reason: 'readonly' }], + ]; + expect(foldDropEvents(lists)).toEqual([{ object: 'expense_report', fields: ['status', 'approved_at'], reason: 'readonly' }]); + expect(held[0].fields).toEqual(['status']); + expect(foldDropEvents([null, 'x', [{}]])).toBeUndefined(); + }); }); diff --git a/packages/services/service-automation/src/run-dropped-fields.ts b/packages/services/service-automation/src/run-dropped-fields.ts index 127c6147389..50f4e946466 100644 --- a/packages/services/service-automation/src/run-dropped-fields.ts +++ b/packages/services/service-automation/src/run-dropped-fields.ts @@ -1,6 +1,6 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. -import type { DroppedFieldsEvent } from '@objectstack/spec/data'; +import { DroppedFieldsEventSchema, type DroppedFieldsEvent } from '@objectstack/spec/data'; import type { StepLogEntry } from './engine.js'; /** @@ -17,22 +17,45 @@ import type { StepLogEntry } from './engine.js'; * The fold is over the FLAT step log, like `summarizeRun`: a structured * region's body steps are already spliced into it, and a run resumed from a * pause carries the steps it ran before the pause — so a drop before a - * `screen` node still reaches the answer the run finally gives. + * `screen` node still reaches the answer the run finally gives. A delegated + * write reaches it the same way `summary` credits one: the `subflow` / `map` + * step carries its child runs' answers ({@link foldDropEvents}). + */ +export function dropEventsOf(steps: readonly StepLogEntry[]): DroppedFieldsEvent[] | undefined { + return foldDropEvents(steps.map((step) => step.droppedFields)); +} + +/** + * The ONE fold (#32861, #33019): every list of drop events a run answers for — + * its steps' (`dropEventsOf`), a `map` entry's synchronously completed items', + * a paused child's credited to the step that awaited it (`creditChildRun`) — + * goes through here, so all of them coalesce under one rule. * * Coalesced, not concatenated: one event per `(object, reason)`, its `fields` * the union in first-seen order. A loop that writes thirty rows and drops * `status` on each is one fact for the caller ("status did not take effect"), * not thirty, and the answer stays bounded by the schema rather than by the * run's length. The element is the engine's own event, unchanged in shape — - * no new vocabulary. + * no new vocabulary. The fields are copied, so no input array is mutated. + * + * Total, never throwing: a list or an event that is not well-typed against + * `DroppedFieldsEventSchema` is skipped. Both in-tree producers are + * well-typed, but a host-registered executor's `droppedFields` reaches the + * step unchecked, and the callers run this inside the `try` whose `catch` + * reads any throw as a node or run failure — a report about values that did + * not land must never turn a completed run into a failed or retried one. * * Returns `undefined` — never `[]` — when nothing was dropped, so the member * is omitted on every run that dropped nothing. */ -export function dropEventsOf(steps: readonly StepLogEntry[]): DroppedFieldsEvent[] | undefined { +export function foldDropEvents(lists: Iterable): DroppedFieldsEvent[] | undefined { const byKey = new Map(); - for (const step of steps) { - for (const e of step.droppedFields ?? []) { + for (const list of lists) { + if (!Array.isArray(list)) continue; + for (const raw of list) { + const parsed = DroppedFieldsEventSchema.safeParse(raw); + if (!parsed.success) continue; + const e = parsed.data; const key = `${e.reason}\u0000${e.object}`; const held = byKey.get(key); if (!held) { diff --git a/packages/services/service-automation/src/run-resume.ts b/packages/services/service-automation/src/run-resume.ts index de95662e1e5..a84d4e33590 100644 --- a/packages/services/service-automation/src/run-resume.ts +++ b/packages/services/service-automation/src/run-resume.ts @@ -17,6 +17,7 @@ import { withFlowRunSlot } from './flow-slots.js'; import type { FlowParsed, FlowRunSummary } from '@objectstack/spec/automation'; +import type { DroppedFieldsEvent } from '@objectstack/spec/data'; import type { AutomationContext, AutomationResult, ResumeSignal } from '@objectstack/spec/contracts'; import { RESUME_AUTHORITY_SERVICE } from '@objectstack/spec/contracts'; import { runIsUnscopedUserMode, flowTouchesData, runAccessibleOrgIds, runOrgUserIds, runTriggerUserId, type SeededRunContext } from './runtime-identity.js'; @@ -24,7 +25,7 @@ import { refuseNode } from './guard-refusal.js'; import { describeThrownForLog } from './thrown-cause-diagnostics.js'; import { carriedRefusalOfResult, readCarriedRefusal } from './inner-refusal.js'; import { summarizeRun } from './run-summary.js'; -import { withDroppedFields } from './run-dropped-fields.js'; +import { dropEventsOf, foldDropEvents } from './run-dropped-fields.js'; import { noteTenantCurrencyReadFault } from './builtin/template.js'; import { mapItemCancelledVariable, type MapItemCancelledMarker } from './builtin/map-node.js'; // The values below (`buildRunTrigger`, `FlowRefusalSignal`, `isRefusalSignal`, @@ -786,10 +787,24 @@ export async function loadSuspendedRunStrict(this: Pick= 0; i--) { if (steps[i].nodeId !== nodeId) continue; + // #33019 — the child's drop events land on the same awaiting step its + // totals do, through the one fold, so the terminal answer's + // `droppedFields` (folded from the steps) credits every child run + // `summary` does. + const droppedFields = childDroppedFields?.length + ? foldDropEvents([steps[i].droppedFields, childDroppedFields]) + : undefined; + if (droppedFields) steps[i] = { ...steps[i], droppedFields }; + if (!child) return; const prior = steps[i].metrics ?? {}; steps[i] = { ...steps[i], @@ -1274,6 +1289,7 @@ export async function resumeInternal( skipBubble: boolean, childSummary?: FlowRunSummary, childRefusal?: ChildRunRefusal, + childDroppedFields?: readonly DroppedFieldsEvent[], ): Promise { // Idempotency guard (set synchronously, before any await): reject a // concurrent duplicate resume of the same run so side effects can't run @@ -1416,7 +1432,7 @@ export async function resumeInternal( // #4354 — up-bubble: the child that just finished did work this run // is accountable for. Credit it to the step that suspended awaiting // it, before traversal appends anything further. - this.creditChildRun(run.steps, run.nodeId, childSummary); + this.creditChildRun(run.steps, run.nodeId, childSummary, childDroppedFields); // [#18714] The refusal this run must end on instead of continuing // past its `subflow` / `map` node, if any. Seeded from the UP-BUBBLE @@ -1580,7 +1596,8 @@ export async function resumeInternal( signal = this.buildSubflowResumeSignal(childRun.context, childRes.output); // #4354 — down-delegation is the other way a child's work // lands under a parent step written at suspend time. - this.creditChildRun(run.steps, run.nodeId, childRes.summary); + // #33019 — and its drop events, onto the same step. + this.creditChildRun(run.steps, run.nodeId, childRes.summary, childRes.droppedFields); } else if (carriesSubflowChildOutput(signal)) { // The engine-built UP-BUBBLE — the HEALTHY path, and the // one this `else` used to describe as a degradation. The @@ -1947,8 +1964,12 @@ export async function resumeInternal( // Skipped when the DELEGATION path drives the chain (it // continues the parent itself). Best-effort: the child's own // completion stands even if the parent continuation fails. + // #33019 — with this run's drop events, the ones its own answer + // below carries, so the parent credits them where it credits + // `summary`. + const droppedFields = dropEventsOf(steps); if (!skipBubble) { - await this.bubbleToParent(run, output, summary); + await this.bubbleToParent(run, output, summary, undefined, droppedFields); } // Surface the flow's friendly completion message so a screen-flow @@ -1968,7 +1989,7 @@ export async function resumeInternal( summary, // #32861 — like `summary`, over the WHOLE run: a drop before // the pause reaches the answer the run finally gives. - ...withDroppedFields(steps), + ...(droppedFields ? { droppedFields } : {}), }; } catch (err: unknown) { // [#15788] A resumed run reached a refusing `end` — the SECOND diff --git a/packages/spec/src/api/automation-api.zod.ts b/packages/spec/src/api/automation-api.zod.ts index cb09df1362f..90af622bd84 100644 --- a/packages/spec/src/api/automation-api.zod.ts +++ b/packages/spec/src/api/automation-api.zod.ts @@ -484,18 +484,20 @@ export const TriggerFlowResponseSchema = lazySchema(() => BaseResponseSchema.ext + 'it yet).', ), // #32861 — mirrors `AutomationResult.droppedFields`; the element IS the - // data engine's `DroppedFieldsEventSchema`, so no new vocabulary. The - // paused-child and `map`-item roll-up the describe says is not built yet - // is #33019. + // data engine's `DroppedFieldsEventSchema`, so no new vocabulary. #33019 + // rolled up the paused-child and `map`-item legs; the failed child and + // the operator-cancelled paused `map` item (#27971) are what remains. droppedFields: z.array(DroppedFieldsEventSchema).optional().describe( 'Caller-supplied field values a write step of the run did not store (e.g. a `readonly` ' + 'field an `update_record` step wrote): the data engine\'s own drop events, one per object ' + 'and reason in first-seen order; a field named means at least one write dropped it, not every ' + 'write. The steps still succeeded and the run\'s outcome is unchanged - this tells ' + 'the caller which values never landed. Set on a terminal success only, and only when ' - + 'a field was dropped. Delegated writes: a `subflow` child that completes without pausing ' - + 'rolls its drops up here; a child that paused, and a `map` item\'s run, do not yet, ' - + 'so an absent member is not proof that a delegated write dropped nothing.', + + 'a field was dropped. Delegated writes roll up here too: a `subflow` child\'s run and each ' + + '`map` item\'s run, whether it completed without pausing or paused and resumed. A child run ' + + 'that failed answers no drops, so where a `try_catch` or `fault` edge contains that failure ' + + 'an absent member is not proof the failed child dropped nothing. A `map` item whose paused run ' + + 'an operator cancelled answers none either (its slot in `results` holds the cancelled marker).', ), }), })); diff --git a/packages/spec/src/contracts/automation-service.ts b/packages/spec/src/contracts/automation-service.ts index 6ee9e725666..b40f6ffb3f1 100644 --- a/packages/spec/src/contracts/automation-service.ts +++ b/packages/spec/src/contracts/automation-service.ts @@ -847,11 +847,15 @@ export interface AutomationResult { * it resumed from), and only when at least one step dropped a field — * absent, never `[]`, otherwise. * - * Delegated writes, as built: a `subflow` child that completes without - * pausing rolls its drops up onto this answer; a child that paused, and - * a `map` item's run, do not yet (#33019) — unlike {@link summary}, - * which credits all three. Until then an absent member is not proof - * that a delegated write dropped nothing. + * Delegated writes roll up onto this answer too: a `subflow` child's run + * and each `map` item's run, whether it completed without pausing or + * paused and resumed (#33019), as {@link summary} credits them. Unlike + * `summary`, a child run that FAILED answers no drops, so where a + * `try_catch` or `fault` edge contains that failure an absent member is + * not proof the failed child dropped nothing. A `map` item whose paused + * run an operator cancelled (#27971) answers none either: the map goes + * on with the cancelled marker in the item's `results` slot, and that + * run's drops, like its totals, reach the parent nowhere. */ droppedFields?: DroppedFieldsEvent[]; }