Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/docs/content/docs/workflows/code/diagnostics.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -127,9 +127,9 @@ Reading the stored workflow in a get.
| Code | Meaning |
| --- | --- |
| `E_CANON_LEGACY_NAME_COLLISION` | Two stored names normalize alike; the loser is keyed `key~n`. |
| `E_CANON_EDGE_SCOPE` | A stored edge crosses subflow scopes. |
| `W_CANON_RESERVED_NAME` | A stored name normalizes to a reserved key. |
| `W_CANON_DANGLING_EDGE` | A stored edge to a missing block; dropped. |
| `W_CANON_EDGE_DROPPED` | A stored edge every save drops (to or from a note, into a trigger, or across a loop or parallel boundary); left out of the source, and the next write removes it. |
| `W_CANON_DANGLING_PARENT` | A parent that does not exist; the block is placed at the root and the raw parent kept. |
| `W_CANON_RAW_HANDLE` | An unknown edge handle, kept as a raw port. |
| `W_CANON_UNKNOWN_BLOCK_TYPE` | A type the catalog does not have; params kept. |
Expand Down
2 changes: 1 addition & 1 deletion apps/docs/content/docs/workflows/code/syntax.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ In a JavaScript file, `$ref.block.path` reads another block's output and `$env.N
| `cond.key.to(x)` | one branch of a condition or router |
| `container.to(x)` | what runs after the loop or parallel finishes |

Refused: `.to()` on a condition or router itself (`E_NO_DEFAULT_OUTPUT`; wire a branch), a branch that does not exist (`E_UNKNOWN_BRANCH`), an edge into a trigger (`E_TARGET_TRIGGER`), `onError` on a block with no error port (`E_ERROR_PORT_UNSUPPORTED`), an edge to or from a note (`E_EDGE_NOTE`), an edge across loop or parallel scopes (`E_EDGE_SCOPE`), a repeated edge (`E_DUPLICATE_EDGE`) and a cycle (`E_EDGE_CYCLE`). Repeat work with a `loop` instead.
Refused: `.to()` on a condition or router itself (`E_NO_DEFAULT_OUTPUT`; wire a branch), a branch that does not exist (`E_UNKNOWN_BRANCH`), an edge into a trigger (`E_TARGET_TRIGGER`), `onError` on a block with no error port (`E_ERROR_PORT_UNSUPPORTED`), an edge to or from a note (`E_EDGE_NOTE`), an edge across loop or parallel scopes (`E_EDGE_SCOPE`), a repeated edge (`E_DUPLICATE_EDGE`) and a cycle (`E_EDGE_CYCLE`). Repeat work with a `loop` instead. A saved edge into a trigger, to or from a note, or across loop or parallel scopes never appears in `source get`: every save drops it, so the read leaves it out with `W_CANON_EDGE_DROPPED` and the next write removes it.

## Comments

