Skip to content

Commit 88c0785

Browse files
committed
improvement(workflow-tests): record each run's stubbed writes on the host
runWorkflowForTest reports its WriteStubPolicy summary to the session when the run ends, after releasing its execution slot, with a throwing callback logged rather than masking the run's own error. The session keeps a payload-free summary per execution, repeats folded into counted entries (at most 20 per list and 50 runs per file, the rest counted), and the file runner stores it as report.sideEffects next to the sandbox's report; only runs finished when the sandbox returns are reported. The contract reads the stored schema, and the Mothership tests tool lists unmockedWrites per run.
1 parent 4ea347b commit 88c0785

9 files changed

Lines changed: 202 additions & 26 deletions

File tree

‎apps/sim/lib/api/contracts/workflow-tests.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { z } from 'zod'
22
import { workspaceIdSchema } from '@/lib/api/contracts/primitives'
33
import { type ContractJsonResponse, defineRouteContract } from '@/lib/api/contracts/types'
4-
import { testCaseStatusSchema, testReportSchema } from '@/lib/workflow-tests/protocol'
4+
import { storedTestReportSchema, testCaseStatusSchema } from '@/lib/workflow-tests/protocol'
55

66
const versionSchema = z.enum(['draft', 'deployed'])
77
const testNameSchema = z
@@ -42,7 +42,7 @@ const runSummarySchema = z.object({
4242

4343
/** One run with its report, and each case's status while it goes. */
4444
const runDetailSchema = runSummarySchema.extend({
45-
report: testReportSchema.nullable(),
45+
report: storedTestReportSchema.nullable(),
4646
/** Each case's status by `describe > it` path while the run goes; null before any. */
4747
progress: z.record(z.string(), testCaseStatusSchema).nullable(),
4848
})

‎apps/sim/lib/mothership/tools/server/tests.ts‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import {
1818
readWorkflowTestRuns,
1919
updateWorkflowTest,
2020
} from '@/lib/workflow-tests/application/tests'
21-
import type { TestReport } from '@/lib/workflow-tests/protocol'
21+
import type { StoredTestReport } from '@/lib/workflow-tests/protocol'
2222

2323
const RUN_POLL_MS = 2_000
2424

@@ -31,7 +31,7 @@ function workspaceFor(input: { workspaceId?: string }, context?: ServerToolConte
3131
}
3232

3333
/** Each failing case once: where it failed and why, in vitest's own words or the judge's. */
34-
function failures(report: TestReport | null) {
34+
function failures(report: StoredTestReport | null) {
3535
if (!report) return []
3636
return report.tests
3737
.filter((test) => test.status === 'fail')
@@ -46,6 +46,21 @@ function failures(report: TestReport | null) {
4646
})
4747
}
4848

49+
/**
50+
* Each write a run stubbed because no mock answered it, once, as `block → tool` (a block answered
51+
* whole by its name alone): a test that passes may still lean on a placeholder.
52+
*/
53+
function unmockedWrites(report: StoredTestReport | null): string[] {
54+
const executions = Object.values(report?.sideEffects?.executions ?? {})
55+
const writes = executions.flatMap((execution) =>
56+
execution.stubbed.map(({ block, blockId, tool }) => {
57+
const site = block ?? blockId ?? 'unnamed block'
58+
return tool ? `${site} → ${tool}` : site
59+
})
60+
)
61+
return [...new Set(writes)]
62+
}
63+
4964
const TEST_READ_ACTIONS = new Set(['list', 'get'])
5065

5166
export const testsServerTool: BaseServerTool = {
@@ -123,6 +138,7 @@ export const testsServerTool: BaseServerTool = {
123138
failed: detail.latestRun.failed,
124139
error: detail.latestRun.error,
125140
failures: failures(detail.latestRun.report),
141+
unmockedWrites: unmockedWrites(detail.latestRun.report),
126142
}
127143
: null,
128144
}
@@ -161,6 +177,7 @@ export const testsServerTool: BaseServerTool = {
161177
skipped: run.skipped,
162178
...(run.error ? { error: run.error } : {}),
163179
failures: failures(run.report),
180+
unmockedWrites: unmockedWrites(run.report),
164181
})),
165182
}
166183
}

