Skip to content

Commit 84ba80a

Browse files
authored
chore(workflows-as-code): remove post-merge leftovers and unify --run handling (#10569)
* chore(workflows-as-code): remove post-merge leftovers - name file references by path like every other kind: drop refs[].id, resolveRefsById and SourcePlanSummary.resolveId - drop file: arguments that repeat kindFinding's default, and inline the forwarding deploymentFinding wrapper - the cli builds a table's declaration path through its layout - realtime's edge write applies getWorkflowEdgeDropKind, keeping its protected-target check, instead of its own copy of the rule * fix(workflows-as-code): refuse a folder rename deployments/ still names with --run, and unify --run results - workspace apply --run --yes previews the whole apply before its first write, so what deployments/ refuses (E_WORKFLOW_RENAMED_IN_USE) writes and runs nothing - an apply without deployments/ moves a renamed workflow's deployment base entry with it, so the deployments write keeps the deployment - E_WORKFLOW_RENAMED_IN_USE points at the childWorkflow() reference when its compile located it - runs[].rateLimited is set by runTests, so workflows source apply reports it too * fix(workflows-as-code): move a renamed workflow's deployment entry when its own write was held or failed
1 parent c7c8a2f commit 84ba80a

16 files changed

Lines changed: 252 additions & 181 deletions

File tree

‎apps/realtime/src/database/operations.ts‎

Lines changed: 16 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -32,15 +32,15 @@ import {
3232
filterAcyclicEdges,
3333
filterUniqueWorkflowEdges,
3434
getWorkflowBlockNameConflict,
35-
getWorkflowEdgeScopeDropReason,
35+
getWorkflowEdgeDropKind,
3636
isKnownWorkflowTriggerBlock,
37-
isWorkflowAnnotationOnlyBlockType,
3837
isWorkflowBlockAncestorLocked,
3938
isWorkflowBlockProtected,
4039
MAX_WORKFLOW_BLOCKS,
4140
normalizeWorkflowEdgeSourceHandle,
4241
normalizeWorkflowEdgeTargetHandle,
4342
preserveProtectedWorkflowBlocks,
43+
type WorkflowEdgeDropKind,
4444
} from '@sim/workflow-types/workflow'
4545
import { and, eq, inArray, isNull, or, type SQL, sql } from 'drizzle-orm'
4646
import type { PgInsertValue } from 'drizzle-orm/pg-core'
@@ -121,6 +121,14 @@ const EDGE_UPSERT_SET = {
121121
targetHandle: sql`excluded.target_handle`,
122122
} as const
123123

124+
/** The stable `droppedCounts` key of each shared edge-drop rule, so counts aggregate across edges. */
125+
const EDGE_DROP_REASONS: Record<WorkflowEdgeDropKind, string> = {
126+
missing_block: 'missing block',
127+
annotation_only: 'annotation-only block',
128+
trigger_target: 'trigger block target',
129+
scope: 'scope boundary',
130+
}
131+
124132
interface FilterEdgesForPersistResult<T> {
125133
safeEdges: T[]
126134
droppedCounts: Record<string, number>
@@ -201,36 +209,16 @@ async function filterEdgesForPersist<T extends EdgeAddCandidate>(
201209
droppedCounts[reason] = (droppedCounts[reason] ?? 0) + 1
202210
}
203211

204-
// Mirrors the client's validateEdges rule order: missing block, protected
205-
// target, annotation-only block, trigger-block target, scope boundary.
206-
// `scopeDropReason`'s detail (which names the specific block ids/scopes)
207-
// is dropped in favor of a stable 'scope boundary' key so droppedCounts
208-
// aggregates across edges instead of gaining one free-text key per edge.
212+
// The rule every save applies (getWorkflowEdgeDropKind), with realtime's protected-target check
213+
// after its missing-block rule.
209214
const structurallyValidEdges = candidates.filter((edge) => {
210-
const sourceBlock = blocksById[edge.source]
211-
const targetBlock = blocksById[edge.target]
212-
213-
if (!sourceBlock || !targetBlock) {
214-
countDrop('missing block')
215-
return false
216-
}
217-
if (isWorkflowBlockProtected(edge.target, blocksById)) {
215+
const drop = getWorkflowEdgeDropKind(edge, blocksById, isKnownWorkflowTriggerBlock)
216+
if (drop !== 'missing_block' && isWorkflowBlockProtected(edge.target, blocksById)) {
218217
countDrop('protected target block')
219218
return false
220219
}
221-
if (
222-
isWorkflowAnnotationOnlyBlockType(sourceBlock.type) ||
223-
isWorkflowAnnotationOnlyBlockType(targetBlock.type)
224-
) {
225-
countDrop('annotation-only block')
226-
return false
227-
}
228-
if (isKnownWorkflowTriggerBlock(targetBlock)) {
229-
countDrop('trigger block target')
230-
return false
231-
}
232-
if (getWorkflowEdgeScopeDropReason(edge, blocksById)) {
233-
countDrop('scope boundary')
220+
if (drop) {
221+
countDrop(EDGE_DROP_REASONS[drop])
234222
return false
235223
}
236224
return true

‎apps/sim/lib/workflows/application/source-pipeline/plan.ts‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ import type { Principal } from '@sim/auth/principal'
22
import type {
33
BlockCatalog,
44
EnvReference,
5-
ResourceKind,
65
SourceBase,
76
SourceFingerprint,
87
WorkflowLockV1,
@@ -121,8 +120,6 @@ export interface SourcePlanSummary {
121120
workflowName?: string
122121
/** Each block of the planned graph, by id; absent for a refusal. */
123122
blocks?: ReadonlyArray<{ id: string; name: string }>
124-
/** The id the plan resolved for a resource the source names by key, or null. */
125-
resolveId(kind: ResourceKind, key: string): string | null
126123
}
127124

128125
/** The {@link SourcePlanSummary} of a plan or a refusal. */
@@ -134,7 +131,6 @@ export function summarizePlan(outcome: PlannedSource | RefusedSource): SourcePla
134131
references: outcome.compiledReferences?.references ?? [],
135132
envReferences: outcome.compiledReferences?.envReferences ?? [],
136133
sourceMetaChanged: false,
137-
resolveId: () => null,
138134
}
139135
}
140136
const { plan } = outcome
@@ -146,7 +142,6 @@ export function summarizePlan(outcome: PlannedSource | RefusedSource): SourcePla
146142
sourceMetaChanged: outcome.noop?.sourceMetaChanged ?? false,
147143
workflowName: plan.meta.name,
148144
blocks: Object.values(plan.blocks).map(({ id, name }) => ({ id, name })),
149-
resolveId: (kind, key) => plan.resources.toId(kind, key),
150145
}
151146
}
152147

‎apps/sim/lib/workspace-source/application/apply-workspace-source.ts‎

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -407,17 +407,31 @@ async function consumeStagedBlobs(target: StagingScope, consumed: StagedBlob[]):
407407
/**
408408
* Moves the base entry of each no-op that follows a workflow rename (an unchanged deployment) to
409409
* the new key, once that rename was written: the base then records the workflow under the new key
410-
* and no longer under the old one. A rename held back or stopped by a failed write moves nothing.
410+
* and no longer under the old one. Any other deployment entry still under the old key moves with
411+
* its workflow too, since its key is the workflow's: one this apply does not plan (an apply
412+
* without deployments/, as the first write of `--run`), or one whose own write was held or failed.
413+
* A rename held back or stopped by a failed write moves nothing.
411414
*/
412415
function moveUnwrittenWithRenames(base: WorkspaceBaseV1, changes: readonly PlannedChange[]): void {
416+
const plannedDeployments = new Set(
417+
changes.filter((change) => change.kind === 'deployment').map((change) => change.key)
418+
)
413419
for (const change of changes) {
414-
if (change.action !== 'noop' || change.renamedFrom === undefined) continue
420+
const from = change.renamedFrom
421+
if (from === undefined) continue
415422
const moved =
416423
base.resources[resourceAddress('workflow', change.key)] !== undefined &&
417-
base.resources[resourceAddress('workflow', change.renamedFrom)] === undefined
424+
base.resources[resourceAddress('workflow', from)] === undefined
418425
if (!moved) continue
419-
if (change.base) base.resources[resourceAddress(change.kind, change.key)] = change.base
420-
dropRenamedEntry(base, change)
426+
if (change.action === 'noop') {
427+
if (change.base) base.resources[resourceAddress(change.kind, change.key)] = change.base
428+
dropRenamedEntry(base, change)
429+
continue
430+
}
431+
const deployment = base.resources[resourceAddress('deployment', from)]
432+
if (change.kind !== 'workflow' || plannedDeployments.has(from) || !deployment) continue
433+
delete base.resources[resourceAddress('deployment', from)]
434+
base.resources[resourceAddress('deployment', change.key)] = deployment
421435
}
422436
}
423437

‎apps/sim/lib/workspace-source/application/deployments.integration.ts‎

Lines changed: 66 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1581,6 +1581,39 @@ export default workflow('Caller', {}, () => {
15811581
}
15821582
)
15831583

1584+
check(
1585+
'renames a folder and its deployment file in the two writes --run sends, keeping the deployment',
1586+
async () => {
1587+
const { workspaceId, id, files, base } = await deployedWorkspace()
1588+
const before = await deployState(id)
1589+
const renamed = moved(files, 'nightly', 'evening')
1590+
delete renamed[DEPLOYMENT]
1591+
1592+
const first = await apply(workspaceId, asUnchanged(renamed, workspaceId), {
1593+
base,
1594+
kinds: ['workflow'],
1595+
})
1596+
expect(first.failed).toBeUndefined()
1597+
const sent: Files = {
1598+
...asUnchanged({ ...renamed, ...first.files }, workspaceId),
1599+
'deployments/evening.ts': files[DEPLOYMENT],
1600+
}
1601+
const second = await apply(workspaceId, sent, { base: first.base })
1602+
1603+
expect(second.failed).toBeUndefined()
1604+
expect(codes(second.diagnostics)).toEqual([])
1605+
expect(actions(second.plan.filter((change) => change.action !== 'noop'))).toEqual([])
1606+
const after = await deployState(id)
1607+
expect([after.isDeployed, after.versions, after.schedules]).toEqual([
1608+
true,
1609+
before.versions,
1610+
before.schedules,
1611+
])
1612+
expect(second.base.resources['deployment:evening']?.id).toBe(id)
1613+
expect(second.base.resources['deployment:nightly']).toBeUndefined()
1614+
}
1615+
)
1616+
15841617
/** Declares a secret the workspace has no value for, so a workflow reading it is held back. */
15851618
const MISSING_SECRET = {
15861619
'secrets.ts': `// @sim-sdk 1
@@ -1640,11 +1673,42 @@ export default defineSecrets({
16401673
expect(
16411674
refused.diagnostics
16421675
.filter((finding) => finding.code === 'E_WORKFLOW_RENAMED_IN_USE')
1643-
.map((finding) => finding.file)
1644-
).toEqual([CALLER])
1676+
.map((finding) => [finding.file, finding.line])
1677+
).toEqual([
1678+
[
1679+
CALLER,
1680+
caller.split('\n').findIndex((line) => line.includes("childWorkflow('nightly')")) + 1,
1681+
],
1682+
])
16451683
expect(Object.keys((await getAll(workspaceId, ['workflow'])).files)).toContain(WORKFLOW)
16461684
})
16471685

1686+
check(
1687+
'moves the deployment base entry with a written folder rename when its deployment write fails',
1688+
async () => {
1689+
const { workspaceId, id, files, base } = await deployedWorkspace()
1690+
const renamed = moved(files, 'nightly', 'evening')
1691+
delete renamed[DEPLOYMENT]
1692+
const sent: Files = {
1693+
...asUnchanged(renamed, workspaceId),
1694+
'deployments/evening.ts': answerChat('moved-folder-chat'),
1695+
}
1696+
const stopped = vi
1697+
.spyOn(replaceWorkflowChatDeployment, 'execute')
1698+
.mockRejectedValueOnce(new Error('process stopped'))
1699+
try {
1700+
const result = await apply(workspaceId, sent, { base })
1701+
1702+
expect(result.failed?.key).toBe('evening')
1703+
expect(result.base.resources['workflow:evening']?.id).toBe(id)
1704+
expect(result.base.resources['deployment:evening']?.id).toBe(id)
1705+
expect(result.base.resources['deployment:nightly']).toBeUndefined()
1706+
} finally {
1707+
stopped.mockRestore()
1708+
}
1709+
}
1710+
)
1711+
16481712
check(
16491713
'keeps the deployment under the old key when the renamed folder is held back',
16501714
async () => {

‎apps/sim/lib/workspace-source/application/in-use.ts‎

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,16 @@ import { db } from '@sim/db'
99
import { workflow, workflowBlocks, workflowDeploymentVersion } from '@sim/db/schema'
1010
import { createLogger } from '@sim/logger'
1111
import { getPostgresErrorCode } from '@sim/utils/errors'
12-
import { SOURCE_ENTRY_FILE } from '@sim/workflow-code/limits'
12+
import type { SourceSpan } from '@sim/workflow-code'
1313
import type { WorkspaceKind } from '@sim/workspace-code'
1414
import { deploymentDeclarationPath } from '@sim/workspace-code/kinds/deployment'
15-
import { workflowFolder } from '@sim/workspace-code/kinds/workflow'
1615
import { sql } from 'drizzle-orm'
17-
import { kindFinding, refDeletedFinding, where } from '@/lib/workspace-source/application/findings'
16+
import {
17+
kindFinding,
18+
refDeletedFinding,
19+
referenceSite,
20+
where,
21+
} from '@/lib/workspace-source/application/findings'
1822
import type {
1923
PlannedChange,
2024
WorkspaceSourceDiagnostic,
@@ -254,27 +258,24 @@ export async function checkDeletesInUse(
254258

255259
/**
256260
* `E_WORKFLOW_RENAMED_IN_USE` on `user` (a deployment file, or a workflow folder) for still naming
257-
* workflow `renamed.renamedFrom`, whose folder this apply renames to `renamed.key`.
261+
* workflow `renamed.renamedFrom`, whose folder this apply renames to `renamed.key`: at the
262+
* reference when its compile located it (`span`).
258263
*/
259264
function renamedInUseFinding(
260265
user: Pick<PlannedChange, 'kind' | 'key'>,
261-
renamed: { key: string; renamedFrom: string }
266+
renamed: { key: string; renamedFrom: string },
267+
span?: SourceSpan
262268
): WorkspaceSourceDiagnostic {
263-
const deployment = user.kind === 'deployment'
269+
const hint =
270+
user.kind === 'deployment'
271+
? `Rename ${deploymentDeclarationPath(renamed.renamedFrom)} to ${deploymentDeclarationPath(renamed.key)}.`
272+
: `Rename childWorkflow('${renamed.renamedFrom}') to childWorkflow('${renamed.key}') there.`
264273
return kindFinding(
265274
user.kind,
266275
user.key,
267276
'E_WORKFLOW_RENAMED_IN_USE',
268277
`${where(user.kind, user.key)} names workflow "${renamed.renamedFrom}", whose folder this apply renames to ${where('workflow', renamed.key)}.`,
269-
deployment
270-
? {
271-
hint: `Rename ${deploymentDeclarationPath(renamed.renamedFrom)} to ${deploymentDeclarationPath(renamed.key)}.`,
272-
file: deploymentDeclarationPath(user.key),
273-
}
274-
: {
275-
hint: `Rename childWorkflow('${renamed.renamedFrom}') to childWorkflow('${renamed.key}') there.`,
276-
file: `${workflowFolder(user.key)}/${SOURCE_ENTRY_FILE}`,
277-
}
278+
{ hint, ...referenceSite(user, span) }
278279
)
279280
}
280281

@@ -302,19 +303,19 @@ export async function checkRenamesInUse(
302303
// A held user is not written and its errors refuse nothing, so its rename carries the refusal.
303304
// A held folder names the old key both in its refs and as stored: it is reported once.
304305
const reported = new Set<string>()
305-
const refuse = (user: PlannedChange, renamed: RenamedWorkflow) => {
306+
const refuse = (user: PlannedChange, renamed: RenamedWorkflow, span?: SourceSpan) => {
306307
const pair = `${user.kind}:${user.key}>${renamed.key}`
307308
if (reported.has(pair)) return
308309
reported.add(pair)
309310
const carrier = user.held ? renamed : user
310-
carrier.diagnostics.push(renamedInUseFinding(user, renamed))
311+
carrier.diagnostics.push(renamedInUseFinding(user, renamed, span))
311312
}
312313
// Declared folders judged by their stored workflow, whose text names the old key.
313314
const stored = new Map<string, PlannedChange>()
314315
for (const change of changes) {
315316
for (const ref of change.refs ?? []) {
316317
const renamed = ref.kind === 'workflow' ? byOldKey.get(ref.key) : undefined
317-
if (renamed) refuse(change, renamed)
318+
if (renamed) refuse(change, renamed, ref.span)
318319
}
319320
if (change.kind === 'workflow' && change.storedId && change.decl) {
320321
if (!writesRefs(change, unchanged)) stored.set(change.storedId, change)

0 commit comments

Comments
 (0)