Expand Down
20 changes: 10 additions & 10 deletions apps/docs/openapi-v2-workflows.json
Original file line number Diff line number Diff line change
Expand Up @@ -19929,9 +19929,9 @@
"E_SOURCE_META_DUPLICATE_IDENT",
"E_SOURCE_META_ANCHOR",
"E_CANON_LEGACY_NAME_COLLISION",
"E_CANON_EDGE_SCOPE",
"W_CANON_RESERVED_NAME",
"W_CANON_DANGLING_EDGE",
"W_CANON_EDGE_DROPPED",
"W_CANON_DANGLING_PARENT",
"W_CANON_RAW_HANDLE",
"W_CANON_UNKNOWN_BLOCK_TYPE",
Expand Down Expand Up @@ -20418,9 +20418,9 @@
"E_SOURCE_META_DUPLICATE_IDENT",
"E_SOURCE_META_ANCHOR",
"E_CANON_LEGACY_NAME_COLLISION",
"E_CANON_EDGE_SCOPE",
"W_CANON_RESERVED_NAME",
"W_CANON_DANGLING_EDGE",
"W_CANON_EDGE_DROPPED",
"W_CANON_DANGLING_PARENT",
"W_CANON_RAW_HANDLE",
"W_CANON_UNKNOWN_BLOCK_TYPE",
Expand Down Expand Up @@ -21416,9 +21416,9 @@
"E_SOURCE_META_DUPLICATE_IDENT",
"E_SOURCE_META_ANCHOR",
"E_CANON_LEGACY_NAME_COLLISION",
"E_CANON_EDGE_SCOPE",
"W_CANON_RESERVED_NAME",
"W_CANON_DANGLING_EDGE",
"W_CANON_EDGE_DROPPED",
"W_CANON_DANGLING_PARENT",
"W_CANON_RAW_HANDLE",
"W_CANON_UNKNOWN_BLOCK_TYPE",
Expand Down Expand Up @@ -22390,9 +22390,9 @@
"E_SOURCE_META_DUPLICATE_IDENT",
"E_SOURCE_META_ANCHOR",
"E_CANON_LEGACY_NAME_COLLISION",
"E_CANON_EDGE_SCOPE",
"W_CANON_RESERVED_NAME",
"W_CANON_DANGLING_EDGE",
"W_CANON_EDGE_DROPPED",
"W_CANON_DANGLING_PARENT",
"W_CANON_RAW_HANDLE",
"W_CANON_UNKNOWN_BLOCK_TYPE",
Expand Down Expand Up @@ -23174,9 +23174,9 @@
"E_SOURCE_META_DUPLICATE_IDENT",
"E_SOURCE_META_ANCHOR",
"E_CANON_LEGACY_NAME_COLLISION",
"E_CANON_EDGE_SCOPE",
"W_CANON_RESERVED_NAME",
"W_CANON_DANGLING_EDGE",
"W_CANON_EDGE_DROPPED",
"W_CANON_DANGLING_PARENT",
"W_CANON_RAW_HANDLE",
"W_CANON_UNKNOWN_BLOCK_TYPE",
Expand Down Expand Up @@ -28256,9 +28256,9 @@
"E_SOURCE_META_DUPLICATE_IDENT",
"E_SOURCE_META_ANCHOR",
"E_CANON_LEGACY_NAME_COLLISION",
"E_CANON_EDGE_SCOPE",
"W_CANON_RESERVED_NAME",
"W_CANON_DANGLING_EDGE",
"W_CANON_EDGE_DROPPED",
"W_CANON_DANGLING_PARENT",
"W_CANON_RAW_HANDLE",
"W_CANON_UNKNOWN_BLOCK_TYPE",
Expand Down Expand Up @@ -28851,9 +28851,9 @@
"E_SOURCE_META_DUPLICATE_IDENT",
"E_SOURCE_META_ANCHOR",
"E_CANON_LEGACY_NAME_COLLISION",
"E_CANON_EDGE_SCOPE",
"W_CANON_RESERVED_NAME",
"W_CANON_DANGLING_EDGE",
"W_CANON_EDGE_DROPPED",
"W_CANON_DANGLING_PARENT",
"W_CANON_RAW_HANDLE",
"W_CANON_UNKNOWN_BLOCK_TYPE",
Expand Down Expand Up @@ -29271,9 +29271,9 @@
"E_SOURCE_META_DUPLICATE_IDENT",
"E_SOURCE_META_ANCHOR",
"E_CANON_LEGACY_NAME_COLLISION",
"E_CANON_EDGE_SCOPE",
"W_CANON_RESERVED_NAME",
"W_CANON_DANGLING_EDGE",
"W_CANON_EDGE_DROPPED",
"W_CANON_DANGLING_PARENT",
"W_CANON_RAW_HANDLE",
"W_CANON_UNKNOWN_BLOCK_TYPE",
Expand Down Expand Up @@ -30148,9 +30148,9 @@
"E_SOURCE_META_DUPLICATE_IDENT",
"E_SOURCE_META_ANCHOR",
"E_CANON_LEGACY_NAME_COLLISION",
"E_CANON_EDGE_SCOPE",
"W_CANON_RESERVED_NAME",
"W_CANON_DANGLING_EDGE",
"W_CANON_EDGE_DROPPED",
"W_CANON_DANGLING_PARENT",
"W_CANON_RAW_HANDLE",
"W_CANON_UNKNOWN_BLOCK_TYPE",
Expand Down Expand Up @@ -30568,9 +30568,9 @@
"E_SOURCE_META_DUPLICATE_IDENT",
"E_SOURCE_META_ANCHOR",
"E_CANON_LEGACY_NAME_COLLISION",
"E_CANON_EDGE_SCOPE",
"W_CANON_RESERVED_NAME",
"W_CANON_DANGLING_EDGE",
"W_CANON_EDGE_DROPPED",
"W_CANON_DANGLING_PARENT",
"W_CANON_RAW_HANDLE",
"W_CANON_UNKNOWN_BLOCK_TYPE",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3517,3 +3517,141 @@ describe('workflow variables in source', () => {
expect(allowed.diff.variables.removed).toEqual(['threshold'])
})
})

