Skip to content

Commit 453014e

Browse files
committed
fix(workflow-code): review round 1 for workspace apply --run
- Gate a managed deployments/ on the runs even when no deployment file is left, so a failed run never undeploys a workflow. - Read the deployments write before the runs and refuse it when a workflow or deployment file changed while they ran, so only tested drafts deploy. - Drop the first write's W_DEPLOYED_DRAFT_CHANGED for deferred deployments before it prints. - Help names runs[].sideEffects.unchecked and .omitted.
1 parent 136cdb3 commit 453014e

3 files changed

Lines changed: 140 additions & 40 deletions

File tree

‎packages/sim-cli/src/commands/protocol/source-loop-help.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,8 @@ The loop, two shell calls:
6060
A non-zero exit stops the chain at the first failure; fix what it reported and run it again. check
6161
compiles and type-checks (TypeScript installs on first run; --no-types skips it); apply re-checks
6262
and writes the workspace; --run <key>='{…}' (one per workflow, <key> its workflows/<key>/ folder)
63-
dry-runs that input on the saved draft (writes stubbed, listed under runs[].sideEffects). A
63+
dry-runs that input on the saved draft: writes are stubbed and listed under runs[].sideEffects,
64+
whose .unchecked lists sandboxed code that ran unchecked and .omitted counts entries left out. A
6465
workflow deploys on apply when deployments/<key>.ts declares it; with --run, deployments/ is
6566
applied only after every run completed.
6667
--allow-delete lets an edit remove a resource, column, rows, document, or a workflow's block or

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

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2264,6 +2264,74 @@ describe('workspaces source apply', () => {
22642264
})
22652265
})
22662266

