Skip to content

Commit 00d21c3

Browse files
authored
improvement(mothership): keep workflow test-run results inside the agent window (#10147)
* improvement(mothership): keep workflow test-run results inside the agent window * fix(mothership): measure the run result window after secret projection and fit the preview
1 parent fe15c69 commit 00d21c3

5 files changed

Lines changed: 261 additions & 65 deletions

File tree

‎apps/sim/app/api/v2/workflows/[workflowId]/execute/route.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -482,6 +482,10 @@ describe('POST /api/v2/workflows/[workflowId]/execute', () => {
482482
blockName: 'Send Email',
483483
blockType: 'gmail',
484484
})
485+
// An agent reads the head of an oversized run, so the error precedes the unbounded output.
486+
const keys = Object.keys(body.data)
487+
expect(keys.indexOf('error')).toBeLessThan(keys.indexOf('output'))
488+
expect(keys.indexOf('durationMs')).toBeLessThan(keys.indexOf('output'))
485489
})
486490

487491
it('queues async runs and returns a 202 receipt with the v2 runs statusUrl', async () => {

‎apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -123,18 +123,23 @@ function encodeNdjson(value: unknown): Uint8Array {
123123
return ndjsonEncoder.encode(`${JSON.stringify(value)}\n`)
124124
}
125125

126+
/**
127+
* The run resource, its bounded fields ahead of `output` and `blockOutputs`: a reader that keeps
128+
* only the head of an oversized response (an agent's output window) still sees the status, the
129+
* failing block and its error, and the duration.
130+
*/
126131
function presentRun(result: ExecuteWorkflowServiceRun) {
127132
return {
128133
runId: result.executionId,
129134
workflowId: result.workflowId,
130135
status: result.status,
131-
output: result.output ?? null,
132-
blockOutputs: result.blockOutputs ?? null,
133136
error: result.error,
134137
startedAt: result.startedAt,
135138
endedAt: result.endedAt,
136139
durationMs: result.durationMs,
137140
executionTimeoutSeconds: executionTimeoutSeconds(result.executionTimeoutMs),
141+
output: result.output ?? null,
142+
blockOutputs: result.blockOutputs ?? null,
138143
}
139144
}
140145

‎apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/resume/route.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -111,13 +111,13 @@ export const POST = withRouteHandler(
111111
runId: result.executionId,
112112
workflowId,
113113
status: result.status as 'completed' | 'failed' | 'paused' | 'cancelled',
114-
output: result.output ?? null,
115-
// Resume has no request body to name selectors in, so selection never applies here.
116-
blockOutputs: null,
117114
error: result.structuredError,
118115
startedAt: result.metadata?.startTime,
119116
endedAt: result.metadata?.endTime,
120117
durationMs: result.metadata?.duration,
118+
output: result.output ?? null,
119+
// Resume has no request body to name selectors in, so selection never applies here.
120+
blockOutputs: null,
121121
},
122122
{ headers }
123123
)

‎apps/sim/lib/mothership/tools/handlers/workflow/run-workflow-result-budget.test.ts‎

Lines changed: 105 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -148,21 +148,91 @@ describe('run_workflow model-facing result budget', () => {
148148
expect(presented.find((log) => log.blockName === 'Query 1')?.output).toEqual(logs[1].output)
149149
})
150150

151-
/** The final output is what the run was for, so it is never compacted and needs the headroom. */
152-
it('leaves room for a large final output beside the bounded logs', async () => {
153-
const finalOutput = { rows: tableRows(4_800, 3_200_000) }
151+
/**
152+
* The agent stores a result past its window behind a paged read, which costs it a round to learn
153+
* whether the run passed. Block outputs give way first, so the verdict, the failing block, and a
154+
* final output that fits all arrive inline.
155+
*/
156+
it('fits a failed run with bulky block outputs inside the agent window', async () => {
157+
const logs = [
158+
...traceShapedLogs().slice(0, 3),
159+
{ blockId: 'send', blockName: 'Send', success: false, error: 'SMTP refused', output: {} },
160+
]
161+
const finalOutput = { summary: 'partial report', rowCount: 1_882 }
154162
mocks.executeWorkflowUseCase.mockResolvedValue({
155-
success: true,
163+
success: false,
156164
output: finalOutput,
157-
logs: traceShapedLogs(),
165+
logs,
158166
metadata: { executionId: EXECUTION_ID },
159167
})
160168

161169
const settled = await executeRunWorkflow({ workflowId: 'wf-1' }, context)
162170
const projection = inspectToolResultForCopilot(settled, registry, 'run_workflow')
163171

164172
expect(projection.safe).toBe(true)
165-
expect((projection.result.output as Record<string, unknown>).output).toEqual(finalOutput)
173+
expect(JSON.stringify(projection.result).length).toBeLessThanOrEqual(24_000)
174+
expect(projection.result.error).toBe('Send: SMTP refused')
175+
const output = projection.result.output as Record<string, unknown>
176+
expect(output.output).toEqual(finalOutput)
177+
const presented = output.logs as Array<Record<string, unknown>>
178+
expect(presented.map((log) => log.blockName)).toEqual(logs.map((log) => log.blockName))
179+
expect(presented[3]).toMatchObject({ success: false, error: 'SMTP refused' })
180+
})
181+
182+
/** A short secret under a long name grows when projected, so the window is measured after it. */
183+
it('fits the window as projected when short secrets expand into longer names', async () => {
184+
const password = 'pw-12345'
185+
const shortSecret = new ResolvedSecretTraceRegistry([
186+
{ name: 'DATABASE_PASSWORD', plaintext: password, encryptedValue: 'ciphertext' },
187+
])
188+
shortSecret.recordResolved('DATABASE_PASSWORD', password, { propagated: true })
189+
mocks.executeWorkflowUseCase.mockResolvedValue({
190+
success: true,
191+
output: { done: true },
192+
logs: [
193+
{
194+
blockId: 'echo',
195+
blockName: 'Echo',
196+
success: true,
197+
// About 14K characters raw, over 31K once each copy becomes {{DATABASE_PASSWORD}}.
198+
output: { tokens: Array.from({ length: 1_300 }, () => password) },
199+
},
200+
],
201+
metadata: { executionId: EXECUTION_ID },
202+
})
203+
204+
const settled = await executeRunWorkflow({ workflowId: 'wf-1' }, callContext(shortSecret))
205+
const projection = inspectToolResultForCopilot(settled, shortSecret, 'run_workflow')
206+
207+
expect(projection.safe).toBe(true)
208+
expect(JSON.stringify(projection.result.output).length).toBeLessThanOrEqual(16_000)
209+
const output = projection.result.output as { output: unknown; logs: Array<{ output: unknown }> }
210+
expect(output.output).toEqual({ done: true })
211+
expect(output.logs[0]?.output).toEqual(expect.stringContaining(`logs get ${EXECUTION_ID}`))
212+
})
213+
214+
/** Many small block entries leave less room than a full preview, so the preview shrinks to fit. */
215+
it('shrinks the final output preview to the room the block entries leave', async () => {
216+
const logs = Array.from({ length: 150 }, (_, index) => ({
217+
blockId: `step-${index}`,
218+
blockName: `Step ${index} of the nightly import`,
219+
success: true,
220+
output: { ok: true },
221+
}))
222+
mocks.executeWorkflowUseCase.mockResolvedValue({
223+
success: true,
224+
output: { report: 'z'.repeat(50_000) },
225+
logs,
226+
metadata: { executionId: EXECUTION_ID },
227+
})
228+
const inactive = secretRegistry({ active: false })
229+
230+
const settled = await executeRunWorkflow({ workflowId: 'wf-1' }, callContext(inactive))
231+
const output = settled.output as { output: unknown; logs: unknown[] }
232+
233+
expect(JSON.stringify({ output }).length).toBeLessThanOrEqual(16_000)
234+
expect(output.logs).toEqual(logs)
235+
expect(output.output).toEqual(expect.stringMatching(/^\{"report":"z+ …\[final output cut at/))
166236
})
167237

168238
/** Narrow rows reach the traversal cap while staying far under every byte budget. */
@@ -186,7 +256,9 @@ describe('run_workflow model-facing result budget', () => {
186256
const projection = inspectToolResultForCopilot(settled, registry, 'run_workflow')
187257

188258
expect(projection.safe).toBe(true)
189-
expect((projection.result.output as Record<string, unknown>).output).toEqual(finalOutput)
259+
expect((projection.result.output as Record<string, unknown>).output).toEqual(
260+
expect.stringContaining(`logs get ${EXECUTION_ID} --trace`)
261+
)
190262
})
191263

192264
it('returns selected values in full, bypassing the log budget', async () => {
@@ -343,11 +415,10 @@ describe('run_workflow model-facing result budget', () => {
343415
})
344416

345417
/**
346-
* Without an active secret the projection passes JSON through under its byte cap alone, so
347-
* nothing is bounded: a lifted output is the whole point of run_block and reaches the worker in
348-
* full, which spills an oversized one to storage for the model to read.
418+
* Without an active secret a cut cannot strand a secret fragment, so an oversized lifted output
419+
* keeps its head inline as a preview and names where the rest is.
349420
*/
350-
it('returns a large lifted output and its logs in full when no secret is active', async () => {
421+
it('previews an oversized lifted output when no secret is active', async () => {
351422
const rows = wideRows()
352423
mocks.executeWorkflowUseCase.mockResolvedValue({
353424
success: true,
@@ -368,52 +439,35 @@ describe('run_workflow model-facing result budget', () => {
368439

369440
expect(projection.safe).toBe(true)
370441
const output = projection.result.output as Record<string, unknown>
371-
expect(output.output).toEqual({ rows })
372-
expect((output.logs as Array<Record<string, unknown>>)[1]?.output).toEqual({ rows })
442+
expect(JSON.stringify(output).length).toBeLessThanOrEqual(16_000)
443+
expect(output.output).toEqual(expect.stringMatching(/^\{"rows":\[\{"c0":"r0"/))
444+
expect(output.output).toEqual(expect.stringContaining(`logs get ${EXECUTION_ID} --trace`))
445+
expect(output.outputFrom).toEqual({ blockId: 'query', blockName: 'Query' })
446+
expect((output.logs as Array<Record<string, unknown>>)[0]?.output).toEqual({ ok: true })
373447
})
374448

375449
/**
376-
* Nothing is bounded while the whole result fits the projection's caps, so a result that crossed
377-
* in full before still does: a lifted output and its log copy of about 27.5k values each, or one
378-
* 4.5 MB block output.
450+
* A preview keeps a prefix that can cut through a secret, so with one active an oversized final
451+
* output becomes a pointer whose text does not depend on the secret.
379452
*/
380-
it('returns a result that fits the caps in full while a secret is active', async () => {
381-
const rows = wideRows()
382-
mocks.executeWorkflowUseCase.mockResolvedValue({
383-
success: true,
384-
output: {},
385-
logs: [{ blockId: 'query', blockName: 'Query', success: true, output: { rows } }],
386-
metadata: { executionId: EXECUTION_ID },
387-
})
388-
const lifted = inspectToolResultForCopilot(
389-
await executeRunWorkflowUntilBlock(
390-
{ workflowId: 'wf-1', stopAfterBlockId: 'query' },
391-
context
392-
),
393-
registry,
394-
'run_workflow'
395-
)
396-
expect(lifted.safe).toBe(true)
397-
const liftedOutput = lifted.result.output as Record<string, unknown>
398-
expect(liftedOutput.output).toEqual({ rows })
399-
expect((liftedOutput.logs as Array<Record<string, unknown>>)[0]?.output).toEqual({ rows })
453+
it('replaces an oversized final output with a pointer, never a preview, while a secret is active', async () => {
454+
async function finalOutputFor(secret: string) {
455+
mocks.executeWorkflowUseCase.mockResolvedValue({
456+
success: true,
457+
output: { report: `${'r'.repeat(20_000)}${secret}`, token: secret },
458+
logs: [{ blockId: 'small', blockName: 'Small', success: true, output: { ok: true } }],
459+
metadata: { executionId: EXECUTION_ID },
460+
})
461+
const settled = await executeRunWorkflow({ workflowId: 'wf-1' }, context)
462+
expect(inspectToolResultForCopilot(settled, registry, 'run_workflow').safe).toBe(true)
463+
return (settled.output as Record<string, unknown>).output
464+
}
400465

401-
const text = { text: 'y'.repeat(4_500_000) }
402-
mocks.executeWorkflowUseCase.mockResolvedValue({
403-
success: true,
404-
output: { done: true },
405-
logs: [{ blockId: 'big', blockName: 'Big', success: true, output: text }],
406-
metadata: { executionId: EXECUTION_ID },
407-
})
408-
const wide = inspectToolResultForCopilot(
409-
await executeRunWorkflow({ workflowId: 'wf-1' }, context),
410-
registry,
411-
'run_workflow'
412-
)
413-
expect(wide.safe).toBe(true)
414-
expect((wide.result.output as { logs: Array<{ output: unknown }> }).logs[0]?.output).toEqual(
415-
text
466+
const short = await finalOutputFor(SECRET)
467+
expect(short).toEqual(
468+
expect.stringMatching(/^…\[output omitted: \d+ values; inspect with logs get /)
416469
)
470+
expect(await finalOutputFor(`${SECRET}-but-considerably-longer`)).toBe(short)
417471
})
418472

419473
/**

0 commit comments

Comments
 (0)