describe('stored edges every save drops', () => {
/**
* Seeds the fixture workflow plus a stored edge from Score into the Start trigger, which every
* save drops (`validateEdges`), with Start locked so a gate that judged the edge's absence as a
* removal would refuse.
*/
async function seedEdgeIntoLockedTrigger() {
const seeded = await seedWorkflow()
const droppedId = generateId()
await db.insert(workflowEdges).values({
id: droppedId,
workflowId: seeded.workflowId,
sourceBlockId: seeded.scoreId,
targetBlockId: seeded.startId,
sourceHandle: 'source',
targetHandle: 'target',
})
await db
.update(workflowBlocks)
.set({ updatedAt: new Date(), locked: true })
.where(eq(workflowBlocks.id, seeded.startId))
return { ...seeded, droppedId }
}

async function storedEdgeIds(workflowId: string): Promise<string[]> {
const rows = await db
.select({ id: workflowEdges.id })
.from(workflowEdges)
.where(eq(workflowEdges.workflowId, workflowId))
return rows.map((row) => row.id).sort(compareStrings)
}

check(
'get leaves an edge into a trigger out with a warning, and applying it unchanged is a no-op',
async () => {
const seeded = await seedEdgeIntoLockedTrigger()
const source = await getSource(seeded.workflowId)
expect(source.diagnostics.map((d) => d.code)).toContain('W_CANON_EDGE_DROPPED')
const before = await snapshot(seeded.workflowId)

const result = await apply(source, source.files)

expect(result.applied).toBe(false)
expect(result.diff.noop).toBe(true)
expect(await snapshot(seeded.workflowId)).toEqual(before)
expect(await storedEdgeIds(seeded.workflowId)).toContain(seeded.droppedId)
}
)

check(
'moving a block out of a loop does not bring back its dropped edge into a locked block',
async () => {
const workflowId = generateId()
const ids = {
start: generateId(),
loop: generateId(),
child: generateId(),
target: generateId(),
dropped: generateId(),
}
const now = new Date()
await db.insert(workflow).values({
id: workflowId,
userId: ownerId,
workspaceId,
name: `Source apply ${workflowId}`,
lastSynced: now,
createdAt: now,
updatedAt: now,
})
const block = (id: string, type: string, name: string, extra: Partial<BlockState> = {}) =>
({
id,
type,
name,
position: { x: 0, y: 0 },
subBlocks: {},
outputs: {},
enabled: true,
...extra,
}) as BlockState
const saved = await saveWorkflowToNormalizedTables(workflowId, {
blocks: {
[ids.start]: block(ids.start, 'start_trigger', 'Start'),
[ids.loop]: block(ids.loop, 'loop', 'Repeat', { data: { loopType: 'for', count: 2 } }),
[ids.child]: block(ids.child, 'function', 'Child', {
subBlocks: { code: { id: 'code', type: 'code', value: 'return 1' } },
data: { parentId: ids.loop, extent: 'parent' },
}),
[ids.target]: block(ids.target, 'function', 'Target', {
subBlocks: { code: { id: 'code', type: 'code', value: 'return 2' } },
locked: true,
}),
},
edges: [
{ id: generateId(), source: ids.start, target: ids.loop },
{
id: generateId(),
source: ids.loop,
target: ids.child,
sourceHandle: 'loop-start-source',
},
{ id: ids.dropped, source: ids.child, target: ids.target },
],
loops: {},
parallels: {},
})
if (!saved.success) throw new Error(`Seeding the workflow failed: ${saved.error}`)
const source = await getSource(workflowId)
expect(source.diagnostics.map((d) => d.code)).toContain('W_CANON_EDGE_DROPPED')
const entry = source.files['workflow.ts']
const child = entry.match(/^ +const (\w+) = fn\('Child'.*\n/m)
if (!child) throw new Error(`The source declares no Child block:\n${entry}`)
const moved = entry
.replace(child[0], '')
.replace(new RegExp(`^ +\\w+\\.to\\(${child[1]}\\)\\n`, 'm'), '')
.replace(/^}\)\s*$/m, `${child[0].trim()}\n})\n`)

const result = await apply(source, { ...source.files, 'workflow.ts': moved })

expect(result.applied).toBe(true)
expect(await storedEdgeIds(workflowId)).not.toContain(ids.dropped)
}
)

check('an apply that writes removes such an edge and counts it as removed', async () => {
const seeded = await seedEdgeIntoLockedTrigger()
const source = await getSource(seeded.workflowId)

const result = await apply(source, edit(source.files, SCORE_CODE, 'return 7'))

expect(result.applied).toBe(true)
expect(result.diff.edges).toEqual({ added: 0, removed: 1 })
expect(result.diagnostics.map((d) => d.code)).toContain('W_CANON_EDGE_DROPPED')
expect(await storedEdgeIds(seeded.workflowId)).toEqual([seeded.edgeId])
})
})
7 changes: 6 additions & 1 deletion apps/sim/lib/workflows/application/source-commit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ import {
saveWorkflowToNormalizedTables,
} from '@/lib/workflows/persistence/utils'
import { parseWorkflowVariables } from '@/lib/workflows/variables/parse'
import { validateEdges } from '@/stores/workflows/workflow/edge-validation'

