Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -2156,6 +2156,47 @@ describe('the code files an apply sends', () => {
expect(sentCodeFiles()).toEqual(['functions/used.py'])
})

it('sends a large function file only the lock names, which the server never measures, without a size refusal', async () => {
writeFunctions('functions/used.js')
writeFileSync(join(dir, 'functions/dropped.js'), `//${'x'.repeat(4_000_000)}\n`)
writeFileSync(
join(dir, '.sim/lock.json'),
JSON.stringify({
...LOCK,
blocks: {
dropped: {
id: 'b-dropped',
parent: null,
ident: 'dropped',
order: 0,
codeFile: 'functions/dropped.js',
},
},
})
)

await applyEntry(
entryWith("const used = fn('Used', { code: codeFile('./functions/used.js') })\n")
)

expect(sentCodeFiles()).toEqual(['functions/dropped.js', 'functions/used.js'])
})

it('still refuses a source whose referenced function files are over the total size limit', async () => {
mkdirSync(join(dir, 'functions'), { recursive: true })
writeFileSync(join(dir, 'functions/big.js'), `//${'x'.repeat(4_000_000)}\n`)
writeFileSync(
join(dir, 'workflow.ts'),
entryWith("const big = fn('Big', { code: codeFile('./functions/big.js') })\n")
)
setTerminal(false)

const error = await apply(WORKFLOW_ID, '--dir', dir, '--dry').catch((caught: unknown) => caught)

expect(error).toMatchObject({ code: 'E_LIMIT_EXCEEDED', exitCode: 7 })
expect(request).not.toHaveBeenCalled()
})