‎apps/sim/lib/workflow-tests/application/tests.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import { workflowTestOperations } from '@/lib/workflow-tests/application/operati
88
import { starterTestSource, testSourceHash } from '@/lib/workflow-tests/definition'
99
import { requireWorkflowTestsEnabled } from '@/lib/workflow-tests/feature-flag'
1010
import { assertTestName, testFilePath } from '@/lib/workflow-tests/paths'
11-
import type { TestCaseStatus, TestReport } from '@/lib/workflow-tests/protocol'
11+
import type { StoredTestReport, TestCaseStatus } from '@/lib/workflow-tests/protocol'
1212
import {
1313
type DeploymentFacts,
1414
getLatestWorkflowTestRun,
@@ -237,7 +237,7 @@ export const getWorkflowTestDetail = defineAuthorizedWorkspaceUseCase({
237237
function presentRunDetail(row: WorkflowTestRunRow, testSourceHash: string, facts: DeploymentFacts) {
238238
return {
239239
...presentRun(row, testSourceHash, facts),
240-
report: row.report as TestReport | null,
240+
report: row.report as StoredTestReport | null,
241241
progress: row.progress as Record<string, TestCaseStatus> | null,
242242
}
243243
}
@@ -390,7 +390,7 @@ export const readWorkflowTestRuns = defineAuthorizedWorkspaceUseCase({
390390
runs: rows.map((row) => ({
391391
...presentRun(row, row.testSourceHash, facts),
392392
name: row.testName,
393-
report: row.report as TestReport | null,
393+
report: row.report as StoredTestReport | null,
394394
})),
395395
}
396396
},

‎apps/sim/lib/workflow-tests/protocol.ts‎

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,48 @@ export const testReportSchema = z.object({
127127
})
128128
),
129129
})
130-
export type TestReport = z.infer<typeof testReportSchema>
130+
131+
/** What one workflow run of a test did with the writes it reached, without their payloads. */
132+
const testRunSideEffectsSchema = z.object({
133+
/** Writes no mock answered, stubbed with a placeholder; `tool` is null for a block answered whole. */
134+
stubbed: z.array(
135+
z.object({
136+
workflowId: z.string(),
137+
blockId: z.string().nullable(),
138+
block: z.string().nullable(),
139+
tool: z.string().nullable(),
140+
/** Calls folded into this entry. */
141+
count: z.number().int().positive(),
142+
})
143+
),
144+
/** Code that ran for real, whose network calls are not stubbed. */
145+
unchecked: z.array(
146+
z.object({
147+
block: z.string().nullable(),
148+
reason: z.string(),
149+
count: z.number().int().positive(),
150+
})
151+
),
152+
/** Calls each list left out once it was full. */
153+
omitted: z.object({ stubbed: z.number().int(), unchecked: z.number().int() }),
154+
})
155+
export type TestRunSideEffects = z.infer<typeof testRunSideEffectsSchema>
156+
157+
/**
158+
* A test file's report as the host stores it: the sandbox's {@link testReportSchema} report, and
159+
* the side effects of each run that reached any, which the host records from the runs themselves,
160+
* never from the sandbox.
161+
*/
162+
export const storedTestReportSchema = testReportSchema.extend({
163+
sideEffects: z
164+
.object({
165+
/** By execution id; at most a fixed number of runs, the rest counted in `omittedExecutions`. */
166+
executions: z.record(z.string(), testRunSideEffectsSchema),
167+
omittedExecutions: z.number().int(),
168+
})
169+
.optional(),
170+
})
171+
export type StoredTestReport = z.infer<typeof storedTestReportSchema>
131172

