Skip to content

Commit 3154b34

Browse files
authored
fix(cli): keep exactly named find blocks, the typed --run on retry, and measure only referenced bytes (#10605)
* fix(cli): keep exactly named find blocks, the typed --run on retry, and measure only referenced bytes - source find: blocks a name matches exactly go ahead of partial matches before the 20-block cap - workspaces source apply: the failed-run next command dedupes runs by the lock-resolved trigger and keeps the --run the user typed over a refusal's rewrite - workflows source apply: the size preflight sums the entry and the code files it references, as the server does; the file count still covers every sent file * fix(cli): keep the trigger-named retry reason when the typed --run wins the dedupe * fix(cli): hold the apply body to the route cap and share the run trigger identity A code file only the lock names is sent but no longer measured against maxTotalBytes, so the preflight now also refuses a JSON body over SOURCE_REQUEST_MAX_BYTES before upload. testRuns builds its trigger identity in one closure for both the duplicate check and the retry dedupe.
1 parent f60650e commit 3154b34

6 files changed

Lines changed: 202 additions & 25 deletions

File tree

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

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2156,6 +2156,77 @@ describe('the code files an apply sends', () => {
21562156
expect(sentCodeFiles()).toEqual(['functions/used.py'])
21572157
})
21582158

2159+
it('sends a large function file only the lock names, which the server never measures, without a size refusal', async () => {
2160+
writeFunctions('functions/used.js')
2161+
writeFileSync(join(dir, 'functions/dropped.js'), `//${'x'.repeat(4_000_000)}\n`)
2162+
writeFileSync(
2163+
join(dir, '.sim/lock.json'),
2164+
JSON.stringify({
2165+
...LOCK,
2166+
blocks: {
2167+
dropped: {
2168+
id: 'b-dropped',
2169+
parent: null,
2170+
ident: 'dropped',
2171+
order: 0,
2172+
codeFile: 'functions/dropped.js',
2173+
},
2174+
},
2175+
})
2176+
)
2177+
2178+
await applyEntry(
2179+
entryWith("const used = fn('Used', { code: codeFile('./functions/used.js') })\n")
2180+
)
2181+
2182+
expect(sentCodeFiles()).toEqual(['functions/dropped.js', 'functions/used.js'])
2183+
})
2184+
2185+
it('refuses a source whose files only the lock names push the request over the body limit', async () => {
2186+
writeFunctions('functions/used.js')
2187+
writeFileSync(join(dir, 'functions/dropped.js'), `//${'x'.repeat(10_000_000)}\n`)
2188+
writeFileSync(
2189+
join(dir, '.sim/lock.json'),
2190+
JSON.stringify({
2191+
...LOCK,
2192+
blocks: {
2193+
dropped: {
2194+
id: 'b-dropped',
2195+
parent: null,
2196+
ident: 'dropped',
2197+
order: 0,
2198+
codeFile: 'functions/dropped.js',
2199+
},
2200+
},
2201+
})
2202+
)
2203+
writeFileSync(
2204+
join(dir, 'workflow.ts'),
2205+
entryWith("const used = fn('Used', { code: codeFile('./functions/used.js') })\n")
2206+
)
2207+
setTerminal(false)
2208+
2209+
const error = await apply(WORKFLOW_ID, '--dir', dir, '--dry').catch((caught: unknown) => caught)
2210+
2211+
expect(error).toMatchObject({ code: 'E_LIMIT_EXCEEDED', exitCode: 7 })
2212+
expect(request).not.toHaveBeenCalled()
2213+
})
2214+
2215+
it('still refuses a source whose referenced function files are over the total size limit', async () => {
2216+
mkdirSync(join(dir, 'functions'), { recursive: true })
2217+
writeFileSync(join(dir, 'functions/big.js'), `//${'x'.repeat(4_000_000)}\n`)
2218+
writeFileSync(
2219+
join(dir, 'workflow.ts'),
2220+
entryWith("const big = fn('Big', { code: codeFile('./functions/big.js') })\n")
2221+
)
2222+
setTerminal(false)
2223+
2224+
const error = await apply(WORKFLOW_ID, '--dir', dir, '--dry').catch((caught: unknown) => caught)
2225+
2226+
expect(error).toMatchObject({ code: 'E_LIMIT_EXCEEDED', exitCode: 7 })
2227+
expect(request).not.toHaveBeenCalled()
2228+
})
2229+
21592230
/** Applies `entry` with --yes, the server answering with `files` as what it stored. */
21602231
async function applyStored(entry: string, files: Record<string, string>): Promise<void> {
21612232
writeFileSync(join(dir, 'workflow.ts'), entry)

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

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
import { toRecord } from '@sim/utils/object'
2-
import { SOURCE_ENTRY_FILE as ENTRY_FILE, sourceFileExcesses } from '@sim/workflow-code/limits'
2+
import { utf8ByteLength } from '@sim/utils/paste'
3+
import {
4+
SOURCE_ENTRY_FILE as ENTRY_FILE,
5+
SOURCE_REQUEST_MAX_BYTES,
6+
sourceFileExcesses,
7+
} from '@sim/workflow-code/limits'
38
import type { Command } from 'commander'
49
import { publishSummary } from '#sim-cli/output/github-actions'
510
import { printError } from '#sim-cli/output/io'
@@ -73,6 +78,7 @@ import {
7378
import { runSourceWrite } from './source-write'
7479
import { storedEdgesWrite } from './stored-edges'
7580
import {
81+
codeFilePaths,
7682
createCommand,
7783
readBase,
7884
readLock,
@@ -203,7 +209,7 @@ async function writeWorkflowSource<Operation extends SourceWriteOperation>(args:
203209
}): Promise<void> {
204210
const { options, creating } = args
205211
assertSendableCodeFiles(args.body.files)
206-
assertWithinFileLimits(args.body.files)
212+
assertWithinFileLimits(args.body)
207213
/** Sends the write (or its dry run); a refusal prints its diagnostics and rethrows. */
208214
const send = async (dry: boolean): Promise<SourceApplyData> => {
209215
try {
@@ -370,14 +376,33 @@ async function writeWorkflowSource<Operation extends SourceWriteOperation>(args:
370376

371377
/**
372378
* Refuses a source over the file-count or total-size limit before it is sent: the server would
373-
* refuse it as `E_LIMIT_EXCEEDED` only after the whole upload.
379+
* refuse it as `E_LIMIT_EXCEEDED` only after the whole upload. The file count is of every file
380+
* sent; the size, as the server measures it, is of the entry and the code files it references, so
381+
* a code file only the lock still names never refuses a source the server would accept. Those
382+
* files are still sent, so the whole JSON body is held to the route's `SOURCE_REQUEST_MAX_BYTES`.
374383
*/
375-
function assertWithinFileLimits(files: Record<string, string>): void {
376-
const excesses = sourceFileExcesses(files).map(({ limit, actual, max }) =>
384+
function assertWithinFileLimits(body: { files: Record<string, string> }): void {
385+
const { files } = body
386+
const entry = files[ENTRY_FILE] ?? null
387+
const measured = Object.fromEntries(
388+
[ENTRY_FILE, ...codeFilePaths(entry, null)].flatMap((path) =>
389+
files[path] === undefined ? [] : [[path, files[path]]]
390+
)
391+
)
392+
const excesses = [
393+
...sourceFileExcesses(files).filter(({ limit }) => limit === 'maxFiles'),
394+
...sourceFileExcesses(measured).filter(({ limit }) => limit === 'maxTotalBytes'),
395+
].map(({ limit, actual, max }) =>
377396
limit === 'maxFiles'
378397
? `it has ${actual} files, over the ${max}-file limit`
379398
: `its files total ${actual} bytes, over the ${max}-byte limit`
380399
)
400+
const requestBytes = utf8ByteLength(JSON.stringify(body))
401+
if (requestBytes > SOURCE_REQUEST_MAX_BYTES) {
402+
excesses.push(
403+
`the request would carry ${requestBytes} bytes, over the ${SOURCE_REQUEST_MAX_BYTES}-byte limit`
404+
)
405+
}
381406
if (excesses.length === 0) return
382407
throw new SourceDirError(
383408
`This source is too large to send: ${excesses.join('; ')}, so nothing was sent. Share one code file between blocks, or shorten the code.`,

‎packages/sim-cli/src/commands/protocol/workflow-source-find.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,24 @@ describe('sim workflows source find', () => {
150150
expect(stdoutJson().blocks.map((block) => block.name)).toEqual(['Score', 'Audit'])
151151
})
152152

153+
it('prints a block named exactly even when a part of another name matches more blocks than it prints', async () => {
154+
const scores = Array.from(
155+
{ length: 21 },
156+
(_, index) => ` const score${index} = fn('Score ${index}', { code: js\`return ${index}\` })`
157+
)
158+
writeFileSync(
159+
join(dir, 'workflow.ts'),
160+
WORKFLOW_TS.replace(' const gate =', `${scores.join('\n')}\n const gate =`)
161+
)
162+
163+
await find('core', 'Fallback')
164+
165+
const result = stdoutJson() as { blocks: Array<Record<string, unknown>>; more?: number }
166+
expect(result.blocks).toHaveLength(20)
167+
expect(result.blocks.map((block) => block.name)).toContain('Fallback')
168+
expect(result.more).toBe(3)
169+
})
170+
153171
it("prints a block's declaration and a short function file's text, so it reads without a sed or cat", async () => {
154172
await find('Score')
155173
expect(stdoutJson().blocks[0]).toMatchObject({

‎packages/sim-cli/src/commands/protocol/workflow-source-find.ts‎

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -194,18 +194,25 @@ function readersByKey(index: SourceIndex): Map<BlockKey, Reader[]> {
194194
return readers
195195
}
196196

197+
interface BlockMatch {
198+
query: string
199+
keys: BlockKey[]
200+
exact: boolean
201+
}
202+
197203
/**
198204
* The blocks `query` names: an exact key, identifier or name first, else every block whose name
199205
* contains the query.
200206
*/
201-
function matchBlocks(index: SourceIndex, query: string): BlockKey[] {
207+
function matchBlocks(index: SourceIndex, query: string): BlockMatch {
202208
const normalized = normalizeWorkflowBlockName(query)
203209
const exact = index.keys().filter((key) => key === normalized || index.identOf(key) === query)
204-
if (exact.length > 0) return exact
210+
if (exact.length > 0) return { query, keys: exact, exact: true }
205211
const needle = query.toLowerCase()
206-
return index
212+
const keys = index
207213
.keys()
208214
.filter((key) => key.includes(normalized) || index.nameOf(key).toLowerCase().includes(needle))
215+
return { query, keys, exact: false }
209216
}
210217

211218
/**
@@ -345,8 +352,13 @@ export function attachWorkflowSourceFind(source: Command): void {
345352
throw new CliUsageError('Name a block.', { code: 'BLOCK_UNKNOWN' })
346353
}
347354
const index = new SourceIndex(compiled, files)
348-
const matched = queries.map((query) => ({ query, keys: matchBlocks(index, query) }))
349-
const keys = [...new Set(matched.flatMap((match) => match.keys))]
355+
const matched = queries.map((query) => matchBlocks(index, query))
356+
// Exactly named blocks go first, so a broad part of a name cannot push them past the cap.
357+
const ranked = [
358+
...matched.filter((match) => match.exact),
359+
...matched.filter((match) => !match.exact),
360+
]
361+
const keys = [...new Set(ranked.flatMap((match) => match.keys))]
350362
const unknown = matched.find((match) => match.keys.length === 0)
351363
if (keys.length === 0 && unknown) throw unknownBlock(index, unknown.query)
352364
const readers = readersByKey(index)

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

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2715,6 +2715,51 @@ describe('workspaces source apply', () => {
27152715
)
27162716
})
27172717

2718+
it("keeps the input a --run typed for a trigger over a bare run's retry through it", async () => {
2719+
serveApplies()
2720+
contextMockFns.mockRequestRaw
2721+
.mockRejectedValueOnce(
2722+
new SimApiError(
2723+
'This workflow has multiple runnable triggers. Pass run.entry.blockId to choose one: b-api (Api In), b-hook (Hook In).',
2724+
400,
2725+
'BAD_REQUEST'
2726+
)
2727+
)
2728+
.mockResolvedValueOnce(runAnswer({ status: 'completed', output: {} }))
2729+
2730+
await expect(
2731+
apply('--yes', '--run', 'ingest={"a":1}', '--run', 'ingest.apiIn={"b":2}')
2732+
).rejects.toThrow(/more than one trigger/)
2733+
2734+
const printed = JSON.parse(String(vi.mocked(console.log).mock.calls.at(-1)?.[0]))
2735+
expect(printed.next).toEqual({
2736+
command: `sim workspaces source apply --dir ${dir} --run 'ingest.apiIn={"b":2}' --yes`,
2737+
reason: 'applies again and tests each workflow through the trigger its --run names',
2738+
})
2739+
})
2740+
2741+
it('retries a bare run once beside a --run naming its trigger by block key, so the next command is not refused', async () => {
2742+
serveApplies()
2743+
contextMockFns.mockRequestRaw
2744+
.mockRejectedValueOnce(
2745+
new SimApiError(
2746+
'This workflow has multiple runnable triggers. Pass run.entry.blockId to choose one: b-api (Api In), b-hook (Hook In).',
2747+
400,
2748+
'BAD_REQUEST'
2749+
)
2750+
)
2751+
.mockResolvedValueOnce(runAnswer({ status: 'completed', output: {} }))
2752+
2753+
await expect(
2754+
apply('--yes', '--run', 'ingest={"a":1}', '--run', 'ingest.apiin={"b":2}')
2755+
).rejects.toThrow(/more than one trigger/)
2756+
2757+
const printed = JSON.parse(String(vi.mocked(console.log).mock.calls.at(-1)?.[0]))
2758+
expect(printed.next.command).toBe(
2759+
`sim workspaces source apply --dir ${dir} --run 'ingest.apiin={"b":2}' --yes`
2760+
)
2761+
})
2762+
27182763
it('refuses the same workflow and trigger twice before sending anything', async () => {
27192764
await expect(
27202765
apply('--yes', '--run', 'ingest.hook={}', '--run', 'ingest.hook={"y":2}')

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

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1079,7 +1079,7 @@ export function attachWorkspaceSourceApply(source: Command): void {
10791079
}
10801080
// Read before the runs, so the deploys publish only what they tested.
10811081
const before = gated ? await afterWrite(readDeploymentWrite) : null
1082-
const nextRuns = await afterWrite(() =>
1082+
const retry = await afterWrite(() =>
10831083
testRuns(client, options.dir, workspaceId, data, runs, tested)
10841084
)
10851085
const failedRuns = tested.filter((run) => run.status !== 'completed')
@@ -1089,17 +1089,11 @@ export function attachWorkspaceSourceApply(source: Command): void {
10891089
// only rate limited needs waiting instead.
10901090
const rateLimited = failedRuns.every((run) => run.rateLimited)
10911091
const refused = failedRuns.some((run) => run.runId === null && !run.rateLimited)
1092-
const named = nextRuns.some((value, index) => value !== options.run?.[index])
1093-
// A refused run's trigger can be one another --run already names: it runs once.
1094-
const nextNames = nextRuns.map((value) => runName(parseRunValue(value)))
1095-
const retried = nextRuns.filter(
1096-
(_, index) => nextNames.indexOf(nextNames[index]) === index
1097-
)
10981092
const next = {
1099-
command: `${applyCommand({ ...options, run: retried }, sim)} --yes`,
1093+
command: `${applyCommand({ ...options, run: retry.runs }, sim)} --yes`,
11001094
reason: rateLimited
11011095
? 'runs the tests again once the rate limit allows'
1102-
: named
1096+
: retry.rewritten
11031097
? 'applies again and tests each workflow through the trigger its --run names'
11041098
: refused
11051099
? 'applies again and tests it with your fixed --run input'
@@ -1392,7 +1386,9 @@ function testRunsText(tested: readonly WorkflowTestRun[]): string {
13921386
* result to `tested`; a run that does not complete has its failing block mapped to file:line in its
13931387
* `workflows/<key>/` folder, and its `error` says why. A key the written base binds to no workflow
13941388
* is refused before any run. Returns each `--run` value a next command repeats, in order: a refused
1395-
* run's names the trigger its refusal listed.
1389+
* run's names the trigger its refusal listed, and is dropped when another `--run` already names
1390+
* that trigger (by its const, block key or id), so the next command keeps the input typed for it;
1391+
* and whether a refusal rewrote any run.
13961392
*/
13971393
async function testRuns(
13981394
client: OperationClient<'executeWorkflow'>,
@@ -1401,7 +1397,7 @@ async function testRuns(
14011397
data: ApplyData,
14021398
runs: readonly WorkspaceRun[],
14031399
tested: WorkflowTestRun[]
1404-
): Promise<string[]> {
1400+
): Promise<{ runs: string[]; rewritten: boolean }> {
14051401
const base = parseWorkspaceBase(data.base).base
14061402
const targets = runs.map((run) => ({
14071403
...run,
@@ -1420,10 +1416,12 @@ async function testRuns(
14201416
}
14211417
}
14221418
// parseRuns compares names as written; the saved lock tells a const from its block key or id.
1419+
const triggerEntry = (key: string, trigger: string | undefined) =>
1420+
`${key}\0${trigger === undefined ? '' : lockTriggerId(locks.get(key), trigger)}`
14231421
const entered = new Map<string, WorkspaceRun>()
14241422
for (const target of targets) {
14251423
if (target.request.trigger === undefined) continue
1426-
const entry = `${target.key}\0${lockTriggerId(locks.get(target.key), target.request.trigger)}`
1424+
const entry = triggerEntry(target.key, target.request.trigger)
14271425
const earlier = entered.get(entry)
14281426
if (earlier) {
14291427
throw new SourceDirError(
@@ -1432,7 +1430,8 @@ async function testRuns(
14321430
}
14331431
entered.set(entry, target)
14341432
}
1435-
const next: string[] = []
1433+
const next = new Map<string, { value: string; rewritten: boolean }>()
1434+
let anyRewritten = false
14361435
for (const { key, request, workflowId } of targets) {
14371436
if (!workflowId) continue
14381437
const [outcome] = await runTests(client, {
@@ -1449,9 +1448,16 @@ async function testRuns(
14491448
...outcome.run,
14501449
...(outcome.failure !== undefined ? { error: outcome.failure } : {}),
14511450
})
1452-
next.push(outcome.next)
1451+
const rewritten = outcome.next !== workspaceRunFlag(key, request)
1452+
anyRewritten ||= rewritten
1453+
const entry = triggerEntry(key, parseRunValue(outcome.next).request.trigger)
1454+
const kept = next.get(entry)
1455+
if (!kept || (kept.rewritten && !rewritten)) next.set(entry, { value: outcome.next, rewritten })
1456+
}
1457+
return {
1458+
runs: [...next.values()].map((run) => run.value),
1459+
rewritten: anyRewritten,
14531460
}
1454-
return next
14551461
}
14561462

14571463
/**

0 commit comments

Comments
 (0)