/** Applies `entry` with --yes, the server answering with `files` as what it stored. */
async function applyStored(entry: string, files: Record<string, string>): Promise<void> {
writeFileSync(join(dir, 'workflow.ts'), entry)
Expand Down
16 changes: 14 additions & 2 deletions packages/sim-cli/src/commands/protocol/workflow-source-apply.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ import {
import { runSourceWrite } from './source-write'
import { storedEdgesWrite } from './stored-edges'
import {
codeFilePaths,
createCommand,
readBase,
readLock,
Expand Down Expand Up @@ -370,10 +371,21 @@ async function writeWorkflowSource<Operation extends SourceWriteOperation>(args:

/**
* Refuses a source over the file-count or total-size limit before it is sent: the server would
* refuse it as `E_LIMIT_EXCEEDED` only after the whole upload.
* refuse it as `E_LIMIT_EXCEEDED` only after the whole upload. The file count is of every file
* sent; the size, as the server measures it, is of the entry and the code files it references, so
* a code file only the lock still names never refuses a source the server would accept.
*/
function assertWithinFileLimits(files: Record<string, string>): void {
const excesses = sourceFileExcesses(files).map(({ limit, actual, max }) =>
const entry = files[ENTRY_FILE] ?? null
const measured = Object.fromEntries(
[ENTRY_FILE, ...codeFilePaths(entry, null)].flatMap((path) =>
files[path] === undefined ? [] : [[path, files[path]]]
)
)
const excesses = [
...sourceFileExcesses(files).filter(({ limit }) => limit === 'maxFiles'),
...sourceFileExcesses(measured).filter(({ limit }) => limit === 'maxTotalBytes'),
].map(({ limit, actual, max }) =>
limit === 'maxFiles'
? `it has ${actual} files, over the ${max}-file limit`
: `its files total ${actual} bytes, over the ${max}-byte limit`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,24 @@ describe('sim workflows source find', () => {
expect(stdoutJson().blocks.map((block) => block.name)).toEqual(['Score', 'Audit'])
})

it('prints a block named exactly even when a part of another name matches more blocks than it prints', async () => {
const scores = Array.from(
{ length: 21 },
(_, index) => ` const score${index} = fn('Score ${index}', { code: js\`return ${index}\` })`
)
writeFileSync(
join(dir, 'workflow.ts'),
WORKFLOW_TS.replace(' const gate =', `${scores.join('\n')}\n const gate =`)
)

await find('core', 'Fallback')

const result = stdoutJson() as { blocks: Array<Record<string, unknown>>; more?: number }
expect(result.blocks).toHaveLength(20)
expect(result.blocks.map((block) => block.name)).toContain('Fallback')
expect(result.more).toBe(3)
})

it("prints a block's declaration and a short function file's text, so it reads without a sed or cat", async () => {
await find('Score')
expect(stdoutJson().blocks[0]).toMatchObject({
Expand Down
22 changes: 17 additions & 5 deletions packages/sim-cli/src/commands/protocol/workflow-source-find.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,18 +194,25 @@ function readersByKey(index: SourceIndex): Map<BlockKey, Reader[]> {
return readers
}

interface BlockMatch {
query: string
keys: BlockKey[]
exact: boolean
}

/**
* The blocks `query` names: an exact key, identifier or name first, else every block whose name
* contains the query.
*/
function matchBlocks(index: SourceIndex, query: string): BlockKey[] {
function matchBlocks(index: SourceIndex, query: string): BlockMatch {
const normalized = normalizeWorkflowBlockName(query)
const exact = index.keys().filter((key) => key === normalized || index.identOf(key) === query)
if (exact.length > 0) return exact
if (exact.length > 0) return { query, keys: exact, exact: true }
const needle = query.toLowerCase()
return index
const keys = index
.keys()
.filter((key) => key.includes(normalized) || index.nameOf(key).toLowerCase().includes(needle))
return { query, keys, exact: false }
}

/**
Expand Down Expand Up @@ -345,8 +352,13 @@ export function attachWorkflowSourceFind(source: Command): void {
throw new CliUsageError('Name a block.', { code: 'BLOCK_UNKNOWN' })
}
const index = new SourceIndex(compiled, files)
const matched = queries.map((query) => ({ query, keys: matchBlocks(index, query) }))
const keys = [...new Set(matched.flatMap((match) => match.keys))]
const matched = queries.map((query) => matchBlocks(index, query))
// Exactly named blocks go first, so a broad part of a name cannot push them past the cap.
const ranked = [
...matched.filter((match) => match.exact),
...matched.filter((match) => !match.exact),
]
const keys = [...new Set(ranked.flatMap((match) => match.keys))]
const unknown = matched.find((match) => match.keys.length === 0)
if (keys.length === 0 && unknown) throw unknownBlock(index, unknown.query)
const readers = readersByKey(index)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2715,6 +2715,51 @@ describe('workspaces source apply', () => {
)
})

it("keeps the input a --run typed for a trigger over a bare run's retry through it", async () => {
serveApplies()
contextMockFns.mockRequestRaw
.mockRejectedValueOnce(
new SimApiError(
'This workflow has multiple runnable triggers. Pass run.entry.blockId to choose one: b-api (Api In), b-hook (Hook In).',
400,
'BAD_REQUEST'
)
)
.mockResolvedValueOnce(runAnswer({ status: 'completed', output: {} }))

await expect(
apply('--yes', '--run', 'ingest={"a":1}', '--run', 'ingest.apiIn={"b":2}')
).rejects.toThrow(/more than one trigger/)

const printed = JSON.parse(String(vi.mocked(console.log).mock.calls.at(-1)?.[0]))
expect(printed.next).toEqual({
command: `sim workspaces source apply --dir ${dir} --run 'ingest.apiIn={"b":2}' --yes`,
reason: 'applies again and tests each workflow through the trigger its --run names',
})
})

it('retries a bare run once beside a --run naming its trigger by block key, so the next command is not refused', async () => {
serveApplies()
contextMockFns.mockRequestRaw
.mockRejectedValueOnce(
new SimApiError(
'This workflow has multiple runnable triggers. Pass run.entry.blockId to choose one: b-api (Api In), b-hook (Hook In).',
400,
'BAD_REQUEST'
)
)
.mockResolvedValueOnce(runAnswer({ status: 'completed', output: {} }))

await expect(
apply('--yes', '--run', 'ingest={"a":1}', '--run', 'ingest.apiin={"b":2}')
).rejects.toThrow(/more than one trigger/)

const printed = JSON.parse(String(vi.mocked(console.log).mock.calls.at(-1)?.[0]))
expect(printed.next.command).toBe(
`sim workspaces source apply --dir ${dir} --run 'ingest.apiin={"b":2}' --yes`
)
})

it('refuses the same workflow and trigger twice before sending anything', async () => {
await expect(
apply('--yes', '--run', 'ingest.hook={}', '--run', 'ingest.hook={"y":2}')
Expand Down
33 changes: 19 additions & 14 deletions packages/sim-cli/src/commands/protocol/workspace-source-apply.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1079,7 +1079,7 @@ export function attachWorkspaceSourceApply(source: Command): void {
}
// Read before the runs, so the deploys publish only what they tested.
const before = gated ? await afterWrite(readDeploymentWrite) : null
const nextRuns = await afterWrite(() =>
const retry = await afterWrite(() =>
testRuns(client, options.dir, workspaceId, data, runs, tested)
)
const failedRuns = tested.filter((run) => run.status !== 'completed')
Expand All @@ -1089,17 +1089,11 @@ export function attachWorkspaceSourceApply(source: Command): void {
// only rate limited needs waiting instead.
const rateLimited = failedRuns.every((run) => run.rateLimited)
const refused = failedRuns.some((run) => run.runId === null && !run.rateLimited)
const named = nextRuns.some((value, index) => value !== options.run?.[index])
// A refused run's trigger can be one another --run already names: it runs once.
const nextNames = nextRuns.map((value) => runName(parseRunValue(value)))
const retried = nextRuns.filter(
(_, index) => nextNames.indexOf(nextNames[index]) === index
)
const next = {
command: `${applyCommand({ ...options, run: retried }, sim)} --yes`,
command: `${applyCommand({ ...options, run: retry.runs }, sim)} --yes`,
reason: rateLimited
? 'runs the tests again once the rate limit allows'
: named
: retry.rewritten
? 'applies again and tests each workflow through the trigger its --run names'
: refused
? 'applies again and tests it with your fixed --run input'
Expand Down Expand Up @@ -1392,7 +1386,9 @@ function testRunsText(tested: readonly WorkflowTestRun[]): string {
* result to `tested`; a run that does not complete has its failing block mapped to file:line in its
* `workflows/<key>/` folder, and its `error` says why. A key the written base binds to no workflow
* is refused before any run. Returns each `--run` value a next command repeats, in order: a refused
* run's names the trigger its refusal listed.
* run's names the trigger its refusal listed, and is dropped when another `--run` already names
* that trigger (by its const, block key or id), so the next command keeps the input typed for it;
* and whether a refusal rewrote any run.
*/
async function testRuns(
client: OperationClient<'executeWorkflow'>,
Expand All @@ -1401,7 +1397,7 @@ async function testRuns(
data: ApplyData,
runs: readonly WorkspaceRun[],
tested: WorkflowTestRun[]
): Promise<string[]> {
): Promise<{ runs: string[]; rewritten: boolean }> {
const base = parseWorkspaceBase(data.base).base
const targets = runs.map((run) => ({
...run,
Expand Down Expand Up @@ -1432,7 +1428,8 @@ async function testRuns(
}
entered.set(entry, target)
}
const next: string[] = []
const next = new Map<string, { value: string; rewritten: boolean }>()
let anyRewritten = false
for (const { key, request, workflowId } of targets) {
if (!workflowId) continue
const [outcome] = await runTests(client, {
Expand All @@ -1449,9 +1446,17 @@ async function testRuns(
...outcome.run,
...(outcome.failure !== undefined ? { error: outcome.failure } : {}),
})
next.push(outcome.next)
const rewritten = outcome.next !== workspaceRunFlag(key, request)
anyRewritten ||= rewritten
const { trigger } = parseRunValue(outcome.next).request
const entry = `${key}\0${trigger === undefined ? '' : lockTriggerId(locks.get(key), trigger)}`
const kept = next.get(entry)
if (!kept || (kept.rewritten && !rewritten)) next.set(entry, { value: outcome.next, rewritten })
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
}
return {
runs: [...next.values()].map((run) => run.value),
rewritten: anyRewritten,
}
return next
}

/**
Expand Down
Loading