132173
export const testCollectionSchema = z.object({
133174
topLevel: z.array(z.object({ kind: z.enum(['suite', 'test']), name: z.string() })),

‎apps/sim/lib/workflow-tests/repository.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,11 @@ import {
99
} from '@sim/db/schema'
1010
import { and, desc, eq, inArray, isNull, sql } from 'drizzle-orm'
1111
import type { DbOrTx, DbTransaction } from '@/lib/db/types'
12-
import type { TestCaseStatus, TestCollection, TestReport } from '@/lib/workflow-tests/protocol'
12+
import type {
13+
StoredTestReport,
14+
TestCaseStatus,
15+
TestCollection,
16+
} from '@/lib/workflow-tests/protocol'
1317
import type { WorkflowTestVersion } from '@/lib/workflows/application/run-workflow-for-test'
1418

1519
export type WorkflowTestRow = typeof workflowTest.$inferSelect
@@ -282,7 +286,7 @@ export async function readDeploymentFacts(
282286

283287
export async function completeWorkflowTestRun(
284288
runId: string,
285-
report: TestReport,
289+
report: StoredTestReport,
286290
sourceHash: string,
287291
ranAgainst: RanAgainstEntry[]
288292
): Promise<void> {

‎apps/sim/lib/workflow-tests/run-test-file.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@ import type { Principal } from '@sim/auth/principal'
22
import { generateShortId } from '@sim/utils/id'
33
import { runSandboxTask } from '@/lib/execution/sandbox/run-task'
44
import {
5+
type StoredTestReport,
56
type TestCaseStatus,
6-
type TestReport,
77
testReportSchema,
88
} from '@/lib/workflow-tests/protocol'
99
import type { EnteredWorkflow } from '@/lib/workflow-tests/repository'
@@ -29,11 +29,14 @@ export interface RunWorkflowTestFileInput {
2929

3030
/**
3131
* Runs one test file in the sandbox. Each `runWorkflow()` it makes becomes a real workflow
32-
* run whose mocked blocks are answered by the file's own mocks.
32+
* run whose mocked blocks are answered by the file's own mocks. The report adds what those runs
33+
* did with the writes no mock answered, as the host saw it: only runs that finished before the
34+
* sandbox returned, since a run the file left unawaited is cancelled when its session closes and
35+
* reports nothing.
3336
*/
3437
export async function runWorkflowTestFile(
3538
input: RunWorkflowTestFileInput
36-
): Promise<{ report: TestReport; entered: EnteredWorkflow[] }> {
39+
): Promise<{ report: StoredTestReport; entered: EnteredWorkflow[] }> {
3740
const requestId = generateShortId(12)
3841
const session = new WorkflowTestSession({
3942
workspaceId: input.workspaceId,
@@ -49,8 +52,9 @@ export async function runWorkflowTestFile(
4952
{ workspaceId: input.workspaceId, code: input.source, codeFilename: input.filePath },
5053
{ requestId, ownerKey: `workspace:${input.workspaceId}`, signal: input.signal }
5154
)
55+
const report = testReportSchema.parse(JSON.parse(Buffer.from(bytes).toString('utf-8')))
5256
return {
53-
report: testReportSchema.parse(JSON.parse(Buffer.from(bytes).toString('utf-8'))),
57+
report: { ...report, sideEffects: session.sideEffects() },
5458
entered: session.enteredWorkflows(),
5559
}
5660
} finally {

‎apps/sim/lib/workflow-tests/session.ts‎

Lines changed: 81 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,24 @@ import {
1414
type MockMatcher,
1515
type ParkedMockCall,
1616
} from '@/lib/workflow-tests/mock-channel'
17-
import type { TestCaseStatus, TestEvent, TestTarget } from '@/lib/workflow-tests/protocol'
17+
import type {
18+
StoredTestReport,
19+
TestCaseStatus,
20+
TestEvent,
21+
TestRunSideEffects,
22+
TestTarget,
23+
} from '@/lib/workflow-tests/protocol'
1824
import { type EnteredWorkflow, readDraftTimestamps } from '@/lib/workflow-tests/repository'
1925
import {
2026
runWorkflowForTest,
2127
type WorkflowTestRunResult,
2228
type WorkflowTestVersion,
2329
} from '@/lib/workflows/application/run-workflow-for-test'
24-
import { sampleBlockOutput, sampleToolOutput } from '@/lib/workflows/dry-run'
30+
import {
31+
type SideEffectsSummary,
32+
sampleBlockOutput,
33+
sampleToolOutput,
34+
} from '@/lib/workflows/dry-run'
2535
import {
2636
loadDeployedWorkflowState,
2737
loadWorkflowFromNormalizedTables,
@@ -39,6 +49,50 @@ import { hasToolId } from '@/tools/tool-ids'
3949
/** How long one `testNext` broker call waits before answering `waiting`, well under the broker timeout. */
4050
const EVENT_WAIT_MS = 25_000
4151

52+
/** Runs whose side effects a test file's report keeps; it counts the rest. */
53+
const MAX_RUNS_WITH_SIDE_EFFECTS = 50
54+
55+
/** Distinct entries a run keeps per list, so a report row stays small; it counts the rest. */
56+
const MAX_SITES_PER_RUN = 20
57+
58+
/**
59+
* `entries` with each repeat folded into one entry and counted, at most
60+
* {@link MAX_SITES_PER_RUN} of them; `omitted` counts the calls of the distinct ones left out.
61+
*/
62+
function tally<T extends object>(entries: readonly T[]) {
63+
const kept = new Map<string, T & { count: number }>()
64+
let omitted = 0
65+
for (const entry of entries) {
66+
const key = JSON.stringify(entry)
67+
const seen = kept.get(key)
68+
if (seen) seen.count++
69+
else if (kept.size < MAX_SITES_PER_RUN) kept.set(key, { ...entry, count: 1 })
70+
else omitted++
71+
}
72+
return { kept: [...kept.values()], omitted }
73+
}
74+
75+
/** A run's side effects as a report keeps them: who did what and how often, never a payload. */
76+
function compactSideEffects(summary: SideEffectsSummary): TestRunSideEffects {
77+
const stubbed = tally(
78+
summary.stubbed.map(({ workflowId, blockId, block, tool }) => ({
79+
workflowId,
80+
blockId,
81+
block,
82+
tool,
83+
}))
84+
)
85+
const unchecked = tally(summary.unchecked.map(({ block, reason }) => ({ block, reason })))
86+
return {
87+
stubbed: stubbed.kept,
88+
unchecked: unchecked.kept,
89+
omitted: {
90+
stubbed: summary.omitted.stubbed + stubbed.omitted,
91+
unchecked: summary.omitted.unchecked + unchecked.omitted,
92+
},
93+
}
94+
}
95+
4296
export interface WorkflowTestSessionConfig {
4397
workspaceId: string
4498
principal: Principal
@@ -515,6 +569,9 @@ export class WorkflowTestSession {
515569
private closed = false
516570
/** Stops `toMatchRubric` model calls still in flight when the sandbox run ends. */
517571
private readonly judgeAbort = new AbortController()
572+
/** Each finished run's side effects by execution id, for runs that reached any write or code. */
573+
private readonly runSideEffects = new Map<string, TestRunSideEffects>()
574+
private omittedRunSideEffects = 0
518575

519576
constructor(readonly config: WorkflowTestSessionConfig) {}
520577

@@ -545,6 +602,7 @@ export class WorkflowTestSession {
545602
triggerBlockId,
546603
testHooks: channel.hooks,
547604
abortSignal: abort.signal,
605+
onSideEffects: (executionId, summary) => this.recordSideEffects(executionId, summary),
548606
})
549607
const run = new TestWorkflowRun(channel, execution, abort, matcher)
550608
this.runs.set(run.id, run)
@@ -600,6 +658,27 @@ export class WorkflowTestSession {
600658
return [...this.enteredVersions.values()]
601659
}
602660

661+
private recordSideEffects(executionId: string, summary: SideEffectsSummary): void {
662+
const { stubbed, unchecked, omitted } = summary
663+
if (stubbed.length + unchecked.length + omitted.stubbed + omitted.unchecked === 0) return
664+
if (this.runSideEffects.size >= MAX_RUNS_WITH_SIDE_EFFECTS) {
665+
this.omittedRunSideEffects++
666+
return
667+
}
668+
this.runSideEffects.set(executionId, compactSideEffects(summary))
669+
}
670+
671+
/**
672+
* What this file's runs finished so far did with the writes they reached, recorded here from
673+
* the runs themselves: the sandbox's own report is untrusted. A run still going is absent.
674+
*/
675+
sideEffects(): NonNullable<StoredTestReport['sideEffects']> {
676+
return {
677+
executions: Object.fromEntries(this.runSideEffects),
678+
omittedExecutions: this.omittedRunSideEffects,
679+
}
680+
}
681+
603682
close(): void {
604683
this.closed = true
605684
this.judgeAbort.abort(new Error('The test run ended'))

‎apps/sim/lib/workflows/application/dry-run.integration.ts‎

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1256,16 +1256,14 @@ describe('a dry run', () => {
12561256
expect(await tableRows(tableId)).toEqual([])
12571257
})
12581258

1259-
it('stubs a workflow test’s unmocked writes', async () => {
1259+
it('stubs a workflow test’s unmocked writes and records them on the host, payloads dropped', async () => {
12601260
const tableId = await createTable()
12611261
const name = `Dry test ${generateId()}`
1262-
await saveWorkflow(
1263-
graph(
1264-
[block('start', 'start_trigger'), upsertLead('save', tableId, 'a@b.co')],
1265-
[['start', 'save']]
1266-
).state,
1267-
name
1262+
const fixture = graph(
1263+
[block('start', 'start_trigger'), upsertLead('save', tableId, 'a@b.co')],
1264+
[['start', 'save']]
12681265
)
1266+
const workflowId = await saveWorkflow(fixture.state, name)
12691267
const session = new WorkflowTestSession({
12701268
workspaceId,
12711269
principal,
@@ -1277,8 +1275,26 @@ describe('a dry run', () => {
12771275
let event = await session.start({ workflow: name, trigger: null, input: {}, targets: [] })
12781276
while (event.kind === 'waiting') event = await session.next(event.runId)
12791277

1280-
expect(event).toMatchObject({ kind: 'done' })
1278+
if (event.kind !== 'done') throw new Error(`The run ended with ${event.kind}`)
12811279
expect(await tableRows(tableId)).toEqual([])
1280+
expect(session.sideEffects()).toEqual({
1281+
executions: {
1282+
[event.executionId]: {
1283+
stubbed: [
1284+
{
1285+
workflowId,
1286+
blockId: fixture.idOf('save'),
1287+
block: 'save',
1288+
tool: 'table_upsert_row',
1289+
count: 1,
1290+
},
1291+
],
1292+
unchecked: [],
1293+
omitted: { stubbed: 0, unchecked: 0 },
1294+
},
1295+
},
1296+
omittedExecutions: 0,
1297+
})
12821298
})
12831299

12841300
it('is forwarded by the v2 execute route, a block entry’s included', async () => {

0 commit comments

Comments
 (0)