Skip to content

Commit 461ae6b

Browse files
committed
fix(executor): selected outputs no longer fail runs that call a child workflow
A sync run handed the caller's public `block.path` selectors to the executor instead of the internal form it had already resolved, so the child-workflow block parsed `done.data` as workflow `done`, block `data` and failed the run after it executed and billed. The v2 execute service and the v1 sync path now pass resolved selectors (v1 drops ones naming no block, as it always ignored them), and the child-workflow block drops a selector it cannot apply with a warning rather than failing the block.
1 parent bb43072 commit 461ae6b

7 files changed

Lines changed: 364 additions & 23 deletions

File tree

‎apps/sim/app/api/workflows/[id]/execute/route.ts‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,10 @@ import {
151151
forwardAgentStreamToExecutionEvents,
152152
shouldForwardAnswerTextFromSink,
153153
} from '@/lib/workflows/streaming/forward-agent-stream-events'
154-
import { resolveOutputSelectors } from '@/lib/workflows/streaming/resolve-output-selectors'
154+
import {
155+
resolveOutputSelectors,
156+
resolveOutputSelectorsLeniently,
157+
} from '@/lib/workflows/streaming/resolve-output-selectors'
155158
import {
156159
agentStreamProtocolResponseHeaders,
157160
createStreamingResponse,
@@ -1460,6 +1463,20 @@ async function handleExecutePost(
14601463
}
14611464

14621465
const executionVariables = cachedWorkflowData?.variables ?? workflow.variables ?? {}
1466+
/**
1467+
* The executor reads only the internal selector form; a public `block.path` reaching
1468+
* a child-workflow block would read as `workflow.block`. The sync response has never
1469+
* refused a stale selector, so one that names no block is dropped, not answered with 400.
1470+
*/
1471+
const syncSelection = resolveOutputSelectorsLeniently({
1472+
selectedOutputs,
1473+
currentBlocks: effectiveWorkflowStateOverride?.blocks ?? {},
1474+
})
1475+
if (syncSelection.rejected.length > 0) {
1476+
reqLogger.warn('Ignoring selected outputs that name no block', {
1477+
rejected: syncSelection.rejected,
1478+
})
1479+
}
14631480

14641481
const timeoutController = createTimeoutAbortController(getEffectiveSyncTimeoutMs())
14651482
const didExecutionTimeOut = (error?: unknown) =>
@@ -1484,7 +1501,7 @@ async function handleExecutePost(
14841501
workflow,
14851502
processedInput,
14861503
executionVariables,
1487-
selectedOutputs
1504+
syncSelection.selectedOutputs
14881505
)
14891506

14901507
const result = await executeWorkflowCore({

‎apps/sim/executor/handlers/workflow/handler.ts‎

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -506,15 +506,23 @@ export class WorkflowBlockHandler implements BlockHandler {
506506
childWorkflow.rawBlocks || {},
507507
ctx.selectedOutputs
508508
)
509-
if (isCustomBlock && childOutputSelection.targetsChildWorkflow) {
510-
throw new Error('Custom block child outputs cannot be selected for streaming')
509+
if (childOutputSelection.ignored.length > 0) {
510+
logger.warn('Ignoring output selectors the child workflow cannot serve', {
511+
childWorkflowId: workflowId,
512+
ignored: childOutputSelection.ignored,
513+
})
511514
}
512-
if (!withinSseChildDepth && childOutputSelection.targetsChildWorkflow) {
513-
throw new Error(
514-
`Selected stream output exceeds the maximum child workflow depth of ${DEFAULTS.MAX_SSE_CHILD_DEPTH}`
515-
)
515+
if (childOutputSelection.targetsChildWorkflow && (isCustomBlock || !withinSseChildDepth)) {
516+
logger.warn('Ignoring child output selection the stream cannot carry', {
517+
childWorkflowId: workflowId,
518+
reason: isCustomBlock
519+
? 'custom block child outputs cannot be selected for streaming'
520+
: 'selected output exceeds the maximum child workflow depth',
521+
maxDepth: DEFAULTS.MAX_SSE_CHILD_DEPTH,
522+
})
516523
}
517-
const childSelectedOutputs = isCustomBlock ? [] : childOutputSelection.selectedOutputs
524+
const childSelectedOutputs =
525+
isCustomBlock || !withinSseChildDepth ? [] : childOutputSelection.selectedOutputs
518526
const shouldStreamChild =
519527
shouldPropagateCallbacks && Boolean(ctx.stream) && childSelectedOutputs.length > 0
520528

Lines changed: 237 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,237 @@
1+
/**
2+
* `selectedOutputs` on a deployed run of a workflow that calls a child workflow, against real
3+
* PostgreSQL through the execute use case. A selector naming a parent block must reach the
4+
* executor in its internal form, so the child-workflow block never mistakes `block.path` for a
5+
* `workflow.block` selector; a selector that targets the child but names nothing there must not
6+
* fail a run that otherwise succeeded; and a selector naming no parent block is refused before
7+
* the run starts, so it is never executed or billed.
8+
*/
9+
import { db } from '@sim/db'
10+
import {
11+
permissions,
12+
user,
13+
workflow,
14+
workflowDeploymentVersion,
15+
workflowExecutionLogs,
16+
workflowExecutionSnapshots,
17+
workspace,
18+
} from '@sim/db/schema'
19+
import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures'
20+
import { createSessionPrincipal } from '@sim/testing/factories/principal.factory'
21+
import { generateId } from '@sim/utils/id'
22+
import { eq, inArray } from 'drizzle-orm'
23+
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
24+
import { executeWorkflowOperation } from '@/lib/workflows/application/execute-workflow'
25+
26+
const ownerId = generateId()
27+
const workspaceId = generateId()
28+
const parentWorkflowId = generateId()
29+
const childWorkflowId = generateId()
30+
const principal = createSessionPrincipal({ userId: ownerId, sessionId: generateId() })
31+
/** Deployed block IDs are UUIDs; `blockOutputs` projects only blocks with one. */
32+
const blockIds = {
33+
start: generateId(),
34+
ask: generateId(),
35+
done: generateId(),
36+
childDone: generateId(),
37+
}
38+
39+
const startBlock = {
40+
id: blockIds.start,
41+
type: 'start_trigger',
42+
name: 'Start',
43+
enabled: true,
44+
position: { x: 0, y: 0 },
45+
outputs: {},
46+
subBlocks: {},
47+
}
48+
49+
function responseBlock(id: string, name: string, data: string) {
50+
return {
51+
id,
52+
type: 'response',
53+
name,
54+
enabled: true,
55+
position: { x: 600, y: 0 },
56+
outputs: {},
57+
subBlocks: {
58+
dataMode: { id: 'dataMode', type: 'dropdown', value: 'json' },
59+
data: { id: 'data', type: 'code', value: data },
60+
status: { id: 'status', type: 'short-input', value: '200' },
61+
},
62+
}
63+
}
64+
65+
const childState = {
66+
blocks: {
67+
[blockIds.start]: startBlock,
68+
[blockIds.childDone]: responseBlock(
69+
blockIds.childDone,
70+
'Child Done',
71+
'{"answer": "from child"}'
72+
),
73+
},
74+
edges: [{ id: generateId(), source: blockIds.start, target: blockIds.childDone }],
75+
loops: {},
76+
parallels: {},
77+
variables: {},
78+
}
79+
80+
const parentState = {
81+
blocks: {
82+
[blockIds.start]: startBlock,
83+
[blockIds.ask]: {
84+
id: blockIds.ask,
85+
type: 'workflow_input',
86+
name: 'Ask',
87+
enabled: true,
88+
position: { x: 300, y: 0 },
89+
outputs: {},
90+
subBlocks: {
91+
workflowId: { id: 'workflowId', type: 'workflow-selector', value: childWorkflowId },
92+
inputMapping: { id: 'inputMapping', type: 'input-mapping', value: {} },
93+
},
94+
},
95+
[blockIds.done]: responseBlock(blockIds.done, 'Done', '{"answer": "<ask.result.data.answer>"}'),
96+
},
97+
edges: [
98+
{ id: generateId(), source: blockIds.start, target: blockIds.ask },
99+
{ id: generateId(), source: blockIds.ask, target: blockIds.done },
100+
],
101+
loops: {},
102+
parallels: {},
103+
variables: {},
104+
}
105+
106+
function run(selectedOutputs: string[]) {
107+
return executeWorkflowOperation.execute({
108+
principal,
109+
input: {
110+
workflowId: parentWorkflowId,
111+
requestId: generateId(),
112+
input: {},
113+
mode: 'sync',
114+
selectedOutputs,
115+
requestHeaders: new Headers(),
116+
},
117+
})
118+
}
119+
120+
async function parentLogCount(): Promise<number> {
121+
const rows = await db
122+
.select({ id: workflowExecutionLogs.id })
123+
.from(workflowExecutionLogs)
124+
.where(eq(workflowExecutionLogs.workflowId, parentWorkflowId))
125+
return rows.length
126+
}
127+
128+
beforeAll(async () => {
129+
const now = new Date()
130+
await db.insert(user).values({
131+
id: ownerId,
132+
name: 'Selected outputs fixture',
133+
email: `${ownerId}@selected-outputs.test`,
134+
emailVerified: true,
135+
createdAt: now,
136+
updatedAt: now,
137+
})
138+
await insertWorkspaceFixture(db, {
139+
id: workspaceId,
140+
name: 'Selected outputs fixture',
141+
ownerId,
142+
billedAccountUserId: ownerId,
143+
})
144+
await db.insert(permissions).values({
145+
id: generateId(),
146+
userId: ownerId,
147+
entityType: 'workspace',
148+
entityId: workspaceId,
149+
permissionType: 'admin',
150+
})
151+
await db.insert(workflow).values(
152+
[
153+
{ id: parentWorkflowId, name: 'Parent' },
154+
{ id: childWorkflowId, name: 'Child' },
155+
].map(({ id, name }) => ({
156+
id,
157+
userId: ownerId,
158+
workspaceId,
159+
name,
160+
isDeployed: true,
161+
deployedAt: now,
162+
lastSynced: now,
163+
createdAt: now,
164+
updatedAt: now,
165+
}))
166+
)
167+
await db.insert(workflowDeploymentVersion).values([
168+
{
169+
id: generateId(),
170+
workflowId: parentWorkflowId,
171+
version: 1,
172+
state: parentState,
173+
isActive: true,
174+
},
175+
{
176+
id: generateId(),
177+
workflowId: childWorkflowId,
178+
version: 1,
179+
state: childState,
180+
isActive: true,
181+
},
182+
])
183+
})
184+
185+
afterAll(async () => {
186+
const workflowIds = [parentWorkflowId, childWorkflowId]
187+
await db
188+
.delete(workflowExecutionLogs)
189+
.where(inArray(workflowExecutionLogs.workflowId, workflowIds))
190+
await db
191+
.delete(workflowExecutionSnapshots)
192+
.where(inArray(workflowExecutionSnapshots.workflowId, workflowIds))
193+
await deleteWorkspaceFixture(db, eq(workspace.id, workspaceId))
194+
await db.delete(user).where(eq(user.id, ownerId))
195+
await db.$client.end()
196+
})
197+
198+
describe('selectedOutputs on a run that calls a child workflow', () => {
199+
it('completes and returns a parent block output selected by name and path', async () => {
200+
const result = await run(['done.data'])
201+
202+
expect(result).toMatchObject({
203+
ok: true,
204+
status: 'completed',
205+
blockOutputs: { 'done.data': { answer: 'from child' } },
206+
})
207+
})
208+
209+
it('completes when a selector targets the child workflow', async () => {
210+
const result = await run([`${childWorkflowId}.childdone.data`, 'done.data'])
211+
212+
expect(result).toMatchObject({
213+
ok: true,
214+
status: 'completed',
215+
blockOutputs: { 'done.data': { answer: 'from child' } },
216+
})
217+
})
218+
219+
it('completes when a child-targeted selector names no block in the child', async () => {
220+
const result = await run([`${childWorkflowId}.missing.data`, 'done.data'])
221+
222+
expect(result).toMatchObject({
223+
ok: true,
224+
status: 'completed',
225+
blockOutputs: { 'done.data': { answer: 'from child' } },
226+
})
227+
})
228+
229+
it('refuses a selector naming no parent block before the run starts, leaving no run to bill', async () => {
230+
const before = await parentLogCount()
231+
232+
const result = await run(['nosuchblock.data'])
233+
234+
expect(result).toMatchObject({ ok: false, failure: { kind: 'input', statusCode: 400 } })
235+
expect(await parentLogCount()).toBe(before)
236+
})
237+
})

‎apps/sim/lib/workflows/executor/execute-service.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -743,7 +743,7 @@ export async function executeWorkflowService(
743743
workflow,
744744
processedInput,
745745
workflowVariables,
746-
selectedOutputs
746+
resolvedSelectedOutputs
747747
)
748748

749749
const result = await executeWorkflowCore({

‎apps/sim/lib/workflows/streaming/output-selector.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,21 @@ describe('output selector scoping', () => {
104104
expect(selection.targetsChildWorkflow).toBe(true)
105105
})
106106

107+
it('drops a selector it cannot apply instead of failing the child block', () => {
108+
const selection = selectChildOutputSelectors(
109+
CHILD_WORKFLOW_ID,
110+
{ [CHILD_BLOCK_ID]: block(CHILD_BLOCK_ID, 'Writer') },
111+
['done.data', formatInternalOutputSelector('missing', 'content', CHILD_WORKFLOW_ID)]
112+
)
113+
114+
expect(selection.selectedOutputs).toEqual([])
115+
expect(selection.targetsChildWorkflow).toBe(false)
116+
expect(selection.ignored.map((entry) => entry.selector)).toEqual([
117+
'done.data',
118+
formatInternalOutputSelector('missing', 'content', CHILD_WORKFLOW_ID),
119+
])
120+
})
121+
107122
it.each([
108123
'',
109124
' workflow.agent_content',

0 commit comments

Comments
 (0)