Skip to content

Commit 79ab6f4

Browse files
committed
fix(lint): judge a child's result.<key> only when every run of the child ends at a Response block
A child with a Response on one branch returns another block's output on the others, so W_CHILD_RESULT_PATH and the server's child-result lint now require every run to end at a root Response (alwaysEndsAtResponse in workflow-types, shared by the CLI check and the server). A deploy judges the child's active deployment, a draft write its draft, read in narrow batched queries; a failed child lookup no longer leaves an unhandled rejection. isElseConditionTitle and RESPONSE_BLOCK_TYPE move to workflow-types so every reader shares one rule.
1 parent 5d777f9 commit 79ab6f4

23 files changed

Lines changed: 610 additions & 122 deletions

File tree

‎apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/condition-input/condition-input.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ import {
1313
} from '@sim/emcn'
1414
import { ChevronDown, ChevronsUpDown, ChevronUp, Plus, Trash } from '@sim/emcn/icons'
1515
import { createLogger } from '@sim/logger'
16+
import { isElseConditionTitle } from '@sim/workflow-types/workflow'
1617
import Editor from 'react-simple-code-editor'
17-
import { isElseConditionTitle } from '@/lib/workflows/conditions'
1818
import {
1919
isLikelyReferenceSegment,
2020
SYSTEM_REFERENCE_PREFIXES,

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
import { createLogger } from '@sim/logger'
22
import { getErrorMessage } from '@sim/utils/errors'
3+
import { isElseConditionTitle } from '@sim/workflow-types/workflow'
34
import { adoptToolFailure, markFailureKind } from '@/lib/core/errors/failure-log'
45
import { normalizeStringRecord, normalizeWorkflowVariables } from '@/lib/core/utils/records'
56
import {
67
isNonRetryableExecutionError,
78
NonRetryableExecutionError,
89
} from '@/lib/execution/non-retryable-error'
9-
import { isElseConditionTitle } from '@/lib/workflows/conditions'
1010
import type { BlockOutput } from '@/blocks/types'
1111
import { BlockType, DEFAULTS, EDGE } from '@/executor/constants'
1212
import type { BlockHandler, ExecutionContext } from '@/executor/types'

‎apps/sim/lib/workflows/conditions.test.ts‎

Lines changed: 0 additions & 20 deletions
This file was deleted.

‎apps/sim/lib/workflows/conditions.ts‎

Lines changed: 0 additions & 9 deletions
This file was deleted.

‎apps/sim/lib/workflows/dynamic-handle-topology.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { isElseConditionTitle, type WorkflowBranchKind } from '@sim/workflow-types/workflow'
12
import type { BlockState } from '@/stores/workflows/workflow/types'
23

34
export interface ConditionRow {
@@ -39,6 +40,15 @@ export function getDynamicHandleSubblockId(
3940
return null
4041
}
4142

43+
/** The branch kind of a block whose branches are rows: `condition`, or `router` for router_v2. */
44+
export function getDynamicHandleBranchKind(
45+
blockType: string | undefined
46+
): WorkflowBranchKind | undefined {
47+
if (blockType === 'condition') return 'condition'
48+
if (blockType === 'router_v2') return 'router'
49+
return undefined
50+
}
51+
4252
export function getDynamicHandleSubblockType(
4353
blockType: string | undefined
4454
): 'condition-input' | 'router-input' | null {
@@ -122,6 +132,29 @@ export function getDynamicHandleRows(
122132
return []
123133
}
124134

135+
/**
136+
* The source handles of the branches `block` always takes one of (as `respondsOnEveryRun` reads
137+
* canonical blocks): every route of a router, and every row of a condition with an else row (by
138+
* stored title, as the executor finds it); none for branches never saved. `undefined` for a block
139+
* without branches.
140+
*/
141+
export function getAlwaysTakenBranchHandles(
142+
block: Pick<BlockState, 'id' | 'type'> & { subBlocks: Record<string, { value: unknown }> }
143+
): string[] | undefined {
144+
const subBlockId = getDynamicHandleSubblockId(block.type)
145+
if (subBlockId === null) return undefined
146+
const stored = parseStructuredValue(block.subBlocks[subBlockId]?.value) ?? []
147+
if (block.type === 'condition') {
148+
const hasElse = stored.some((row) =>
149+
isElseConditionTitle((row as { title?: unknown } | null)?.title)
150+
)
151+
return stored.length > 0 && hasElse
152+
? getConditionRows(block.id, stored).map((row) => `condition-${row.id}`)
153+
: []
154+
}
155+
return stored.length > 0 ? getRouterRows(block.id, stored).map((row) => `router-${row.id}`) : []
156+
}
157+
125158
export function getDynamicHandleTopologySignature(block: BlockState): string | null {
126159
if (block.type === 'condition') {
127160
const rows = getConditionRows(block.id, block.subBlocks?.conditions?.value)

‎apps/sim/lib/workflows/editing/lint-report.integration.ts‎

Lines changed: 121 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,20 @@
11
/**
22
* Real PostgreSQL coverage for the lint's child workflow checks: the children a Workflow block
3-
* calls are read from the workflow and block tables, and a graph is linted against them. A
4-
* responding child's `result.<key>` reads nothing unless `<key>` is a Response output, and a
5-
* deploy reports a called child with no deployment, which a deployed run cannot call.
3+
* calls are read from the workflow, graph and deployment tables, and a graph is linted against
4+
* them. The `result.<key>` of a child whose every run ends at a Response block reads nothing
5+
* unless `<key>` is a Response output, judged on the version the caller's run calls, and a deploy
6+
* reports a called child with no deployment, which a deployed run cannot call.
67
*/
78
import { mkdir, writeFile } from 'node:fs/promises'
89
import { dirname, resolve } from 'node:path'
910
import { db } from '@sim/db'
10-
import { user, workflow, workspace } from '@sim/db/schema'
11+
import { user, workflow, workflowDeploymentVersion, workspace } from '@sim/db/schema'
1112
import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures'
1213
import { getErrorMessage } from '@sim/utils/errors'
1314
import { generateId } from '@sim/utils/id'
1415
import { saveWorkflowToNormalizedTables } from '@sim/workflow-persistence/save'
1516
import type { BlockState, WorkflowState } from '@sim/workflow-types/workflow'
17+
import type { Edge } from '@xyflow/react'
1618
import { eq, inArray } from 'drizzle-orm'
1719
import { afterAll, beforeAll, expect, it } from 'vitest'
1820
import { buildWorkflowLintReport } from '@/lib/workflows/editing/lint-report'
@@ -64,10 +66,69 @@ function block(
6466
} as BlockState
6567
}
6668

67-
/** Stores a child workflow whose only blocks are a Start and, when given, a Response block. */
69+
function edge(source: string, target: string, sourceHandle = 'source'): Edge {
70+
return { id: generateId(), source, target, sourceHandle, targetHandle: 'target' }
71+
}
72+
73+
/**
74+
* A child graph: a Start trigger wired to a Response block "Reply" (disabled with `'disabled'`),
75+
* or a Start trigger alone with `'none'`. Block ids are fresh, as stored block ids are global.
76+
*/
77+
function replyGraph(reply: 'enabled' | 'disabled' | 'none'): WorkflowState {
78+
const startId = generateId()
79+
const blocks: Record<string, BlockState> = { [startId]: block(startId, 'start_trigger', 'Start') }
80+
const edges: Edge[] = []
81+
if (reply !== 'none') {
82+
const replyId = generateId()
83+
blocks[replyId] = block(
84+
replyId,
85+
'response',
86+
'Reply',
87+
{ dataMode: 'json', data: '{"mobile": "1"}' },
88+
reply === 'enabled'
89+
)
90+
edges.push(edge(startId, replyId))
91+
}
92+
return { blocks, edges, loops: {}, parallels: {} }
93+
}
94+
95+
/**
96+
* A child graph whose condition "Gate" sends its `if` branch to a Response block and its else
97+
* branch to `elseTarget`: a second Response block, or a function that ends the run there.
98+
*/
99+
function gateGraph(elseTarget: 'response' | 'function'): WorkflowState {
100+
const startId = generateId()
101+
const gateId = generateId()
102+
const replyId = generateId()
103+
const otherId = generateId()
104+
const conditions = JSON.stringify([
105+
{ id: `${gateId}-if`, title: 'if', value: 'true' },
106+
{ id: `${gateId}-else`, title: 'else', value: '' },
107+
])
108+
const blocks: Record<string, BlockState> = {
109+
[startId]: block(startId, 'start_trigger', 'Start'),
110+
[gateId]: block(gateId, 'condition', 'Gate', { conditions }),
111+
[replyId]: block(replyId, 'response', 'Reply', { dataMode: 'json', data: '{"mobile": "1"}' }),
112+
[otherId]:
113+
elseTarget === 'response'
114+
? block(otherId, 'response', 'Other', { dataMode: 'json', data: '{"mobile": "2"}' })
115+
: block(otherId, 'function', 'Other', { code: "return { mobile: '2' }" }),
116+
}
117+
const edges = [
118+
edge(startId, gateId),
119+
edge(gateId, replyId, `condition-${gateId}-if`),
120+
edge(gateId, otherId, `condition-${gateId}-else`),
121+
]
122+
return { blocks, edges, loops: {}, parallels: {} }
123+
}
124+
125+
/**
126+
* Stores a child workflow with draft `graph` (a Start trigger alone by default) and, with
127+
* `deployed`, an active deployment of that graph (`true`) or of another one.
128+
*/
68129
async function seedChild(
69130
name: string,
70-
options: { response?: 'enabled' | 'disabled'; deployed?: boolean; workspace?: string } = {}
131+
options: { graph?: WorkflowState; deployed?: boolean | WorkflowState; workspace?: string } = {}
71132
): Promise<string> {
72133
const id = generateId()
73134
const now = new Date()
@@ -76,26 +137,23 @@ async function seedChild(
76137
userId: ownerId,
77138
workspaceId: options.workspace ?? workspaceId,
78139
name,
79-
isDeployed: options.deployed ?? false,
140+
isDeployed: Boolean(options.deployed),
80141
lastSynced: now,
81142
createdAt: now,
82143
updatedAt: now,
83144
})
84-
const startId = generateId()
85-
const blocks: Record<string, BlockState> = { [startId]: block(startId, 'start_trigger', 'Start') }
86-
if (options.response) {
87-
const replyId = generateId()
88-
blocks[replyId] = block(
89-
replyId,
90-
'response',
91-
'Reply',
92-
{ dataMode: 'json', data: '{"mobile": "1"}' },
93-
options.response === 'enabled'
94-
)
95-
}
96-
const state: WorkflowState = { blocks, edges: [], loops: {}, parallels: {} }
97-
const saved = await saveWorkflowToNormalizedTables(id, state)
145+
const graph = options.graph ?? replyGraph('none')
146+
const saved = await saveWorkflowToNormalizedTables(id, graph)
98147
if (!saved.success) throw new Error(`Seeding the child failed: ${saved.error}`)
148+
if (options.deployed) {
149+
await db.insert(workflowDeploymentVersion).values({
150+
id: generateId(),
151+
workflowId: id,
152+
version: 1,
153+
state: options.deployed === true ? graph : options.deployed,
154+
isActive: true,
155+
})
156+
}
99157
return id
100158
}
101159

@@ -122,6 +180,14 @@ function lint(graph: ReturnType<typeof parent>, deployed = false) {
122180
)
123181
}
124182

183+
/** The references a parent reading `<call.result.mobile>` from `childId` is told read nothing. */
184+
async function childResultValues(childId: string, deployed = false) {
185+
const report = await lint(parent(childId, 'return <call.result.mobile>'), deployed)
186+
return report.unresolvedReferences
187+
.filter((ref) => ref.kind === 'child-result')
188+
.map((ref) => ref.value)
189+
}
190+
125191
beforeAll(async () => {
126192
const now = new Date()
127193
await db.insert(user).values({
@@ -154,7 +220,7 @@ afterAll(async () => {
154220
check(
155221
"a responding child's result.<key> is reported with result.data.<key> as the fix",
156222
async () => {
157-
const childId = await seedChild('Responder', { response: 'enabled', deployed: true })
223+
const childId = await seedChild('Responder', { graph: replyGraph('enabled'), deployed: true })
158224

159225
const report = await lint(
160226
parent(
@@ -180,8 +246,11 @@ check(
180246
'a child with no enabled Response block, or in another workspace, is not judged',
181247
async () => {
182248
const silent = await seedChild('Silent')
183-
const disabled = await seedChild('Disabled reply', { response: 'disabled' })
184-
const foreign = await seedChild('Foreign', { response: 'enabled', workspace: otherWorkspaceId })
249+
const disabled = await seedChild('Disabled reply', { graph: replyGraph('disabled') })
250+
const foreign = await seedChild('Foreign', {
251+
graph: replyGraph('enabled'),
252+
workspace: otherWorkspaceId,
253+
})
185254

186255
for (const childId of [silent, disabled, foreign]) {
187256
const report = await lint(parent(childId, 'return <call.result.mobile>'))
@@ -207,3 +276,31 @@ check('a deploy reports a called child that is not deployed; a draft write does
207276
expect(childFindings(await lint(parent(undeployed, 'return 1')))).toEqual([])
208277
expect(childFindings(await lint(parent(deployed, 'return 1'), true))).toEqual([])
209278
})
279+
280+
check(
281+
'a child whose run can end outside a Response block is not judged; one that always responds is',
282+
async () => {
283+
const branchy = await seedChild('Branchy', { graph: gateGraph('function') })
284+
const covered = await seedChild('Covered', { graph: gateGraph('response') })
285+
expect(await childResultValues(branchy)).toEqual([])
286+
expect(await childResultValues(covered)).toEqual([['<call.result.mobile>']])
287+
}
288+
)
289+
290+
check(
291+
"a deploy judges a child's result by its active deployment; a draft write by its draft",
292+
async () => {
293+
const respondsInDraft = await seedChild('Draft responder', {
294+
graph: replyGraph('enabled'),
295+
deployed: replyGraph('none'),
296+
})
297+
const respondsDeployed = await seedChild('Deployed responder', {
298+
graph: replyGraph('none'),
299+
deployed: replyGraph('enabled'),
300+
})
301+
expect(await childResultValues(respondsInDraft)).toEqual([['<call.result.mobile>']])
302+
expect(await childResultValues(respondsInDraft, true)).toEqual([])
303+
expect(await childResultValues(respondsDeployed)).toEqual([])
304+
expect(await childResultValues(respondsDeployed, true)).toEqual([['<call.result.mobile>']])
305+
}
306+
)

‎apps/sim/lib/workflows/editing/lint-report.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { flushMacrotask } from '@sim/testing/helpers/async'
2+
import { dbChainMockFns, resetDbChainMock } from '@sim/testing/mocks/database.mock'
13
import { tableServiceMock, tableServiceMockFns } from '@sim/testing/mocks/table-service.mock'
24
import type { Mock } from 'vitest'
35
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
@@ -95,6 +97,35 @@ describe('buildWorkflowLintReport notes', () => {
9597
}
9698
)
9799

100+
it('a complete diagnostic whose reference and child workflow lookups both fail rejects once, leaving no rejection unhandled', async () => {
101+
resetDbChainMock()
102+
const unhandled: unknown[] = []
103+
const onUnhandled = (reason: unknown) => unhandled.push(reason)
104+
process.on('unhandledRejection', onUnhandled)
105+
try {
106+
const call = block('call', 'workflow_input')
107+
call.subBlocks = { workflowId: { id: 'workflowId', type: 'short-input', value: 'child-1' } }
108+
mocks.collectUnresolvedReferences.mockRejectedValueOnce(new Error('lookup down'))
109+
dbChainMockFns.where.mockImplementationOnce(() => {
110+
throw new Error('child lookup down')
111+
})
112+
113+
await expect(
114+
buildWorkflowLintReport(
115+
{ blocks: { start: block('start', 'starter'), call }, edges: [edge('start', 'call')] },
116+
scope,
117+
{ requireComplete: true }
118+
)
119+
).rejects.toThrow('Workflow reference checks could not complete')
120+
await flushMacrotask()
121+
122+
expect(unhandled).toEqual([])
123+
} finally {
124+
process.off('unhandledRejection', onUnhandled)
125+
resetDbChainMock()
126+
}
127+
})
128+
98129
/**
99130
* `--blocks '{}' --edges '[]'` used to lint perfectly clean, so a dry run gave
100131
* no hint that applying it would erase the workflow.

0 commit comments

Comments
 (0)