Skip to content

Commit fb42142

Browse files
committed
fix(lint): stop a child's response check at the first else row, on a root cycle, and for a __proto__ key
Rows after a condition's first else never run, so only those up to it must be wired; a root cycle never runs to the Response block; and the canonical graph is built with own properties so a block keyed __proto__ is kept.
1 parent 20f16f9 commit fb42142

5 files changed

Lines changed: 111 additions & 17 deletions

File tree

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

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -134,8 +134,9 @@ export function getDynamicHandleRows(
134134

135135
/**
136136
* 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
137+
* canonical blocks): every route of a router, and a condition's rows up to its first else row (by
138+
* stored title, as the executor finds it), which runs when none before it matches; none for a
139+
* condition without one or branches never saved. `undefined` for a block
139140
* without branches.
140141
*/
141142
export function getAlwaysTakenBranchHandles(
@@ -145,12 +146,14 @@ export function getAlwaysTakenBranchHandles(
145146
if (subBlockId === null) return undefined
146147
const stored = parseStructuredValue(block.subBlocks[subBlockId]?.value) ?? []
147148
if (block.type === 'condition') {
148-
const hasElse = stored.some((row) =>
149+
const elseAt = stored.findIndex((row) =>
149150
isElseConditionTitle((row as { title?: unknown } | null)?.title)
150151
)
151-
return stored.length > 0 && hasElse
152-
? getConditionRows(block.id, stored).map((row) => `condition-${row.id}`)
153-
: []
152+
return elseAt === -1
153+
? []
154+
: getConditionRows(block.id, stored)
155+
.slice(0, elseAt + 1)
156+
.map((row) => `condition-${row.id}`)
154157
}
155158
return stored.length > 0 ? getRouterRows(block.id, stored).map((row) => `router-${row.id}`) : []
156159
}

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

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest'
33
import { getBlock } from '@/blocks/registry'
44
import { getToolParams } from '@/tools/metadata'
55
import {
6+
alwaysEndsAtResponseBlock,
67
collectTableBlockFieldIssues,
78
collectWorkflowFieldIssues,
89
collectWorkflowTableIds,
@@ -113,6 +114,55 @@ function baseBlock(id: string, type: string, name: string, subBlocks: Record<str
113114
}
114115
}
115116

117+
describe('alwaysEndsAtResponseBlock', () => {
118+
const block = (type: string, subBlocks: Record<string, { value: unknown }> = {}) => ({
119+
type,
120+
subBlocks,
121+
})
122+
const edge = (source: string, target: string, sourceHandle = 'source') => ({
123+
source,
124+
target,
125+
sourceHandle,
126+
})
127+
128+
it('needs only the branches up to the first else row, the last a run can take', () => {
129+
const conditions = JSON.stringify([
130+
{ id: 'g-if', title: 'if', value: 'true' },
131+
{ id: 'g-else', title: 'else', value: '' },
132+
{ id: 'g-after', title: 'else if', value: 'true' },
133+
])
134+
const graph = {
135+
blocks: {
136+
start: block('start_trigger'),
137+
gate: block('condition', { conditions: { value: conditions } }),
138+
yes: block('response'),
139+
no: block('response'),
140+
},
141+
edges: [
142+
edge('start', 'gate'),
143+
edge('gate', 'yes', 'condition-g-if'),
144+
edge('gate', 'no', 'condition-g-else'),
145+
],
146+
}
147+
148+
expect(alwaysEndsAtResponseBlock(graph)).toBe(true)
149+
})
150+
151+
it('is false for a root cycle, whose blocks never run to the Response block', () => {
152+
const graph = {
153+
blocks: {
154+
start: block('start_trigger'),
155+
a: block('function'),
156+
b: block('function'),
157+
reply: block('response'),
158+
},
159+
edges: [edge('start', 'a'), edge('a', 'b'), edge('b', 'a')],
160+
}
161+
162+
expect(alwaysEndsAtResponseBlock(graph)).toBe(false)
163+
})
164+
})
165+
116166
describe('lintEditedWorkflowState', () => {
117167
it('reports orphan blocks but allows unconnected condition/router branches', () => {
118168
const workflowState = {

‎packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -549,16 +549,26 @@ describe('sim workspaces source check', () => {
549549
'gate.else.to(other)'
550550
)
551551
)
552+
writeFile(
553+
'workflows/proto/workflow.ts',
554+
workflowFile(
555+
"const start = trigger.start('Start', { inputFormat: { q: 'string' } })",
556+
"const reply = response('__proto__', { body: { mobile: start.q } })",
557+
'start.to(reply)'
558+
)
559+
)
552560
writeFile(
553561
'workflows/parent/workflow.ts',
554562
workflowFile(
555563
"const start = trigger.start('Start', { inputFormat: { q: 'string' } })",
556564
"const maybe = runWorkflow('Maybe', { workflowId: childWorkflow('branchy'), inputMapping: { q: start.q } })",
557565
"const always = runWorkflow('Always', { workflowId: childWorkflow('covered'), inputMapping: { q: start.q } })",
558-
"const use = fn('Use', { code: js`return [${maybe.result.mobile}, ${always.result.mobile}]` })",
566+
"const named = runWorkflow('Named', { workflowId: childWorkflow('proto'), inputMapping: { q: start.q } })",
567+
"const use = fn('Use', { code: js`return [${maybe.result.mobile}, ${always.result.mobile}, ${named.result.mobile}]` })",
559568
'start.to(maybe)',
560569
'maybe.to(always)',
561-
'always.to(use)'
570+
'always.to(named)',
571+
'named.to(use)'
562572
)
563573
)
564574

@@ -571,6 +581,9 @@ describe('sim workspaces source check', () => {
571581
expect.objectContaining({
572582
message: expect.stringContaining('<always.result.mobile> reads mobile'),
573583
}),
584+
expect.objectContaining({
585+
message: expect.stringContaining('<named.result.mobile> reads mobile'),
586+
}),
574587
])
575588
})
576589

‎packages/workflow-code/src/responds.ts‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,20 +8,22 @@ import {
88
} from '@sim/workflow-types/workflow'
99
import { storedTitle } from './canonicalize/branches'
1010
import type { CanonicalBlock, CanonicalWorkflow, Port } from './model'
11+
import { setOwn } from './records'
1112

1213
/**
1314
* The branches `block` always takes one of (as `getAlwaysTakenBranchHandles` reads stored
14-
* blocks): every route of a router, and every row of a condition with an else row (by stored
15-
* title, as the executor finds it); none for branches never saved.
15+
* blocks): every route of a router, and a condition's rows up to its first else row (by stored
16+
* title, as the executor finds it); none for a condition without one or branches never saved.
1617
*/
1718
function alwaysTakenBranches(block: CanonicalBlock): ResponseGraphBlock['branches'] {
1819
const branches = block.branches
1920
if (!branches) return undefined
2021
const rows = branches.rows ?? []
21-
const hasElse = rows.some((row, index) =>
22+
if (branches.kind === 'router') return rows.map((row) => row.key)
23+
const elseAt = rows.findIndex((row, index) =>
2224
isElseConditionTitle(storedTitle(branches.kind, row, index, rows.length))
2325
)
24-
return branches.kind === 'condition' && !hasElse ? [] : rows.map((row) => row.key)
26+
return elseAt === -1 ? [] : rows.slice(0, elseAt + 1).map((row) => row.key)
2527
}
2628

2729
function portName(port: Port): string {
@@ -37,12 +39,12 @@ export function respondsOnEveryRun(workflow: CanonicalWorkflow): boolean {
3739
const blocks: Record<string, ResponseGraphBlock> = {}
3840
for (const [key, block] of Object.entries(workflow.blocks)) {
3941
const branches = alwaysTakenBranches(block)
40-
blocks[key] = {
42+
setOwn(blocks, key, {
4143
type: block.type,
4244
enabled: block.enabled,
4345
parentId: block.parent,
4446
...(branches !== undefined && { branches }),
45-
}
47+
})
4648
}
4749
return alwaysEndsAtResponse(
4850
blocks,

‎packages/workflow-types/src/workflow.ts‎

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -714,7 +714,8 @@ export interface ResponseGraphBlock {
714714
parentId: string | null
715715
/**
716716
* Set on a condition or router block: the branches a run always takes one of, empty when a run
717-
* can take none (a condition without an else branch, or branches never saved).
717+
* can take none (a condition without an else branch, or branches never saved). A condition's
718+
* end at its first else row: the rows after it never run.
718719
*/
719720
branches?: readonly string[]
720721
}
@@ -729,13 +730,29 @@ export interface ResponseGraphEdge {
729730
port: string
730731
}
731732

733+
/** Whether the graph of `successors` (with each target's incoming count in `pending`) has a cycle. */
734+
function hasCycle(successors: Map<string, string[]>, pending: Map<string, number>): boolean {
735+
const ready = [...successors.keys()].filter((id) => !pending.has(id))
736+
let visited = 0
737+
for (let id = ready.pop(); id !== undefined; id = ready.pop()) {
738+
visited += 1
739+
for (const next of successors.get(id) ?? []) {
740+
const left = (pending.get(next) ?? 0) - 1
741+
pending.set(next, left)
742+
if (left === 0) ready.push(next)
743+
}
744+
}
745+
const nodes = new Set([...successors.keys(), ...pending.keys()])
746+
return visited < nodes.size
747+
}
748+
732749
/**
733750
* Whether every run of a workflow ends at an enabled Response block at its root, so a caller's
734751
* `result` is always that block's output (`{ data, status, headers }`) rather than the output of
735752
* whichever block the run ended at. True when there is a root Response and every other root block
736753
* that runs always goes on to one that runs (its out edge, a container's end edge, or an edge from
737-
* every branch it always takes one of): the root graph is acyclic, so every run then ends at a
738-
* Response.
754+
* every branch it always takes one of), and the root graph is acyclic: every run then ends at a
755+
* Response. A root cycle never runs (its blocks wait on each other), so it makes this false.
739756
*/
740757
export function alwaysEndsAtResponse(
741758
blocks: Readonly<Record<string, ResponseGraphBlock>>,
@@ -745,13 +762,22 @@ export function alwaysEndsAtResponse(
745762
const block = Object.hasOwn(blocks, id) ? blocks[id] : undefined
746763
return block?.enabled === true && !isWorkflowAnnotationOnlyBlockType(block.type)
747764
}
765+
const isRoot = (id: string) => blocks[id]?.parentId === null
748766
const portsBySource = new Map<string, Set<string>>()
767+
const successors = new Map<string, string[]>()
768+
const pending = new Map<string, number>()
749769
for (const edge of edges) {
750770
if (!runs(edge.source) || !runs(edge.target)) continue
751771
const ports = portsBySource.get(edge.source) ?? new Set<string>()
752772
ports.add(edge.port)
753773
portsBySource.set(edge.source, ports)
774+
if (!isRoot(edge.source) || !isRoot(edge.target)) continue
775+
const next = successors.get(edge.source) ?? []
776+
next.push(edge.target)
777+
successors.set(edge.source, next)
778+
pending.set(edge.target, (pending.get(edge.target) ?? 0) + 1)
754779
}
780+
if (hasCycle(successors, pending)) return false
755781
let responds = false
756782
for (const [id, block] of Object.entries(blocks)) {
757783
if (!runs(id) || block.parentId !== null) continue

0 commit comments

Comments
 (0)