2267+
it('holds back a managed deployments/ with no files left (its undeploys) until the runs complete', async () => {
2268+
unlinkSync(join(dir, 'deployments/ingest.ts'))
2269+
write('deployments/.gitkeep', '')
2270+
serveApplies()
2271+
contextMockFns.mockRequestRaw.mockResolvedValue(
2272+
runAnswer({ status: 'failed', error: { message: 'score is not a number' } })
2273+
)
2274+
2275+
await expect(apply('--yes', '--allow-delete', '--run', 'ingest={}')).rejects.toThrow(
2276+
/deployments\/ was not applied/
2277+
)
2278+
expect(applies()).toHaveLength(1)
2279+
expect(applies()[0][1].body.kinds).not.toContain('deployment')
2280+
})
2281+
2282+
it('applies no deployments when a workflow file changed while the runs ran', async () => {
2283+
serveApplies()
2284+
contextMockFns.mockRequestRaw.mockImplementation(async () => {
2285+
write('workflows/ingest/workflow.ts', `${INGEST}// edited during the run\n`)
2286+
return runAnswer({ status: 'completed', output: {} })
2287+
})
2288+
2289+
await expect(apply('--yes', '--run', 'ingest={}')).rejects.toThrow(
2290+
/workflows\/ingest\/workflow\.ts changed in .* while they ran, so deployments\/ was not applied/
2291+
)
2292+
expect(applies()).toHaveLength(1)
2293+
})
2294+
2295+
it("never prints the first write's warning that a deferred deployment's workflow is not deployed", async () => {
2296+
request.mockImplementation(async (path: string, options: { body?: { kinds?: string[] } }) => {
2297+
if (path === '/api/v2/workflows/wf_1/deployment') return deploymentStatus(1)
2298+
const base = { ...BASE, resources: { 'workflow:ingest': { id: 'wf_1' } } }
2299+
if (options.body?.kinds?.includes('deployment')) {
2300+
return answer({
2301+
plan: [{ kind: 'deployment', key: 'ingest', action: 'update' }],
2302+
applied: [{ kind: 'deployment', key: 'ingest', action: 'update' }],
2303+
base,
2304+
})
2305+
}
2306+
return answer({
2307+
plan: [{ kind: 'workflow', key: 'ingest', action: 'update' }],
2308+
applied: [{ kind: 'workflow', key: 'ingest', action: 'update' }],
2309+
files: { 'workflows/ingest/workflow.ts': `${INGEST}// stored\n` },
2310+
base,
2311+
diagnostics: [
2312+
{
2313+
code: 'W_DEPLOYED_DRAFT_CHANGED',
2314+
severity: 'warning',
2315+
message: 'workflow ingest is deployed: the live version keeps running the old one.',
2316+
kind: 'workflow',
2317+
key: 'ingest',
2318+
},
2319+
],
2320+
})
2321+
})
2322+
contextMockFns.mockRequestRaw.mockResolvedValue(
2323+
runAnswer({ status: 'completed', output: {} })
2324+
)
2325+
2326+
await apply('--yes', '--run', 'ingest={}')
2327+
2328+
expect(applies()).toHaveLength(2)
2329+
const out = [...vi.mocked(console.error).mock.calls, ...vi.mocked(console.log).mock.calls]
2330+
.flat()
2331+
.join('\n')
2332+
expect(out).not.toContain('W_DEPLOYED_DRAFT_CHANGED')
2333+
})
2334+
22672335
it('refuses a key with no workflow folder, naming the keys there, before sending anything', async () => {
22682336
await expect(apply('--yes', '--run', 'ingset={}')).rejects.toThrow(
22692337
/--run ingset: no such folder under workflows\/ .* Its workflow keys: ingest\./

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

Lines changed: 70 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -857,13 +857,27 @@ export function attachWorkspaceSourceApply(source: Command): void {
857857
)
858858
: null
859859
const submission = promotion?.submission ?? read
860-
// With --run, deployments/ waits for the test runs: the first write leaves it out, and a
861-
// second applies it once every run completed (the drafts the runs tested, vouched for by
862-
// the workflow folders' bases the first write saved).
860+
// With --run, a managed deployments/ (its deploys, and the undeploys of files removed
861+
// from it) waits for the test runs: the first write leaves it out, and a second applies
862+
// it once every run completed (the drafts the runs tested, vouched for by the workflow
863+
// folders' bases the first write saved).
864+
const gated = runs.length > 0 && submission.kinds.includes('deployment')
863865
const deferred = new Set(
864-
runs.length > 0 ? (declaredKeys('deployment', submission.files) ?? []) : []
866+
gated ? (declaredKeys('deployment', submission.files) ?? []) : []
865867
)
866-
const firstWrite = deferred.size > 0 ? withoutDeployments(submission) : submission
868+
const firstWrite = gated ? withoutDeployments(submission) : submission
869+
/**
870+
* The first write declares no deployment file, so the server warns that each deferred
871+
* deployment's workflow changed with none to deploy it (`warnDeployedDraftChanges`): the
872+
* second write decides those.
873+
*/
874+
const withoutDeferredWarnings = (data: ApplyData): ApplyData => ({
875+
...data,
876+
diagnostics: data.diagnostics.filter(
877+
(finding) =>
878+
finding.code !== 'W_DEPLOYED_DRAFT_CHANGED' || !deferred.has(finding.key ?? '')
879+
),
880+
})
867881
/** `data` as this apply reports it: a promotion's own wording and warnings added. */
868882
const reported = (data: ApplyData): ApplyData =>
869883
promotion
@@ -934,9 +948,10 @@ export function attachWorkspaceSourceApply(source: Command): void {
934948
beforeCommit: (preview) =>
935949
stage(commit, preview ? new Set(preview.needBlobs) : blobsToStage(commit)),
936950
commit: async () => {
937-
const answer = reported(
951+
const sent = reported(
938952
await send(commit, false, commit === submission ? only : commit.kinds)
939953
)
954+
const answer = commit === firstWrite && gated ? withoutDeferredWarnings(sent) : sent
940955
findings.print(answer.diagnostics)
941956
return answer
942957
},
@@ -1006,67 +1021,63 @@ export function attachWorkspaceSourceApply(source: Command): void {
10061021

10071022
const data = await runSourceWrite<ApplyData>(writeFlow(firstWrite, written))
10081023
if (!data) return
1009-
// The first write declares no deployment file, so the server warns that each deferred
1010-
// deployment's workflow changed with none to deploy it (`warnDeployedDraftChanges`):
1011-
// the second write decides those.
1012-
const first =
1013-
deferred.size === 0
1014-
? data
1015-
: {
1016-
...data,
1017-
diagnostics: data.diagnostics.filter(
1018-
(finding) =>
1019-
finding.code !== 'W_DEPLOYED_DRAFT_CHANGED' ||
1020-
!deferred.has(finding.key ?? '')
1021-
),
1022-
}
1023-
const complete = settle(first)
1024-
if (runs.length === 0) return finish(first)
1024+
const complete = settle(data)
1025+
if (runs.length === 0) return finish(data)
10251026
if (!complete) {
10261027
printError(
1027-
`Not test-run${deferred.size > 0 ? ', and deployments/ not applied' : ''}: the apply did not write every change.`
1028+
`Not test-run${gated ? ', and deployments/ not applied' : ''}: the apply did not write every change.`
10281029
)
1029-
return finish(first)
1030+
return finish(data)
10301031
}
1031-
/** Runs a step after the write; a failure prints the write's result first: it stands. */
1032+
/** Runs a step after the write; a failure prints the write's result data: it stands. */
10321033
const afterWrite = async <T>(step: () => Promise<T>): Promise<T> => {
10331034
try {
10341035
return await step()
10351036
} catch (error) {
1036-
await finish(first)
1037+
await finish(data)
10371038
throw error
10381039
}
10391040
}
1040-
await afterWrite(() => testRuns(client, options.dir, workspaceId, first, runs, tested))
1041+
/** What the deployments write sends: the workflows the first write saved, and deployments/. */
1042+
const readDeploymentWrite = async () => {
1043+
const saved = await readWritten(options.dir)
1044+
const read = await readWorkspaceDir(
1045+
options.dir,
1046+
['workflow', 'deployment'],
1047+
workspaceId,
1048+
saved
1049+
)
1050+
return { saved, read }
1051+
}
1052+
// Read before the runs, so the deploys publish only what they tested.
1053+
const before = gated ? await afterWrite(readDeploymentWrite) : null
1054+
await afterWrite(() => testRuns(client, options.dir, workspaceId, data, runs, tested))
10411055
const failedRuns = tested.filter((run) => run.status !== 'completed')
10421056
if (failedRuns.length > 0) {
10431057
const next = {
10441058
command: `${applyCommand(options)} --yes`,
10451059
reason: 'applies your fix and tests it again',
10461060
}
1047-
await finish(first, next)
1061+
await finish(data, next)
10481062
const why = failedRuns
10491063
.map((run) => `the test run of ${run.workflow} ${String(run.status)}: ${run.error}`)
10501064
.join('; ')
10511065
throw new SimApiError(
1052-
`The apply was written into ${options.dir}, but ${why}.${deferred.size > 0 ? ' deployments/ was not applied.' : ''} Fix the source, then run \`${next.command}\`.`,
1066+
`The apply was written into ${options.dir}, but ${why}.${gated ? ' deployments/ was not applied.' : ''} Fix the source, then run \`${next.command}\`.`,
10531067
0
10541068
)
10551069
}
1056-
if (deferred.size === 0) return finish(first)
1070+
if (!before) return finish(data)
10571071
const deployed = await afterWrite(async () => {
1058-
const saved = await readWritten(options.dir)
1059-
const second = await readWorkspaceDir(
1060-
options.dir,
1061-
['workflow', 'deployment'],
1062-
workspaceId,
1063-
saved
1064-
)
1065-
return runSourceWrite<ApplyData>({ ...writeFlow(second, saved), mode: 'write' })
1072+
assertUnchangedSinceRuns(options.dir, before.read, (await readDeploymentWrite()).read)
1073+
return runSourceWrite<ApplyData>({
1074+
...writeFlow(before.read, before.saved),
1075+
mode: 'write',
1076+
})
10661077
})
10671078
if (!deployed) return
10681079
settle({ ...deployed, plan: deployed.plan.filter(isDeployment) })
1069-
await finish(mergedApply(first, deployed))
1080+
await finish(mergedApply(data, deployed))
10701081
},
10711082
{ readOnly: mode === 'dry' || mode === 'plan' }
10721083
)
@@ -1159,6 +1170,26 @@ async function readRunInputs(runs: readonly RunRequest[]): Promise<RunRequest[]>
11591170
)
11601171
}
11611172

1173+
/**
1174+
* Refuses the deployments write of a `--run` apply when its workflow or deployment files changed
1175+
* while the runs ran (`before` was read ahead of them, `after` once they completed): deploying
1176+
* then would publish a draft, or settings, no run tested.
1177+
*/
1178+
function assertUnchangedSinceRuns(
1179+
dir: string,
1180+
before: WorkspaceSubmission,
1181+
after: WorkspaceSubmission
1182+
): void {
1183+
const paths = new Set([...Object.keys(before.files), ...Object.keys(after.files)])
1184+
const changed = [...paths]
1185+
.filter((path) => before.files[path] !== after.files[path])
1186+
.sort(compareStrings)
1187+
if (changed.length === 0) return
1188+
throw new SourceDirError(
1189+
`The apply was written and every test run completed, but ${changed.join(', ')} changed in ${dir} while they ran, so ${KIND_DIRS.deployment}/ was not applied: apply again to test and deploy what is there now.`
1190+
)
1191+
}
1192+
11621193
const isDeployment = (change: Pick<Change, 'kind'>) => change.kind === 'deployment'
11631194

11641195
/** `submission` without its deployment files: an apply of every other kind it sends. */

0 commit comments

Comments
 (0)