/** What a commit (or a dry run's preview of one) stores, after persistence preparation. */
interface CommittedGraph {
Expand Down Expand Up @@ -318,8 +319,12 @@ export async function commitSourceReplace(args: ExistingDraftCommit): Promise<Co
blocks: mergeConcurrentLayout(plan.blocks, current.state.blocks, args.stored.state.blocks),
edges: plan.edges,
}
// A save drops these edges whatever the merge keeps, and the plan never holds them.
assertLockedBlocksPreserved(
{ blocks: current.state.blocks, edges: current.state.edges },
{
blocks: current.state.blocks,
edges: validateEdges(current.state.edges, current.state.blocks).valid,
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
},
next
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
)
return plan.variables === undefined ? next : { ...next, variables: plan.variables }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,12 @@ function boundLock(identity: LockIdentity, submitted: WorkflowLockV1): WorkflowL
return { version: 1, blocks, variables: identity.variables }
}

/** The stored-edge findings of edges the source leaves out because every save drops them. */
const DROPPED_EDGE_CODES: ReadonlySet<string> = new Set([
'W_CANON_DANGLING_EDGE',
'W_CANON_EDGE_DROPPED',
])

/**
* Normalizes the changed values, snapshots MCP tool output schemas, lays out new blocks, lints the
* graph, refuses ids of another workspace's resources, and gathers every finding pinned to the
Expand Down Expand Up @@ -266,7 +272,16 @@ export async function finalizePlan(
pending,
keyOf: keyOfId,
})
const noop = !isNew && canonicalDiff.noop
// Stored edges a write removes though the source never held them: the ones every save drops.
const writtenEdgeIds = new Set(edges.map((edge) => edge.id))
const removedBySave = noop
? []
: gated.droppedStoredEdges.filter((edge) => !writtenEdgeIds.has(edge.id))
const serverFindings = [
...(removedBySave.length > 0
? resolved.storedCanonical.diagnostics.filter((d) => DROPPED_EDGE_CODES.has(d.code))
: []),
...resolved.keptDiagnostics,
...resolved.materializeDiagnostics,
...refusals.sourceRefusals,
Expand All @@ -287,7 +302,6 @@ export async function finalizePlan(
}
}

const noop = !isNew && canonicalDiff.noop
const mintedIds: Record<string, string> = {}
for (const entry of materialized.entries) {
if (entry.status === 'created' && entry.idSource === 'minted') mintedIds[entry.key] = entry.id
Expand All @@ -300,6 +314,18 @@ export async function finalizePlan(
const compiledSource = { hints: compiled.hints, workflow: compiledWorkflow }
const lockAfter = boundLock(materialized.identity, lock)

const summary = summarizeDiff(
canonicalDiff,
resolved.storedCanonical,
{ workflow: materialized.workflow, identity: materialized.identity },
noop,
metaChanged
)
const diff = {
...summary,
edges: { ...summary.edges, removed: summary.edges.removed + removedBySave.length },
}

return {
plan: {
meta,
Expand All @@ -310,13 +336,7 @@ export async function finalizePlan(
storedVariables:
variables === undefined ? state.variables : (parseWorkflowVariables(variables) ?? {}),
diagnostics,
diff: summarizeDiff(
canonicalDiff,
resolved.storedCanonical,
{ workflow: materialized.workflow, identity: materialized.identity },
noop,
metaChanged
),
diff,
metaChanged,
mintedIds,
identity: materialized.identity,
Expand Down
Loading
Loading