From 4a9f9f57270b69a5d64e4d0ccf64426ce9dd7fd5 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 25 Nov 2026 11:15:44 -0800 Subject: [PATCH 1/2] feat(workflows): dry-run overrides reach child workflows, mock from an earlier run --allow and --mock (run.allowBlocks / run.mocks) now also name a block of a workflow the run calls as . (the workflow's id or name, then the block's id, name or key). A dotted selector names a block of the run's workflow only by its exact id or display name (keys drop dots, so `slack.send` never shadows child "Slack" block "Send"); otherwise its workflow part matches the children Workflow blocks call by a fixed id, at any depth up to the call chain limit, then, for a child chosen as the run goes, a workflow of the same workspace by id or exact name, looked up once per request in one query. Selectors are capped at 256 characters. Matches are deduplicated by workflow and block; several distinct ones are refused with candidates. Another workspace's workflow is never found, so its refusal is an unknown id's. A workflow reachable only as a custom block is refused unless a Workflow block chooses its child at run time. The policy keys every override by workflow and block id, so a child's entry applies wherever that workflow runs, at every depth. The dry-run record adds childAllowBlocks / childMockedBlocks. Rough edges: loops, parallels, and blocks disabled anywhere up their container chain are refused as targets; a mock of a block of a locked workflow or folder returns 423 through requireMutableWorkflow, as any change to one does; a mock holding a __simLargeValueRef is refused; the duplicate-mock error names both selectors. sideEffects reports `unused` overrides, `undeclaredMockFields` (Agent and Function outputs skipped) and `droppedMockFields`, and the CLI prints a note for each. run.mocksFrom {runId, blocks} (--mock-from with a bare --mock ) answers this workflow's blocks with the outputs they recorded in an earlier run of it, read through readWorkflowRun (read role, logs.trace_spans projection, secrets redacted). Fields only a block sets are left out and reported. Refused: a block the run did not execute; one in a loop or parallel unless that run mocked it; and, from a test run, a block it answered with a placeholder rather than mocking or allowing it. An unknown run is 404; a running one, or one with no recorded outputs yet, 409; outputs hidden by the viewer's permission group 403 (readWorkflowRun now says which). A child selector there is refused with a pointer to run.mocks. Recorded as dryRun.mocksFrom. next repeats --mock-from; mocks the caller passed to this workflow's blocks are read back from the failed run itself, and only a child's mock, or one passed beside --mock-from, comes back as a --mock '=' placeholder, which the CLI refuses verbatim with a hint to replace it. --- apps/docs/content/docs/cli/reference.mdx | 12 +- apps/docs/content/docs/cli/workflows.mdx | 12 +- apps/docs/openapi-v2-workflows.json | 193 +++++- .../workflows/[workflowId]/execute/route.ts | 2 + .../[workflowId]/runs/[runId]/route.ts | 3 +- apps/sim/executor/execution/types.ts | 14 +- apps/sim/executor/utils/mock-output.ts | 25 +- apps/sim/lib/api/contracts/v2/workflows.ts | 114 +++- .../workflows/application/block-selector.ts | 48 ++ .../application/dry-run-overrides.ts | 611 ++++++++++++++++++ .../application/dry-run.integration.ts | 561 +++++++++++++++- .../application/execute-manual-workflow.ts | 159 +---- .../application/read-workflow-run.ts | 2 + apps/sim/lib/workflows/dry-run/index.ts | 4 + .../sim/lib/workflows/dry-run/side-effects.ts | 131 +++- .../workflows/executor/execution-status.ts | 9 +- apps/sim/lib/workflows/queries.ts | 40 +- apps/sim/tools/index.test.ts | 2 +- apps/sim/tools/side-effects.test.ts | 5 +- .../protocol/workflow-run-follow.test.ts | 33 +- .../commands/protocol/workflow-run-follow.ts | 109 +++- packages/sim-cli/src/generated/v2-api.ts | 46 ++ packages/sim-cli/src/runtime/run-next.test.ts | 27 +- packages/sim-cli/src/runtime/run-next.ts | 47 +- 24 files changed, 1991 insertions(+), 218 deletions(-) create mode 100644 apps/sim/lib/workflows/application/block-selector.ts create mode 100644 apps/sim/lib/workflows/application/dry-run-overrides.ts diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 33b58e17ebd..a3c9d34773d 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8516,10 +8516,10 @@ sim workflows run [options] | `--base64-max-bytes ` | No | Maximum total bytes of file content to inline as base64, lowering but never raising the server limit of 16 MiB. Rejected when `async` is true. | | `--run-id ` | No | One-shot identifier for this run; NOT an idempotency key — reusing a claimed value fails with RUN_ID_CONFLICT instead of replaying the first result, and a fresh value starts another run. | | `--manual` | No | Run the current saved workflow state instead of the active deployment. | -| `--deployment-version ` | No | Run this deployed version instead of the active one (a version number from `sim workflows versions list`); a Workflow block in it still runs its child workflow's active deployment. Needs workspace write access, through a full-access API key or an OAuth token with api:write. Not with --manual or any flag that runs the draft. | | `--dry` | No | Dry run of the saved draft (implies --manual): writes are not sent but answered with placeholders and listed with their request payloads in sideEffects; reads, model calls and code run for real. Logged as a test run. Not with --follow, --async or --wait-timeout. | -| `--allow ` | No | Send this block's writes for real during a --dry run (its id, display name or key); for an Agent, only its own tool calls, not a workflow or custom block it calls; repeatable. | -| `--mock =` | No | Answer this block with the given JSON object instead of running it during a --dry run (its id, display name or key), to steer a branch or give a stubbed write a realistic result. Not a locked block; data only, so no cost, tokens, model or other field the run’s trace or billing reads, and no field starting with _. The run records only which blocks were mocked, so a rerun passes it again (its log shows the output like any other block’s); repeatable. | +| `--allow ` | No | Send this block's writes for real during a --dry run (its id, display name or key, or <workflow>.<block> for a workflow it calls); for an Agent, only its own tool calls, not a workflow or custom block it calls; repeatable. | +| `--mock =` | No | Answer this block with the given JSON object instead of running it during a --dry run (its id, display name or key, or <workflow>.<block> for a workflow it calls), to steer a branch or give a stubbed write a realistic result; a bare --mock <block> takes its output from --mock-from. Not a locked block, or one of a locked workflow or folder; data only, so no cost, tokens, model or other field the run’s trace or billing reads, and no field starting with _. The run records only which blocks were mocked, not the outputs (its log shows each like any other block’s output), so a rerun reads them again with --mock-from; repeatable. | +| `--mock-from ` | No | Answer each block a bare --mock <block> names (this workflow's blocks only) with the output it recorded in this earlier run of the workflow, redacted as the run shows it; fields only a block sets, such as cost or model, are left out (requires --dry). | | `--trigger ` | No | Enter the run through this runnable trigger, by its block id; runs the current saved workflow state (implies --manual). | | `--mock-payload` | No | Use the selected trigger's server-derived mock payload; runs the current saved workflow state (implies --manual). | | `--from-block ` | No | Rerun the saved draft from this block (its id, display name or key), reusing the outputs --source-run produced before it; a failed run prints this command as next. | @@ -8533,13 +8533,13 @@ sim workflows run [options] -Without --manual (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --deployment-version <n> runs that deployed version instead, as a pin for comparing or reproducing (it needs workspace write access, through a full-access API key or an OAuth token with api:write); the child workflows it calls still run their own active deployment. --manual runs the saved draft, as the source loop leaves it. +Without --manual (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --manual runs the saved draft, as the source loop leaves it. ---dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls other than GET/HEAD/OPTIONS, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes) runs: its GET/HEAD/OPTIONS fetches are sent (an API that writes on a GET is not stubbed), and any other fetch, or one with a method-override header, gets an empty 200 and is listed in sideEffects.stubbed. Code in a remote sandbox (shell, Python, imports) is listed in sideEffects.unchecked, since its network cannot be seen. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. Agents read memory but write none, and the run raises no workspace event. --allow <block> sends that block's writes (a Function's fetches included) for real (use a test resource); allowing an Agent sends only its own tool calls, not a workflow or custom block it calls. --mock <block>=<json> answers a block with fixed output, to steer a branch; a locked block cannot be mocked, and a mock is data, so it cannot set a field the run's execution, trace or billing reads (such as cost, tokens, model or a field starting with _). A dry run is the --source-run only of another dry run, and is never resumed. +--dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes) runs and is listed in sideEffects.unchecked. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. Agents read memory but write none, and the run raises no workspace event. --allow <block> sends that block's writes for real (use a test resource); allowing an Agent sends only its own tool calls, not a workflow or custom block it calls. --mock <block>=<json> answers a block with fixed output, to steer a branch; a locked block, or one of a locked workflow or folder, cannot be mocked, and a mock is data, so it cannot set a field the run's execution, trace or billing reads (such as cost, tokens, model or a field starting with _). --mock-from <runId> with a bare --mock <block> answers that block with the output it recorded in that run of this workflow (not a block a test run answered with a placeholder); fields only a block sets, such as cost or model, are left out and noted. --allow and --mock also name a block of a workflow this one calls as <workflow>.<block> (the workflow's id or name); the entry applies wherever that workflow runs, at every depth. Blocks for --from-block, --stop-after and a bare --mock with --mock-from are this workflow's only. Blocks never reached, and mock fields a block does not declare, are noted. A dry run is the --source-run only of another dry run, and is never resumed. The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: branch on status, or on the exit code. With --follow it is the stream's final frame instead: success and output. -A run that failed in a block has next: the command that reruns the saved draft from that block (or from the outermost loop or parallel holding it) with this run as --source-run, so after a fix only that block and those after it run again; a dry run's keeps --dry and --allow. The run records only which blocks were mocked, so pass each --mock again; its log shows a mocked block's output like any other. Add --stop-after <block> to stop after a block; naming the block next starts from reruns only it. +A run that failed in a block has next: the command that reruns the saved draft from that block (or from the outermost loop or parallel holding it) with this run as --source-run, so after a fix only that block and those after it run again; a dry run's keeps --dry and --allow, and reads its mocks again with --mock-from (this run, for mocks you passed). A mock of a child's block, or one passed beside --mock-from, comes back as --mock <block>=<json>: replace <json> with the output. Add --stop-after <block> to stop after a block; naming the block next starts from reruns only it. Exit codes: 0 completed or paused (--async: queued); 1 failed or cancelled (the result is printed first, then the error on stderr), or the command failed; 4 still running when --wait-timeout elapsed. diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index c038e50e73b..e4e02e678bd 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -833,10 +833,10 @@ sim workflows run [options] | `--base64-max-bytes ` | No | Maximum total bytes of file content to inline as base64, lowering but never raising the server limit of 16 MiB. Rejected when `async` is true. | | `--run-id ` | No | One-shot identifier for this run; NOT an idempotency key — reusing a claimed value fails with RUN_ID_CONFLICT instead of replaying the first result, and a fresh value starts another run. | | `--manual` | No | Run the current saved workflow state instead of the active deployment. | -| `--deployment-version ` | No | Run this deployed version instead of the active one (a version number from `sim workflows versions list`); a Workflow block in it still runs its child workflow's active deployment. Needs workspace write access, through a full-access API key or an OAuth token with api:write. Not with --manual or any flag that runs the draft. | | `--dry` | No | Dry run of the saved draft (implies --manual): writes are not sent but answered with placeholders and listed with their request payloads in sideEffects; reads, model calls and code run for real. Logged as a test run. Not with --follow, --async or --wait-timeout. | -| `--allow ` | No | Send this block's writes for real during a --dry run (its id, display name or key); for an Agent, only its own tool calls, not a workflow or custom block it calls; repeatable. | -| `--mock =` | No | Answer this block with the given JSON object instead of running it during a --dry run (its id, display name or key), to steer a branch or give a stubbed write a realistic result. Not a locked block; data only, so no cost, tokens, model or other field the run’s trace or billing reads, and no field starting with _. The run records only which blocks were mocked, so a rerun passes it again (its log shows the output like any other block’s); repeatable. | +| `--allow ` | No | Send this block's writes for real during a --dry run (its id, display name or key, or <workflow>.<block> for a workflow it calls); for an Agent, only its own tool calls, not a workflow or custom block it calls; repeatable. | +| `--mock =` | No | Answer this block with the given JSON object instead of running it during a --dry run (its id, display name or key, or <workflow>.<block> for a workflow it calls), to steer a branch or give a stubbed write a realistic result; a bare --mock <block> takes its output from --mock-from. Not a locked block, or one of a locked workflow or folder; data only, so no cost, tokens, model or other field the run’s trace or billing reads, and no field starting with _. The run records only which blocks were mocked, not the outputs (its log shows each like any other block’s output), so a rerun reads them again with --mock-from; repeatable. | +| `--mock-from ` | No | Answer each block a bare --mock <block> names (this workflow's blocks only) with the output it recorded in this earlier run of the workflow, redacted as the run shows it; fields only a block sets, such as cost or model, are left out (requires --dry). | | `--trigger ` | No | Enter the run through this runnable trigger, by its block id; runs the current saved workflow state (implies --manual). | | `--mock-payload` | No | Use the selected trigger's server-derived mock payload; runs the current saved workflow state (implies --manual). | | `--from-block ` | No | Rerun the saved draft from this block (its id, display name or key), reusing the outputs --source-run produced before it; a failed run prints this command as next. | @@ -850,13 +850,13 @@ sim workflows run [options] -Without --manual (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --deployment-version <n> runs that deployed version instead, as a pin for comparing or reproducing (it needs workspace write access, through a full-access API key or an OAuth token with api:write); the child workflows it calls still run their own active deployment. --manual runs the saved draft, as the source loop leaves it. +Without --manual (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --manual runs the saved draft, as the source loop leaves it. ---dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls other than GET/HEAD/OPTIONS, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes) runs: its GET/HEAD/OPTIONS fetches are sent (an API that writes on a GET is not stubbed), and any other fetch, or one with a method-override header, gets an empty 200 and is listed in sideEffects.stubbed. Code in a remote sandbox (shell, Python, imports) is listed in sideEffects.unchecked, since its network cannot be seen. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. Agents read memory but write none, and the run raises no workspace event. --allow <block> sends that block's writes (a Function's fetches included) for real (use a test resource); allowing an Agent sends only its own tool calls, not a workflow or custom block it calls. --mock <block>=<json> answers a block with fixed output, to steer a branch; a locked block cannot be mocked, and a mock is data, so it cannot set a field the run's execution, trace or billing reads (such as cost, tokens, model or a field starting with _). A dry run is the --source-run only of another dry run, and is never resumed. +--dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes) runs and is listed in sideEffects.unchecked. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. Agents read memory but write none, and the run raises no workspace event. --allow <block> sends that block's writes for real (use a test resource); allowing an Agent sends only its own tool calls, not a workflow or custom block it calls. --mock <block>=<json> answers a block with fixed output, to steer a branch; a locked block, or one of a locked workflow or folder, cannot be mocked, and a mock is data, so it cannot set a field the run's execution, trace or billing reads (such as cost, tokens, model or a field starting with _). --mock-from <runId> with a bare --mock <block> answers that block with the output it recorded in that run of this workflow (not a block a test run answered with a placeholder); fields only a block sets, such as cost or model, are left out and noted. --allow and --mock also name a block of a workflow this one calls as <workflow>.<block> (the workflow's id or name); the entry applies wherever that workflow runs, at every depth. Blocks for --from-block, --stop-after and a bare --mock with --mock-from are this workflow's only. Blocks never reached, and mock fields a block does not declare, are noted. A dry run is the --source-run only of another dry run, and is never resumed. The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: branch on status, or on the exit code. With --follow it is the stream's final frame instead: success and output. -A run that failed in a block has next: the command that reruns the saved draft from that block (or from the outermost loop or parallel holding it) with this run as --source-run, so after a fix only that block and those after it run again; a dry run's keeps --dry and --allow. The run records only which blocks were mocked, so pass each --mock again; its log shows a mocked block's output like any other. Add --stop-after <block> to stop after a block; naming the block next starts from reruns only it. +A run that failed in a block has next: the command that reruns the saved draft from that block (or from the outermost loop or parallel holding it) with this run as --source-run, so after a fix only that block and those after it run again; a dry run's keeps --dry and --allow, and reads its mocks again with --mock-from (this run, for mocks you passed). A mock of a child's block, or one passed beside --mock-from, comes back as --mock <block>=<json>: replace <json> with the output. Add --stop-after <block> to stop after a block; naming the block next starts from reruns only it. Exit codes: 0 completed or paused (--async: queued); 1 failed or cancelled (the result is printed first, then the error on stderr), or the command failed; 4 still running when --wait-timeout elapsed. diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index 67c0d390361..38b6e065112 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -17400,9 +17400,107 @@ "required": ["stubbed", "allowed", "unchecked"], "additionalProperties": false, "description": "Entries each list left out once it held 50." + }, + "unused": { + "type": "array", + "items": { + "type": "object", + "properties": { + "workflowId": { + "type": "string", + "description": "Workflow of the block." + }, + "blockId": { + "type": "string", + "description": "Block id in that workflow." + }, + "block": { + "type": "string", + "description": "Block display name." + }, + "override": { + "type": "string", + "enum": ["allow", "mock"], + "description": "Whether `run.allowBlocks` or a mock (`run.mocks`, `run.mocksFrom`) named it." + } + }, + "required": ["workflowId", "blockId", "block", "override"], + "additionalProperties": false + }, + "description": "Allowed and mocked blocks the run never reached: on a branch it did not take, upstream of a block entry, or in a child it never called." + }, + "undeclaredMockFields": { + "type": "array", + "items": { + "type": "object", + "properties": { + "workflowId": { + "type": "string", + "description": "Workflow of the block." + }, + "blockId": { + "type": "string", + "description": "Block id in that workflow." + }, + "block": { + "type": "string", + "description": "Block display name." + }, + "fields": { + "type": "array", + "items": { + "type": "string", + "description": "Output field." + }, + "description": "Fields not declared." + } + }, + "required": ["workflowId", "blockId", "block", "fields"], + "additionalProperties": false + }, + "description": "Passed mocks setting top-level fields their block does not declare as outputs, likely misspelt; a block reading one gets nothing. Agent and Function blocks, whose outputs the model or code decides, are never listed." + }, + "droppedMockFields": { + "type": "array", + "items": { + "type": "object", + "properties": { + "workflowId": { + "type": "string", + "description": "Workflow of the block." + }, + "blockId": { + "type": "string", + "description": "Block id in that workflow." + }, + "block": { + "type": "string", + "description": "Block display name." + }, + "fields": { + "type": "array", + "items": { + "type": "string", + "description": "Output field." + }, + "description": "Fields left out." + } + }, + "required": ["workflowId", "blockId", "block", "fields"], + "additionalProperties": false + }, + "description": "Mocks read from a run (`run.mocksFrom`) whose recorded output held fields only a block sets (`cost`, `tokens`, `model`, `toolCalls` and the like), which a mock cannot set and so were left out; a block reading one gets nothing." } }, - "required": ["stubbed", "allowed", "unchecked", "omitted"], + "required": [ + "stubbed", + "allowed", + "unchecked", + "omitted", + "unused", + "undeclaredMockFields", + "droppedMockFields" + ], "additionalProperties": false, "title": "Workflow run side effects", "description": "What a dry run did with each write it reached." @@ -17425,6 +17523,64 @@ "description": "Block id." }, "description": "Blocks the run answered with fixed outputs (`run.mocks`), by id. Only the ids are recorded, so a rerun passes the outputs again." + }, + "childAllowBlocks": { + "description": "Blocks of workflows it calls whose writes the run sent; a rerun names each as `.`. Absent when none.", + "type": "array", + "items": { + "type": "object", + "properties": { + "workflowId": { + "type": "string", + "description": "Workflow the run called." + }, + "blockId": { + "type": "string", + "description": "Block id in that workflow." + } + }, + "required": ["workflowId", "blockId"], + "additionalProperties": false + } + }, + "childMockedBlocks": { + "description": "Blocks of workflows it calls that the run answered with fixed outputs (`run.mocks`); a rerun passes each output again as `.`. Absent when none.", + "type": "array", + "items": { + "type": "object", + "properties": { + "workflowId": { + "type": "string", + "description": "Workflow the run called." + }, + "blockId": { + "type": "string", + "description": "Block id in that workflow." + } + }, + "required": ["workflowId", "blockId"], + "additionalProperties": false + } + }, + "mocksFrom": { + "description": "Blocks the run answered with their outputs in another run (`run.mocksFrom`), which a rerun reads again. Absent when none.", + "type": "object", + "properties": { + "runId": { + "type": "string", + "description": "Run the outputs were read from." + }, + "blockIds": { + "type": "array", + "items": { + "type": "string", + "description": "Block id." + }, + "description": "Blocks answered, by id." + } + }, + "required": ["runId", "blockIds"], + "additionalProperties": false } }, "required": ["allowBlocks", "mockedBlocks"], @@ -17765,19 +17921,22 @@ "type": "boolean" }, "allowBlocks": { - "description": "Blocks (id, display name or reference key) of this workflow whose writes a dry run sends for real, listed in `sideEffects.allowed`. Requires `dry`. A Human in the loop or Wait block, or a block that runs another workflow (a Workflow or custom block), cannot be allowed. Allowing an Agent sends only its own tool calls: a workflow or custom block it calls stays stubbed.", + "description": "Blocks whose writes a dry run sends for real, listed in `sideEffects.allowed`. Requires `dry`. Name a block of this workflow by id, display name or reference key, or a block of a workflow it calls as `.` (the workflow's id or name, then the block's id, name or key), at most 256 characters. A selector holding a dot names a block of this workflow only by its exact id or display name; otherwise its workflow part is matched against the workflows its Workflow blocks call at any depth, then, for a child chosen as the run goes, a workflow of this workspace by id or exact name. A selector matching several blocks is refused with them. A child's entry applies wherever that workflow runs, at every depth. A Human in the loop or Wait block, a block that runs another workflow (a Workflow or custom block), a loop or parallel, a disabled block, or a block of a workflow reached only as a custom block's cannot be allowed. Allowing an Agent sends only its own tool calls: a workflow or custom block it calls stays stubbed. An entry the run never reaches is listed in `sideEffects.unused`.", "maxItems": 50, "type": "array", "items": { "type": "string", - "minLength": 1 + "minLength": 1, + "maxLength": 256 } }, "mocks": { - "description": "Blocks of this workflow (keyed by id, display name or reference key) answered with this output object instead of running, to steer branches or give a stubbed write a realistic result. Requires `dry`. A locked block (or one inside a locked loop or parallel) cannot be mocked. A mock is data: it cannot set a field the run’s execution, trace or billing reads (`cost`, `tokens`, `model`, `providerTiming`, `toolCalls`, `executionData`, `childTraceSpans`, `childWorkflowId`, `childWorkflowSnapshotId`, `childDeploymentVersionId`, or any field starting with `_`). The run records only which blocks were mocked, so a rerun passes the outputs again; its log shows a mocked block’s output like any other block’s.", + "description": "Blocks answered with this output object instead of running, to steer branches or give a stubbed write a realistic result, keyed like `allowBlocks` entries (a block of this workflow, or `.` of a workflow it calls). Requires `dry`. A locked block (or one inside a locked loop or parallel), a loop or parallel, and a disabled block cannot be mocked; a block of a locked workflow, or of one in a locked folder, returns `423`. A mock is data: it cannot set a field the run’s execution, trace or billing reads (`cost`, `tokens`, `model`, `providerTiming`, `toolCalls`, `executionData`, `childTraceSpans`, `childWorkflowId`, `childWorkflowSnapshotId`, `childDeploymentVersionId`, or any field starting with `_`), nor hold a large-value reference (an object with `__simLargeValueRef`). A field the block does not declare is listed in `sideEffects.undeclaredMockFields`, not refused. The run records only which blocks were mocked, so a rerun passes the outputs again; its log shows a mocked block’s output like any other block’s.", "type": "object", "propertyNames": { - "type": "string" + "type": "string", + "maxLength": 256, + "description": "Block selector." }, "additionalProperties": { "type": "object", @@ -17790,6 +17949,30 @@ "description": "Output object that answers the block instead of its handler." }, "maxProperties": 50 + }, + "mocksFrom": { + "description": "Answer blocks with their outputs in an earlier run of this workflow. Requires `dry`. The run records the source run and blocks, so a rerun names them again.", + "type": "object", + "properties": { + "runId": { + "type": "string", + "minLength": 1, + "description": "Run of this workflow whose recorded block outputs answer the blocks. An unknown or expired run returns `404`; one still running, or whose log is not written yet, `409`; reading it needs what reading the run does, and a permission group that hides execution data returns `403`." + }, + "blocks": { + "minItems": 1, + "maxItems": 50, + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "description": "Blocks of this workflow only (id, display name or reference key; never a child’s) answered with the output each recorded in that run, redacted as the run shows it. Refused: a block the run did not execute; one inside a loop or parallel, unless that run mocked it; and, when that run was a test run, a block it answered with a placeholder rather than mocking or allowing it. Fields only a block sets (`cost`, `tokens`, `model`, `toolCalls`, child traces and the like, and fields starting with `_`) are left out and listed in `sideEffects.droppedMockFields`; an output holding a large-value reference is refused. Other refusals are those of `mocks`, and a block cannot be named here and in `mocks` both." + } + }, + "required": ["runId", "blocks"], + "additionalProperties": false } }, "required": ["source"], diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts b/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts index 027e08ddc3e..624e59e2438 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts @@ -554,6 +554,7 @@ export const POST = withRouteHandler( dry: manualRun.dry, allowBlocks: manualRun.allowBlocks, mocks: manualRun.mocks, + mocksFrom: manualRun.mocksFrom, }, request: req, }) @@ -570,6 +571,7 @@ export const POST = withRouteHandler( dry: manualRun.dry, allowBlocks: manualRun.allowBlocks, mocks: manualRun.mocks, + mocksFrom: manualRun.mocksFrom, }, request: req, }) diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/route.ts b/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/route.ts index c38294bb99c..a88ac375195 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/route.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/route.ts @@ -61,7 +61,8 @@ export const GET = defineV2JsonRoute({ output: status.finalOutput, blockOutputs: status.blockOutputs, files: status.files, - dryRun: status.dryRun, + // Only a failed dry run's: what a rerun of it names again. + dryRun: status.status === 'failed' ? status.dryRun : null, }, }), }) diff --git a/apps/sim/executor/execution/types.ts b/apps/sim/executor/execution/types.ts index c4cd785cec8..9b795f0380e 100644 --- a/apps/sim/executor/execution/types.ts +++ b/apps/sim/executor/execution/types.ts @@ -320,10 +320,22 @@ export interface ExecutionTestHooks { recordSpy(call: { blockId: string; input: unknown; output: unknown }): void } -/** A dry run's allowed and mocked blocks of the workflow it started, by id; never a mock's output. */ +/** A block of a child workflow a dry run names. */ +interface DryRunChildBlock { + workflowId: string + blockId: string +} + +/** A dry run's allowed and mocked blocks, by id; never a mock's output. */ export interface DryRunOptions { + /** Blocks of the workflow it started whose writes it sent. */ allowBlocks: string[] + /** Blocks of the workflow it started answered with outputs the caller passed. */ mockedBlocks: string[] + childAllowBlocks?: DryRunChildBlock[] + childMockedBlocks?: DryRunChildBlock[] + /** Blocks of the workflow it started answered with their outputs in another run. */ + mocksFrom?: { runId: string; blockIds: string[] } } /** Where a call that may change state outside the run was made: a block of one executing workflow. */ diff --git a/apps/sim/executor/utils/mock-output.ts b/apps/sim/executor/utils/mock-output.ts index 6e9e6211e60..599c6684bed 100644 --- a/apps/sim/executor/utils/mock-output.ts +++ b/apps/sim/executor/utils/mock-output.ts @@ -1,3 +1,4 @@ +import { LARGE_VALUE_REF_MARKER } from '@/lib/execution/payloads/large-value-ref' import { SPAN_SOURCE_OUTPUT_FIELDS } from '@/lib/logs/execution/trace-spans/factory' /** @@ -9,12 +10,30 @@ export function isRunControlledOutputField(field: string): boolean { return field.startsWith('_') || SPAN_SOURCE_OUTPUT_FIELDS.has(field) } +/** Whether `value` holds a large-value reference at any depth. */ +function holdsLargeValueRef(value: unknown): boolean { + const pending: unknown[] = [value] + while (pending.length > 0) { + const next = pending.pop() + if (next === null || typeof next !== 'object') continue + if (Object.hasOwn(next, LARGE_VALUE_REF_MARKER)) return true + pending.push(...Object.values(next)) + } + return false +} + /** * Why a mocked output, named by `label`, is refused; null when it sets only data. A mock (a dry - * run's `run.mocks`, or a workflow test's `mockBlock`) is data, never run control or billing. + * run's `run.mocks`, or a workflow test's `mockBlock`) is data, never run control or billing, and + * carries its data inline: a large-value reference would read a value this run was never granted. */ export function mockOutputRefusal(label: string, output: Record): string | null { const fields = Object.keys(output).filter(isRunControlledOutputField) - if (fields.length === 0) return null - return `${label} sets ${fields.join(', ')}: a mock is data, so it cannot set a field the run's execution, trace or billing reads (${[...SPAN_SOURCE_OUTPUT_FIELDS].join(', ')}, or any field starting with "_").` + if (fields.length > 0) { + return `${label} sets ${fields.join(', ')}: a mock is data, so it cannot set a field the run's execution, trace or billing reads (${[...SPAN_SOURCE_OUTPUT_FIELDS].join(', ')}, or any field starting with "_").` + } + if (holdsLargeValueRef(output)) { + return `${label} holds a large-value reference (an object with ${LARGE_VALUE_REF_MARKER}): a mock carries its data inline.` + } + return null } diff --git a/apps/sim/lib/api/contracts/v2/workflows.ts b/apps/sim/lib/api/contracts/v2/workflows.ts index 3bcca7f573f..7b4e31f7ffe 100644 --- a/apps/sim/lib/api/contracts/v2/workflows.ts +++ b/apps/sim/lib/api/contracts/v2/workflows.ts @@ -1638,6 +1638,9 @@ export const EXECUTE_OPTION_CONSTRAINTS = /** Blocks one run's `run.mocks` may answer. */ const MAX_RUN_MOCKS = 50 +/** Longest block selector a dry run resolves; a dotted one is tried at every dot. */ +const MAX_BLOCK_SELECTOR_LENGTH = 256 + export const v2WorkflowRunSelectionSchema = z.discriminatedUnion('source', [ z .object({ @@ -1712,15 +1715,23 @@ export const v2WorkflowRunSelectionSchema = z.discriminatedUnion('source', [ "Dry run: every tool call not declared `read` (sends, table writes, HTTP calls other than a GET, HEAD or OPTIONS without a method-override header, custom and MCP tools) is not sent; it returns a correctly shaped placeholder (a table row insert, upsert or update echoes the data it would have written, secrets masked) and is listed in `sideEffects.stubbed` with the request it would have sent, credentials, secrets and (when the workspace redacts it) PII redacted. Reads, model calls and credential resolution run for real, and so does code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes): JavaScript without imports sends its GET, HEAD and OPTIONS `fetch` calls (an API that writes on a GET is not stubbed), while any other request, or one carrying a method-override header, gets an empty 200 response (header `x-sim-dry-run: stubbed`) and is listed in `sideEffects.stubbed` as tool `function_execute`; code in a remote sandbox (shell, Python, JavaScript with imports, a selected sandbox or files) has network the run cannot see and is listed in `sideEffects.unchecked`. Child workflows inherit it. Custom, Mothership, Pi, Human in the loop and Wait blocks are answered whole with placeholders. Agents read their memory but write none, and nothing else beyond the run's own log is kept: it raises no workspace event and does not count as a run of the workflow. Logged under the `test` trigger. Synchronous only: cannot be combined with `stream` or `waitTimeoutSeconds`." ), allowBlocks: z - .array(z.string().min(1, 'run.allowBlocks entries cannot be empty')) + .array( + z + .string() + .min(1, 'run.allowBlocks entries cannot be empty') + .max(MAX_BLOCK_SELECTOR_LENGTH, 'run.allowBlocks entries are at most 256 characters') + ) .max(50) .optional() .describe( - 'Blocks (id, display name or reference key) of this workflow whose writes a dry run sends for real, listed in `sideEffects.allowed`. Requires `dry`. A Human in the loop or Wait block, or a block that runs another workflow (a Workflow or custom block), cannot be allowed. Allowing an Agent sends only its own tool calls: a workflow or custom block it calls stays stubbed.' + "Blocks whose writes a dry run sends for real, listed in `sideEffects.allowed`. Requires `dry`. Name a block of this workflow by id, display name or reference key, or a block of a workflow it calls as `.` (the workflow's id or name, then the block's id, name or key), at most 256 characters. A selector holding a dot names a block of this workflow only by its exact id or display name; otherwise its workflow part is matched against the workflows its Workflow blocks call at any depth, then, for a child chosen as the run goes, a workflow of this workspace by id or exact name. A selector matching several blocks is refused with them. A child's entry applies wherever that workflow runs, at every depth. A Human in the loop or Wait block, a block that runs another workflow (a Workflow or custom block), a loop or parallel, a disabled block, or a block of a workflow reached only as a custom block's cannot be allowed. Allowing an Agent sends only its own tool calls: a workflow or custom block it calls stays stubbed. An entry the run never reaches is listed in `sideEffects.unused`." ), mocks: z .record( - z.string(), + z + .string() + .max(MAX_BLOCK_SELECTOR_LENGTH, 'run.mocks keys are at most 256 characters') + .describe('Block selector.'), z .record(z.string(), z.unknown().describe('Output field.')) .describe('Output object that answers the block instead of its handler.') @@ -1731,7 +1742,36 @@ export const v2WorkflowRunSelectionSchema = z.discriminatedUnion('source', [ .meta({ maxProperties: MAX_RUN_MOCKS }) .optional() .describe( - 'Blocks of this workflow (keyed by id, display name or reference key) answered with this output object instead of running, to steer branches or give a stubbed write a realistic result. Requires `dry`. A locked block (or one inside a locked loop or parallel) cannot be mocked. A mock is data: it cannot set a field the run’s execution, trace or billing reads (`cost`, `tokens`, `model`, `providerTiming`, `toolCalls`, `executionData`, `childTraceSpans`, `childWorkflowId`, `childWorkflowSnapshotId`, `childDeploymentVersionId`, or any field starting with `_`). The run records only which blocks were mocked, so a rerun passes the outputs again; its log shows a mocked block’s output like any other block’s.' + 'Blocks answered with this output object instead of running, to steer branches or give a stubbed write a realistic result, keyed like `allowBlocks` entries (a block of this workflow, or `.` of a workflow it calls). Requires `dry`. A locked block (or one inside a locked loop or parallel), a loop or parallel, and a disabled block cannot be mocked; a block of a locked workflow, or of one in a locked folder, returns `423`. A mock is data: it cannot set a field the run’s execution, trace or billing reads (`cost`, `tokens`, `model`, `providerTiming`, `toolCalls`, `executionData`, `childTraceSpans`, `childWorkflowId`, `childWorkflowSnapshotId`, `childDeploymentVersionId`, or any field starting with `_`), nor hold a large-value reference (an object with `__simLargeValueRef`). A field the block does not declare is listed in `sideEffects.undeclaredMockFields`, not refused. The run records only which blocks were mocked, so a rerun passes the outputs again; its log shows a mocked block’s output like any other block’s.' + ), + mocksFrom: z + .object({ + runId: z + .string() + .min(1, 'run.mocksFrom.runId cannot be empty') + .describe( + 'Run of this workflow whose recorded block outputs answer the blocks. An unknown or expired run returns `404`; one still running, or whose log is not written yet, `409`; reading it needs what reading the run does, and a permission group that hides execution data returns `403`.' + ), + blocks: z + .array( + z + .string() + .min(1, 'run.mocksFrom.blocks entries cannot be empty') + .max( + MAX_BLOCK_SELECTOR_LENGTH, + 'run.mocksFrom.blocks entries are at most 256 characters' + ) + ) + .min(1, 'run.mocksFrom.blocks names at least one block') + .max(MAX_RUN_MOCKS) + .describe( + 'Blocks of this workflow only (id, display name or reference key; never a child’s) answered with the output each recorded in that run, redacted as the run shows it. Refused: a block the run did not execute; one inside a loop or parallel, unless that run mocked it; and, when that run was a test run, a block it answered with a placeholder rather than mocking or allowing it. Fields only a block sets (`cost`, `tokens`, `model`, `toolCalls`, child traces and the like, and fields starting with `_`) are left out and listed in `sideEffects.droppedMockFields`; an output holding a large-value reference is refused. Other refusals are those of `mocks`, and a block cannot be named here and in `mocks` both.' + ), + }) + .strict() + .optional() + .describe( + 'Answer blocks with their outputs in an earlier run of this workflow. Requires `dry`. The run records the source run and blocks, so a rerun names them again.' ), }) .strict(), @@ -2044,6 +2084,46 @@ const v2RunSideEffectsSchema = z unchecked: z.number().int().nonnegative().describe('Blocks left out of `unchecked`.'), }) .describe('Entries each list left out once it held 50.'), + unused: z + .array( + z.object({ + workflowId: z.string().describe('Workflow of the block.'), + blockId: z.string().describe('Block id in that workflow.'), + block: z.string().describe('Block display name.'), + override: z + .enum(['allow', 'mock']) + .describe( + 'Whether `run.allowBlocks` or a mock (`run.mocks`, `run.mocksFrom`) named it.' + ), + }) + ) + .describe( + 'Allowed and mocked blocks the run never reached: on a branch it did not take, upstream of a block entry, or in a child it never called.' + ), + undeclaredMockFields: z + .array( + z.object({ + workflowId: z.string().describe('Workflow of the block.'), + blockId: z.string().describe('Block id in that workflow.'), + block: z.string().describe('Block display name.'), + fields: z.array(z.string().describe('Output field.')).describe('Fields not declared.'), + }) + ) + .describe( + 'Passed mocks setting top-level fields their block does not declare as outputs, likely misspelt; a block reading one gets nothing. Agent and Function blocks, whose outputs the model or code decides, are never listed.' + ), + droppedMockFields: z + .array( + z.object({ + workflowId: z.string().describe('Workflow of the block.'), + blockId: z.string().describe('Block id in that workflow.'), + block: z.string().describe('Block display name.'), + fields: z.array(z.string().describe('Output field.')).describe('Fields left out.'), + }) + ) + .describe( + 'Mocks read from a run (`run.mocksFrom`) whose recorded output held fields only a block sets (`cost`, `tokens`, `model`, `toolCalls` and the like), which a mock cannot set and so were left out; a block reading one gets nothing.' + ), }) .meta({ id: 'WorkflowRunSideEffects', @@ -2051,6 +2131,11 @@ const v2RunSideEffectsSchema = z description: 'What a dry run did with each write it reached.', }) +const v2RunDryRunChildBlockSchema = z.object({ + workflowId: z.string().describe('Workflow the run called.'), + blockId: z.string().describe('Block id in that workflow.'), +}) + export const v2RunDryRunSchema = z .object({ allowBlocks: z @@ -2061,6 +2146,27 @@ export const v2RunDryRunSchema = z .describe( 'Blocks the run answered with fixed outputs (`run.mocks`), by id. Only the ids are recorded, so a rerun passes the outputs again.' ), + childAllowBlocks: z + .array(v2RunDryRunChildBlockSchema) + .optional() + .describe( + 'Blocks of workflows it calls whose writes the run sent; a rerun names each as `.`. Absent when none.' + ), + childMockedBlocks: z + .array(v2RunDryRunChildBlockSchema) + .optional() + .describe( + 'Blocks of workflows it calls that the run answered with fixed outputs (`run.mocks`); a rerun passes each output again as `.`. Absent when none.' + ), + mocksFrom: z + .object({ + runId: z.string().describe('Run the outputs were read from.'), + blockIds: z.array(z.string().describe('Block id.')).describe('Blocks answered, by id.'), + }) + .optional() + .describe( + 'Blocks the run answered with their outputs in another run (`run.mocksFrom`), which a rerun reads again. Absent when none.' + ), }) .meta({ id: 'WorkflowDryRun', diff --git a/apps/sim/lib/workflows/application/block-selector.ts b/apps/sim/lib/workflows/application/block-selector.ts new file mode 100644 index 00000000000..ae19e123bbe --- /dev/null +++ b/apps/sim/lib/workflows/application/block-selector.ts @@ -0,0 +1,48 @@ +import { formatQuotedNameList } from '@sim/utils/string' +import type { BlockState } from '@sim/workflow-types/workflow' +import { normalizeWorkflowBlockName } from '@sim/workflow-types/workflow' +import { OrchestrationError } from '@/lib/core/orchestration/types' + +type SavedBlocks = Record + +/** At most this many block names are listed when a block selector matches none. */ +const MAX_LISTED_BLOCKS = 25 + +/** `"name" (id)` for each block of `ids`, at most {@link MAX_LISTED_BLOCKS} of them. */ +export function listBlocks(blocks: SavedBlocks, ids: string[]): string { + return formatQuotedNameList(ids, MAX_LISTED_BLOCKS, (id) => `"${blocks[id]?.name ?? id}" (${id})`) +} + +/** + * The ids of the saved blocks `selector` names: its id, else each block whose display name or + * reference key (the name lowercased, whitespace and dots removed: "Score lead" and `scorelead`) + * matches it. + */ +function matchBlockSelector(blocks: SavedBlocks, selector: string): string[] { + if (Object.hasOwn(blocks, selector)) return [selector] + const key = normalizeWorkflowBlockName(selector) + return Object.keys(blocks).filter((id) => { + const name = blocks[id]?.name + return typeof name === 'string' && normalizeWorkflowBlockName(name) === key + }) +} + +/** + * The id of the one saved block `selector` names ({@link matchBlockSelector}). A selector matching + * no block, or several, is refused with the candidates, so a caller never has to read block ids + * out of the stored workflow. `field` names the wire field. + */ +export function resolveBlockSelector(blocks: SavedBlocks, selector: string, field: string): string { + const matches = matchBlockSelector(blocks, selector) + if (matches.length === 1) return matches[0] + if (matches.length > 1) { + throw new OrchestrationError( + 'validation', + `${field} "${selector}" names ${matches.length} blocks: ${listBlocks(blocks, matches)}. Pass one of their ids.` + ) + } + throw new OrchestrationError( + 'validation', + `${field} "${selector}" is not a block in the current saved workflow. Pass a block's id, name or key: ${listBlocks(blocks, Object.keys(blocks))}.` + ) +} diff --git a/apps/sim/lib/workflows/application/dry-run-overrides.ts b/apps/sim/lib/workflows/application/dry-run-overrides.ts new file mode 100644 index 00000000000..d918b460c8e --- /dev/null +++ b/apps/sim/lib/workflows/application/dry-run-overrides.ts @@ -0,0 +1,611 @@ +import type { WorkflowExecutionPrincipal } from '@sim/auth/principal' +import { isRecordLike } from '@sim/utils/object' +import { + type BlockState, + isWorkflowBlockProtected, + normalizeWorkflowBlockName, +} from '@sim/workflow-types/workflow' +import { OrchestrationError } from '@/lib/core/orchestration/types' +import { MAX_CALL_CHAIN_DEPTH } from '@/lib/execution/call-chain' +import { listBlocks, resolveBlockSelector } from '@/lib/workflows/application/block-selector' +import { requireMutableWorkflow } from '@/lib/workflows/application/mutability' +import { readWorkflowRun } from '@/lib/workflows/application/read-workflow-run' +import { getEffectiveBlockOutputs } from '@/lib/workflows/blocks/outputs' +import { + type DryRunMock, + type DryRunOverride, + overrideKey, + PAUSING_BLOCK_TYPES, + runsAnotherWorkflow, + SELF_DIRECTED_BLOCK_TYPES, + WriteStubPolicy, +} from '@/lib/workflows/dry-run' +import { + isCustomBlockSourceWorkflow, + listActiveWorkflowIdsByIdOrName, + loadWorkflowReadSnapshots, +} from '@/lib/workflows/queries' +import { getWorkflowInvocationTarget } from '@/lib/workflows/streaming/nested-output-options' +import { getBlock } from '@/blocks/registry' +import { BlockType } from '@/executor/constants' +import { isRunControlledOutputField, mockOutputRefusal } from '@/executor/utils/mock-output' +import { TEST_TRIGGER } from '@/stores/logs/filters/types' +import { getToolMetadata } from '@/tools/metadata' + +/** The blocks a manual run asks a dry run to send or answer. */ +export interface DryRunRequest { + /** Answer writes with placeholders and return what each would have sent (`run.dry`). */ + dry?: boolean + /** Blocks, by selector, whose writes a dry run sends for real (`run.allowBlocks`). */ + allowBlocks?: string[] + /** Block selector to the output that answers the block in a dry run (`run.mocks`). */ + mocks?: Record> + /** Blocks answered with their outputs in another run of this workflow (`run.mocksFrom`). */ + mocksFrom?: { runId: string; blocks: string[] } +} + +/** A workflow whose blocks a dry run's overrides may name, as its saved draft holds them. */ +interface OverrideWorkflow { + id: string + name: string + blocks: Record +} + +interface OverrideTarget extends DryRunOverride { + workflow: OverrideWorkflow +} + +/** The workflows reachable through Workflow blocks, as far as the saved drafts say. */ +interface CallGraph { + /** Children called by a fixed id, at any depth, by id. */ + called: Map + /** Whether some Workflow block chooses its child as the run goes, by a reference. */ + choosesAtRunTime: boolean +} + +/** Blocks whose outputs depend on what the model or code returns, so none is undeclared. */ +const DYNAMIC_OUTPUT_BLOCK_TYPES: ReadonlySet = new Set([ + BlockType.AGENT, + BlockType.FUNCTION, +]) + +const CONTAINER_BLOCK_TYPES: ReadonlySet = new Set([BlockType.LOOP, BlockType.PARALLEL]) + +/** Tools a dry run sends whatever the block, as `WriteStubPolicy.decideWrite` does. */ +const ALWAYS_SENT_TOOLS: ReadonlySet = new Set(['function_execute', 'workflow_executor']) + +function overrideTarget(workflow: OverrideWorkflow, blockId: string): OverrideTarget { + return { + workflow, + workflowId: workflow.id, + blockId, + block: workflow.blocks[blockId]?.name ?? blockId, + } +} + +async function loadWorkspaceWorkflows( + workflowIds: string[], + workspaceId: string +): Promise { + if (workflowIds.length === 0) return [] + const snapshots = await loadWorkflowReadSnapshots(workflowIds, workspaceId) + const workflows: OverrideWorkflow[] = [] + for (const { normalizedData, workflowRecord } of snapshots.values()) { + if (!normalizedData) continue + workflows.push({ + id: workflowRecord.id, + name: workflowRecord.name, + blocks: normalizedData.blocks, + }) + } + return workflows +} + +/** The blocks containing `blockId`, innermost first, then the block itself first of all. */ +function blockAndAncestors(blocks: Record, blockId: string): BlockState[] { + const chain: BlockState[] = [] + const seen = new Set() + for (let id: string | undefined = blockId; id && !seen.has(id); id = blocks[id]?.data?.parentId) { + seen.add(id) + const block = blocks[id] + if (block) chain.push(block) + } + return chain +} + +/** + * Resolves a dry run's block selectors to blocks of the run's workflow, or, in the dotted form + * `.` (a workflow id or name, then a block id, name or key), of a workflow it + * calls. A selector without a dot names a block of the run's workflow by id, name or key. A dotted + * one names a block of the run's workflow only by its exact id or display name, since keys drop + * dots, and otherwise a child's: one its Workflow blocks call by a fixed id (at every depth a run + * can reach), matched by id then by name or its key, else, for a child chosen as the run goes, a + * workflow of this workspace by id or exact name. Every workspace lookup the request's selectors + * need is one query, made once; a workflow of another workspace is never found, so a refusal says + * nothing of whether it exists. A selector naming several blocks is refused with them. + */ +class OverrideResolver { + private graph: Promise | undefined + private inWorkspace: Promise | undefined + + constructor( + private readonly root: OverrideWorkflow, + private readonly workspaceId: string, + /** Every selector of the request, so the workspace is asked about all of them at once. */ + private readonly selectors: readonly string[] + ) {} + + async resolve(selector: string, field: string): Promise { + if (!selector.includes('.')) { + return overrideTarget(this.root, resolveBlockSelector(this.root.blocks, selector, field)) + } + const candidates = new Map() + const add = (target: OverrideTarget) => candidates.set(overrideKey(target), target) + for (const [blockId, block] of Object.entries(this.root.blocks)) { + if (blockId === selector || block.name === selector) add(overrideTarget(this.root, blockId)) + } + const namedWorkflows: OverrideWorkflow[] = [] + for (const [workflowName, blockSelector] of dottedSplits(selector)) { + for (const workflow of await this.named(workflowName)) { + namedWorkflows.push(workflow) + const blockKey = normalizeWorkflowBlockName(blockSelector) + for (const [blockId, block] of Object.entries(workflow.blocks)) { + if (blockId === blockSelector || normalizeWorkflowBlockName(block.name) === blockKey) { + add(overrideTarget(workflow, blockId)) + } + } + } + } + const label = `${field} "${selector}"` + const [only, ...others] = candidates.values() + if (only && others.length === 0) { + await this.refuseCustomBlockSource(only, label) + return only + } + if (only) { + throw new OrchestrationError( + 'validation', + `${label} names ${candidates.size} blocks: ${[...candidates.values()] + .map( + (entry) => + `"${entry.workflow.name}"."${entry.block}" (${entry.workflowId}.${entry.blockId})` + ) + .join(', ')}. Pass the workflow id and block id.` + ) + } + const [workflow] = namedWorkflows + if (workflow) { + throw new OrchestrationError( + 'validation', + `${label} names no block of workflow "${workflow.name}" (${workflow.id}). Pass one of its blocks' id, name or key: ${listBlocks(workflow.blocks, Object.keys(workflow.blocks))}.` + ) + } + throw new OrchestrationError( + 'validation', + `${label} is not a block of this workflow, nor . for a workflow of this workspace it can call. This workflow's blocks: ${listBlocks(this.root.blocks, Object.keys(this.root.blocks))}.` + ) + } + + /** The workflows `name` names: a called child by id, else by name or key, else the workspace's. */ + private async named(name: string): Promise { + const { called } = await this.callGraph() + const byId = called.get(name) + if (byId) return [byId] + const key = normalizeWorkflowBlockName(name) + const byName = [...called.values()].filter( + (child) => normalizeWorkflowBlockName(child.name) === key + ) + if (byName.length > 0) return byName + const inWorkspace = await this.workspaceWorkflows() + const chosenById = inWorkspace.filter((workflow) => workflow.id === name) + return chosenById.length > 0 + ? chosenById + : inWorkspace.filter((workflow) => workflow.name === name) + } + + private callGraph(): Promise { + this.graph ??= this.walk() + return this.graph + } + + private async walk(): Promise { + const called = new Map() + let choosesAtRunTime = false + const seen = new Set([this.root.id]) + let frontier = [this.root] + for (let depth = 0; depth < MAX_CALL_CHAIN_DEPTH && frontier.length > 0; depth++) { + const targets = new Set() + for (const workflow of frontier) { + for (const block of Object.values(workflow.blocks)) { + if (block.enabled === false) continue + const target = getWorkflowInvocationTarget(block) + if (target?.includes('<')) choosesAtRunTime = true + else if (target && !seen.has(target)) targets.add(target) + } + } + for (const target of targets) seen.add(target) + frontier = await loadWorkspaceWorkflows([...targets], this.workspaceId) + for (const child of frontier) called.set(child.id, child) + } + return { called, choosesAtRunTime } + } + + /** The workspace's workflows named by any selector's workflow part, by id or exact name. */ + private workspaceWorkflows(): Promise { + this.inWorkspace ??= (async () => { + const names = [ + ...new Set( + this.selectors.flatMap((selector) => dottedSplits(selector).map(([name]) => name)) + ), + ] + const ids = await listActiveWorkflowIdsByIdOrName(this.workspaceId, names) + return loadWorkspaceWorkflows(ids, this.workspaceId) + })() + return this.inWorkspace + } + + /** + * A workflow that publishes a custom block, found only in the workspace, is one this run reaches + * only as that custom block, which a dry run answers whole, unless a Workflow block chooses its + * child as the run goes and so may call it. + */ + private async refuseCustomBlockSource(target: OverrideTarget, label: string): Promise { + if (target.workflow === this.root) return + const { called, choosesAtRunTime } = await this.callGraph() + if (called.has(target.workflowId) || choosesAtRunTime) return + if (!(await isCustomBlockSourceWorkflow(target.workflowId))) return + throw new OrchestrationError( + 'validation', + `${label} names a block of workflow "${target.workflow.name}", which this run reaches only as a custom block; a dry run answers a custom block whole, so its blocks never run.` + ) + } +} + +/** Each way to split a dotted selector into `` and ``, at one of its dots. */ +function dottedSplits(selector: string): Array<[string, string]> { + const splits: Array<[string, string]> = [] + for (let dot = selector.indexOf('.'); dot > 0; dot = selector.indexOf('.', dot + 1)) { + if (dot < selector.length - 1) splits.push([selector.slice(0, dot), selector.slice(dot + 1)]) + } + return splits +} + +/** Refuses a block the run never executes as itself: a disabled one, or a loop or parallel. */ +function refuseUnrunnable(target: OverrideTarget, label: string): void { + const chain = blockAndAncestors(target.workflow.blocks, target.blockId) + if (chain.some((block) => block.enabled === false)) { + throw new OrchestrationError( + 'validation', + `${label} is disabled (or inside a disabled loop or parallel), so the run never executes it.` + ) + } + if (CONTAINER_BLOCK_TYPES.has(target.workflow.blocks[target.blockId].type)) { + throw new OrchestrationError( + 'validation', + `${label} is a loop or parallel, which runs the blocks inside it; name one of those blocks instead.` + ) + } +} + +function refuseUnallowable(target: OverrideTarget, label: string): void { + const blockType = target.workflow.blocks[target.blockId].type + if (PAUSING_BLOCK_TYPES.has(blockType)) { + throw new OrchestrationError( + 'validation', + `${label} is a Human in the loop or Wait block, which a dry run always answers with a placeholder and never pauses on; mock its output with run.mocks to choose it.` + ) + } + if (runsAnotherWorkflow(blockType)) { + throw new OrchestrationError( + 'validation', + `${label} runs another workflow (a Workflow or custom block), whose writes a dry run never sends; allow a block of that workflow as ., or mock this block's output with run.mocks.` + ) + } +} + +/** + * Top-level output fields the block does not declare, which likely misspell one it does; none for + * a block whose outputs the model or code decides, or whose outputs are unknown. + */ +function undeclaredOutputFields(block: BlockState, output: Record): string[] { + if (DYNAMIC_OUTPUT_BLOCK_TYPES.has(block.type)) return [] + const declared = Object.keys( + getEffectiveBlockOutputs(block.type, block.subBlocks, { includeHidden: true }) + ) + if (declared.length === 0) return [] + const known = new Set([ + ...declared, + ...Object.keys(getBlock(block.type)?.errorOutputs ?? {}), + 'error', + ]) + return Object.keys(output).filter((field) => !known.has(field)) +} + +/** + * Whether a test run answered this block with a placeholder unless it allowed or mocked it: a + * block answered whole, one that runs another workflow (whose writes were placeholders too), or + * one whose tool, for the operation it is configured with, is not declared `read`. An Agent's and + * a Function's own output is real, whatever their tool calls returned. + */ +function answeredWithPlaceholder(block: BlockState): boolean { + if ( + PAUSING_BLOCK_TYPES.has(block.type) || + SELF_DIRECTED_BLOCK_TYPES.has(block.type) || + runsAnotherWorkflow(block.type) + ) { + return true + } + if (DYNAMIC_OUTPUT_BLOCK_TYPES.has(block.type)) return false + const tools = getBlock(block.type)?.tools + if (!tools?.access?.length) return false + const params = Object.fromEntries( + Object.entries(block.subBlocks).map(([key, subBlock]) => [key, subBlock.value]) + ) + let toolId: string | undefined + try { + toolId = tools.config?.tool ? tools.config.tool(params) : tools.access[0] + } catch { + return true + } + if (!toolId) return true + return !ALWAYS_SENT_TOOLS.has(toolId) && getToolMetadata(toolId)?.effect !== 'read' +} + +interface RecordedMock { + label: string + blockId: string + output: Record + droppedFields: string[] +} + +/** + * The output each block answered with in `runId`, a run of this workflow, read through the run + * resource, so it is redacted like the run's log and withheld where the caller's permission group + * withholds execution data. Fields only a block's handler may set (its cost, tokens, model, tool + * calls or child traces, and `_` fields) are left out and reported, as `run.mocks` refuses them. + * Refused: a block the run did not execute; one inside a loop or parallel, whose recorded output + * is one iteration's, unless the run mocked it (every iteration answered alike); and, when the + * run was itself a test run, a block it answered with a placeholder rather than mocked or allowed. + */ +async function readRecordedOutputs( + principal: WorkflowExecutionPrincipal, + root: OverrideWorkflow, + mocksFrom: { runId: string; blocks: string[] } +): Promise { + const { runId } = mocksFrom + const selected = mocksFrom.blocks.map((selector) => { + const label = `run.mocksFrom.blocks "${selector}"` + try { + return { label, blockId: resolveBlockSelector(root.blocks, selector, 'run.mocksFrom.blocks') } + } catch (error) { + if (!selector.includes('.')) throw error + throw new OrchestrationError( + 'validation', + `${label} is not a block of this workflow. Only this workflow's blocks can be mocked from a run; pass a child's output with run.mocks as ..` + ) + } + }) + const run = await readWorkflowRun + .execute({ + principal, + input: { + workflowId: root.id, + runId, + includeOutput: false, + selectedOutputs: [...new Set(selected.map((entry) => entry.blockId))], + }, + }) + .catch((error: unknown) => { + if (error instanceof OrchestrationError && error.code === 'not_found') { + throw new OrchestrationError( + 'not_found', + `run.mocksFrom.runId "${runId}" is not a run of this workflow, or its log has expired.` + ) + } + throw error + }) + if (run.status === 'queued' || run.status === 'pending' || run.status === 'running') { + throw new OrchestrationError( + 'conflict', + `run.mocksFrom.runId "${runId}" is still ${run.status}; mock from it once it settles.` + ) + } + const { blockOutputs } = run + if (!blockOutputs) { + if (run.outputsHidden) { + throw new OrchestrationError( + 'forbidden', + `run.mocksFrom.runId "${runId}": your permission group hides runs' execution data, so its block outputs cannot be read.` + ) + } + throw new OrchestrationError( + 'conflict', + `run.mocksFrom.runId "${runId}" has no recorded block outputs yet; mock from a run whose log is written.` + ) + } + const sourceIsTestRun = run.trigger === TEST_TRIGGER + const sourceMocked = new Set([ + ...(run.dryRun?.mockedBlocks ?? []), + ...(run.dryRun?.mocksFrom?.blockIds ?? []), + ]) + const sourceAllowed = new Set(run.dryRun?.allowBlocks ?? []) + return selected.map(({ label, blockId }) => { + const mockedThere = sourceMocked.has(blockId) + if (!mockedThere && blockAndAncestors(root.blocks, blockId).length > 1) { + throw new OrchestrationError( + 'validation', + `${label} is inside a loop or parallel, whose recorded output is one iteration's; pass its output with run.mocks instead.` + ) + } + const output = blockOutputs[blockId] + if (output === undefined) { + throw new OrchestrationError( + 'validation', + mockedThere + ? `${label} was mocked in run "${runId}" but never ran there, so the run recorded no output; pass it again with --mock = (run.mocks).` + : `${label} did not run in run "${runId}", so it recorded no output.` + ) + } + if (!isRecordLike(output)) { + throw new OrchestrationError( + 'validation', + `${label} recorded an output that is not an object in run "${runId}".` + ) + } + if ( + sourceIsTestRun && + !mockedThere && + !sourceAllowed.has(blockId) && + answeredWithPlaceholder(root.blocks[blockId]) + ) { + throw new OrchestrationError( + 'validation', + `${label}: run "${runId}" is a test run, which answered this block with a placeholder instead of running it; mock from a run that ran it, or pass its output with run.mocks.` + ) + } + const kept = Object.entries(output).filter(([field]) => !isRunControlledOutputField(field)) + return { + label, + blockId, + output: Object.fromEntries(kept), + droppedFields: Object.keys(output).filter(isRunControlledOutputField), + } + }) +} + +/** + * The dry run a manual run asked for: its allowed and mocked blocks, each a block of the run's + * workflow or, as `.`, of a workflow it calls ({@link OverrideResolver}), so it + * applies wherever that workflow runs. A dry run is logged under the `test` trigger, never as a + * manual run, and returns its side effects with the result it waits for, so it cannot stream or + * detach. Mocks need a dry run, so a fixed output reaches a real write only through a block the + * caller allows. A mock is data ({@link mockOutputRefusal}), and never replaces a locked block + * (refused as invalid), or a block of a locked workflow or folder (refused as locked, like any + * change to one), whose configured behaviour only an admin may change. A block that never runs + * as itself (a disabled one, a loop or a parallel) is refused, and a mock setting a field its + * block does not declare is reported, not refused. + */ +export async function resolveRunOverrides(params: { + principal: WorkflowExecutionPrincipal + workspaceId: string + workflow: { id: string; name: string } + blocks: Record + mode: 'sync' | 'stream' | 'sync-result-stream' + detachable: boolean | undefined + request: DryRunRequest +}) { + const { request } = params + if (!request.dry) { + if (request.allowBlocks?.length) { + throw new OrchestrationError('validation', 'run.allowBlocks requires run.dry') + } + if ((request.mocks && Object.keys(request.mocks).length > 0) || request.mocksFrom) { + throw new OrchestrationError( + 'validation', + `${request.mocksFrom ? 'run.mocksFrom' : 'run.mocks'} requires run.dry: a mocked block must never steer a run that sends its writes` + ) + } + return { triggerType: 'manual' as const } + } + if (params.mode === 'stream' || params.detachable) { + throw new OrchestrationError( + 'validation', + 'run.dry returns its side effects with the run result, so it cannot be combined with stream or waitTimeoutSeconds' + ) + } + const root: OverrideWorkflow = { ...params.workflow, blocks: params.blocks } + const passedMocks = Object.entries(request.mocks ?? {}) + const resolver = new OverrideResolver(root, params.workspaceId, [ + ...(request.allowBlocks ?? []), + ...passedMocks.map(([selector]) => selector), + ]) + + const allowBlocks: DryRunOverride[] = [] + for (const selector of request.allowBlocks ?? []) { + const label = `run.allowBlocks "${selector}"` + const target = await resolver.resolve(selector, 'run.allowBlocks') + refuseUnrunnable(target, label) + refuseUnallowable(target, label) + allowBlocks.push({ + workflowId: target.workflowId, + blockId: target.blockId, + block: target.block, + }) + } + + const mocks: Array<{ + label: string + target: OverrideTarget + output: Record + recorded?: { runId: string; droppedFields: string[] } + }> = [] + for (const [selector, output] of passedMocks) { + const target = await resolver.resolve(selector, 'run.mocks') + mocks.push({ label: `run.mocks "${selector}"`, target, output }) + } + if (request.mocksFrom) { + const { runId } = request.mocksFrom + for (const entry of await readRecordedOutputs(params.principal, root, request.mocksFrom)) { + mocks.push({ + label: entry.label, + target: overrideTarget(root, entry.blockId), + output: entry.output, + recorded: { runId, droppedFields: entry.droppedFields }, + }) + } + } + + const lockChecks = new Map>() + const labelsByKey = new Map() + const blockMocks: DryRunMock[] = [] + for (const { label, target, output, recorded } of mocks) { + const key = overrideKey(target) + const earlier = labelsByKey.get(key) + if (earlier) { + throw new OrchestrationError( + 'validation', + `${earlier} and ${label} both name block "${target.block}" (${target.blockId}); mock it once.` + ) + } + labelsByKey.set(key, label) + refuseUnrunnable(target, label) + if (isWorkflowBlockProtected(target.blockId, target.workflow.blocks)) { + throw new OrchestrationError( + 'validation', + `${label} is a locked block (or inside a locked loop or parallel); its configured behaviour cannot be replaced.` + ) + } + let lockCheck = lockChecks.get(target.workflowId) + if (!lockCheck) { + lockCheck = requireMutableWorkflow(target.workflowId) + lockChecks.set(target.workflowId, lockCheck) + } + await lockCheck.catch((error: unknown) => { + if (error instanceof OrchestrationError && error.code === 'locked') { + throw new OrchestrationError( + 'locked', + `${label} is a block of workflow "${target.workflow.name}" (${error.message}); its configured behaviour cannot be replaced.` + ) + } + throw error + }) + const refusal = mockOutputRefusal(label, output) + if (refusal) throw new OrchestrationError('validation', refusal) + blockMocks.push({ + workflowId: target.workflowId, + blockId: target.blockId, + block: target.block, + output, + ...(recorded ? { sourceRunId: recorded.runId } : {}), + undeclaredFields: recorded + ? [] + : undeclaredOutputFields(target.workflow.blocks[target.blockId], output), + droppedFields: recorded?.droppedFields ?? [], + }) + } + + return { + triggerType: TEST_TRIGGER, + sideEffectPolicy: new WriteStubPolicy({ workflowId: root.id, allowBlocks, blockMocks }), + } +} diff --git a/apps/sim/lib/workflows/application/dry-run.integration.ts b/apps/sim/lib/workflows/application/dry-run.integration.ts index df66777d5fb..4a8764278d8 100644 --- a/apps/sim/lib/workflows/application/dry-run.integration.ts +++ b/apps/sim/lib/workflows/application/dry-run.integration.ts @@ -28,6 +28,7 @@ import { organization, pausedExecutions, permissions, + resumeQueue, user, userStats, userTableDefinitions, @@ -53,7 +54,7 @@ import { and, eq, inArray } from 'drizzle-orm' import { NextRequest } from 'next/server' import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest' -const { subscriberRuns, session } = vi.hoisted(() => { +const { subscriberRuns, session, viewer } = vi.hoisted(() => { /** Custom blocks are a self-hosted opt-in, read when the config module loads. */ process.env.CUSTOM_BLOCKS_ENABLED = 'true' /** Agents keep durable turn history (rich history and the memory retrieval tool). */ @@ -69,6 +70,22 @@ const { subscriberRuns, session } = vi.hoisted(() => { session: { id: string } }, }, + /** Whether the viewer's permission group hides execution data; off unless a test hides it. */ + viewer: { hidesTraceSpans: false }, + } +}) + +/** A permission group hiding `logs.trace_spans`, applied when a test sets `viewer.hidesTraceSpans`. */ +vi.mock('@/lib/logs/projection', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + resolveLogFieldProjection: async ( + ...args: Parameters + ) => + viewer.hidesTraceSpans + ? { hideTraceSpans: true, hideCostInfo: false } + : actual.resolveLogFieldProjection(...args), } }) @@ -111,6 +128,8 @@ import type { PausePoint } from '@/executor/types' const ownerId = generateId() const organizationId = generateId() const workspaceId = generateId() +/** A second workspace of the same owner, whose workflows a dry run never names. */ +const otherWorkspaceId = generateId() const SECRET = `dry-secret-${generateId()}` const UNREFERENCED_SECRET = `unreferenced-${generateId()}` const SECRET_URL = `http://dry-run.invalid/hook/${generateId()}` @@ -181,14 +200,18 @@ function condition(name: string, expression: string): BlockState { return gate } -/** Saves `state` as the draft of a new workflow in the fixture workspace. */ -async function saveWorkflow(state: WorkflowState, name = `Dry run ${generateId()}`) { +/** Saves `state` as the draft of a new workflow, in the fixture workspace unless told otherwise. */ +async function saveWorkflow( + state: WorkflowState, + name = `Dry run ${generateId()}`, + inWorkspaceId = workspaceId +) { const id = generateId() const now = new Date() await db.insert(workflow).values({ id, userId: ownerId, - workspaceId, + workspaceId: inWorkspaceId, name, lastSynced: now, createdAt: now, @@ -420,6 +443,13 @@ beforeAll(async () => { billedAccountUserId: ownerId, organizationId, }) + await insertWorkspaceFixture(db, { + id: otherWorkspaceId, + name: 'Dry run other workspace', + ownerId, + billedAccountUserId: ownerId, + organizationId, + }) await db.insert(permissions).values({ id: generateId(), userId: ownerId, @@ -450,6 +480,7 @@ beforeAll(async () => { afterEach(() => { vi.unstubAllGlobals() session.current = null + viewer.hidesTraceSpans = false }) afterAll(async () => { @@ -460,7 +491,7 @@ afterAll(async () => { await db .delete(workflowExecutionSnapshots) .where(inArray(workflowExecutionSnapshots.workflowId, workflowIds)) - await deleteWorkspaceFixture(db, eq(workspace.id, workspaceId)) + await deleteWorkspaceFixture(db, inArray(workspace.id, [workspaceId, otherWorkspaceId])) await db.delete(organization).where(eq(organization.id, organizationId)) await db.delete(user).where(eq(user.id, ownerId)) await closeRedisConnection() @@ -1618,6 +1649,25 @@ describe('a dry run’s mocks', () => { expect(await tableRows(tableId)).toEqual([]) }) + it('cannot hold a large-value reference, which would read a value the run was never granted', async () => { + const { parentId } = await parentFixture() + const ref = { + __simLargeValueRef: true, + version: 1, + id: 'lv_abcdefghijkl', + kind: 'array', + size: 1, + } + + await expect( + run(parentId, { dry: true, mocks: { lookup: { rows: [], page: { rows: ref } } } }) + ).rejects.toMatchObject({ + ...validationError, + message: expect.stringContaining('holds a large-value reference'), + }) + expect(await logTriggers(parentId)).toEqual([]) + }) + it('cannot replace a locked block', async () => { const tableId = await createTable() const lookup = queryLeads('lookup', tableId) @@ -1969,3 +2019,504 @@ return created.id.toString()` ]) }) }) + +/** Start → a Workflow block calling `childId`. */ +function callerOf(childId: string) { + return graph( + [block('start', 'start_trigger'), block('call', 'workflow', { workflowId: childId })], + [['start', 'call']] + ).state +} + +/** Start → lookup (read) → save, a table write whose note holds `lookup`'s total count. */ +function lookupThenSave(tableId: string, email: string) { + return graph( + [ + block('start', 'start_trigger'), + queryLeads('lookup', tableId), + block('save', 'table', { + operation: 'upsert_row', + tableSelector: tableId, + data: JSON.stringify({ email, note: 'count ' }), + }), + ], + [ + ['start', 'lookup'], + ['lookup', 'save'], + ] + ) +} + +describe('a dry run’s overrides of a child workflow', () => { + it('sends a child block’s writes when named ., by name or id, and records it', async () => { + const tableId = await createTable() + const childName = `Child ${generateId()}` + const child = lookupThenSave(tableId, 'child@b.co') + const childId = await saveWorkflow(child.state, childName) + const parentId = await saveWorkflow(callerOf(childId)) + + const byName = await run(parentId, { dry: true, allowBlocks: [`${childName}.save`] }) + + expect(byName.status, JSON.stringify(byName.error)).toBe('completed') + expect(await tableRows(tableId)).toEqual([expect.stringContaining('child@b.co')]) + expect(byName.sideEffects?.allowed).toEqual([ + { workflowId: childId, blockId: child.idOf('save'), block: 'save', tool: 'table_upsert_row' }, + ]) + expect(byName.sideEffects?.unused).toEqual([]) + const recorded = { + allowBlocks: [], + mockedBlocks: [], + childAllowBlocks: [{ workflowId: childId, blockId: child.idOf('save') }], + } + expect(byName.dryRun).toEqual(recorded) + + const byId = await run(parentId, { + dry: true, + allowBlocks: [`${childId}.${child.idOf('save')}`], + }) + expect(byId.sideEffects?.allowed.map((entry) => entry.blockId)).toEqual([child.idOf('save')]) + expect(byId.dryRun).toEqual(recorded) + + const doubleDot = await run(parentId, { dry: true, allowBlocks: [`${childName}..save`] }) + expect(doubleDot.dryRun).toEqual(recorded) + }) + + it('answers a grandchild’s block with a mock, at whatever depth it runs', async () => { + const tableId = await createTable() + const grandchildName = `Grandchild ${generateId()}` + const grandchild = lookupThenSave(tableId, 'grand@b.co') + const grandchildId = await saveWorkflow(grandchild.state, grandchildName) + const childId = await saveWorkflow(callerOf(grandchildId)) + const parentId = await saveWorkflow(callerOf(childId)) + + const result = await run(parentId, { + dry: true, + mocks: { [`${grandchildName}.lookup`]: { rows: [], rowCount: 0, totalCount: 99 } }, + }) + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + const [save] = result.sideEffects?.stubbed ?? [] + expect(save).toMatchObject({ workflowId: grandchildId, block: 'save' }) + expect(save.request).toMatchObject({ data: { email: 'grand@b.co', note: 'count 99' } }) + expect(result.dryRun).toEqual({ + allowBlocks: [], + mockedBlocks: [], + childMockedBlocks: [{ workflowId: grandchildId, blockId: grandchild.idOf('lookup') }], + }) + expect(await tableRows(tableId)).toEqual([]) + }) + + it('cannot replace a child’s locked block, or any block of a locked child workflow', async () => { + const tableId = await createTable() + const lockedBlock = lookupThenSave(tableId, 'a@b.co') + lockedBlock.state.blocks[lockedBlock.idOf('lookup')].locked = true + const childId = await saveWorkflow(lockedBlock.state) + const lockedWorkflowId = await saveWorkflow(lookupThenSave(tableId, 'b@b.co').state) + await db.update(workflow).set({ locked: true }).where(eq(workflow.id, lockedWorkflowId)) + const parentId = await saveWorkflow( + graph( + [ + block('start', 'start_trigger'), + block('first', 'workflow', { workflowId: childId }), + block('second', 'workflow', { workflowId: lockedWorkflowId }), + ], + [ + ['start', 'first'], + ['first', 'second'], + ] + ).state + ) + const mock = { rows: [], rowCount: 0, totalCount: 99 } + + await expect( + run(parentId, { dry: true, mocks: { [`${childId}.lookup`]: mock } }) + ).rejects.toMatchObject({ + ...validationError, + message: expect.stringContaining('locked block'), + }) + await expect( + run(parentId, { dry: true, mocks: { [`${lockedWorkflowId}.lookup`]: mock } }) + ).rejects.toMatchObject({ + code: 'locked', + message: expect.stringContaining('Workflow is locked'), + }) + expect(await logTriggers(parentId)).toEqual([]) + }) + + it('never names a workflow of another workspace, saying no more than of one that does not exist', async () => { + const tableId = await createTable() + const elsewhere = lookupThenSave(tableId, 'x@b.co') + const elsewhereId = await saveWorkflow( + elsewhere.state, + `Elsewhere ${generateId()}`, + otherWorkspaceId + ) + const parentId = await saveWorkflow(callerOf(elsewhereId)) + const missingId = generateId() + + const refusal = async (selector: string) => + run(parentId, { dry: true, allowBlocks: [selector] }).then( + () => 'ran', + (error: OrchestrationError) => { + expect(error.code).toBe('validation') + return error.message.replace(selector, '') + } + ) + + const otherWorkspace = await refusal(`${elsewhereId}.save`) + expect(otherWorkspace).toEqual(await refusal(`${missingId}.save`)) + expect(otherWorkspace).not.toContain(elsewhereId) + expect(await tableRows(tableId)).toEqual([]) + }) + + it('refuses a block that never runs as itself: a loop, a parallel, a disabled block', async () => { + const tableId = await createTable() + const repeat = block('repeat', 'loop') + repeat.data = { loopType: 'for', count: 2 } + const fanOut = block('fanout', 'parallel') + fanOut.data = { parallelType: 'count', count: 2 } + const off = upsertLead('off', tableId, 'a@b.co') + off.enabled = false + const outer = block('outer', 'loop') + outer.data = { loopType: 'for', count: 2 } + outer.enabled = false + const inner = block('inner', 'loop') + inner.data = { loopType: 'for', count: 2, parentId: outer.id, extent: 'parent' } + const deep = upsertLead('deep', tableId, 'd@b.co') + deep.data = { parentId: inner.id, extent: 'parent' } + const workflowId = await saveWorkflow( + graph( + [block('start', 'start_trigger'), repeat, fanOut, off, outer, inner, deep], + [['start', 'repeat']] + ).state + ) + + for (const selector of ['repeat', 'fanout']) { + await expect(run(workflowId, { dry: true, allowBlocks: [selector] })).rejects.toMatchObject({ + ...validationError, + message: expect.stringContaining('is a loop or parallel'), + }) + await expect( + run(workflowId, { dry: true, mocks: { [selector]: { results: [] } } }) + ).rejects.toMatchObject({ + ...validationError, + message: expect.stringContaining('is a loop or parallel'), + }) + } + for (const selector of ['off', 'deep']) { + await expect(run(workflowId, { dry: true, allowBlocks: [selector] })).rejects.toMatchObject({ + ...validationError, + message: expect.stringContaining('is disabled'), + }) + } + expect(await logTriggers(workflowId)).toEqual([]) + }) + + it('reports allowed and mocked blocks the run never reached, and mock fields a block does not declare', async () => { + const tableId = await createTable() + const gate = condition('gate', 'false') + const fixture = graph( + [ + block('start', 'start_trigger'), + queryLeads('lookup', tableId), + gate, + upsertLead('save', tableId, 'a@b.co'), + queryLeads('recheck', tableId), + ], + [ + ['start', 'lookup'], + ['lookup', 'gate'], + ['gate', 'save', `condition-${gate.id}-if`], + ['gate', 'recheck', `condition-${gate.id}-if`], + ] + ) + const workflowId = await saveWorkflow(fixture.state) + + const result = await run(workflowId, { + dry: true, + allowBlocks: ['save'], + mocks: { + lookup: { rows: [], totalCuont: 3 }, + recheck: { rows: [], totalCount: 0 }, + }, + }) + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + expect(result.sideEffects?.unused).toEqual([ + { workflowId, blockId: fixture.idOf('save'), block: 'save', override: 'allow' }, + { workflowId, blockId: fixture.idOf('recheck'), block: 'recheck', override: 'mock' }, + ]) + expect(result.sideEffects?.undeclaredMockFields).toEqual([ + { workflowId, blockId: fixture.idOf('lookup'), block: 'lookup', fields: ['totalCuont'] }, + ]) + }) +}) + +describe('a dry run’s mocks from an earlier run', () => { + it('answers a block with the output it recorded, without what only its handler sets', async () => { + const fixture = graph( + [block('start', 'start_trigger'), agent('assistant', {})], + [['start', 'assistant']] + ) + const workflowId = await saveWorkflow(fixture.state) + const source = await runWithModel(workflowId, 0) + expect(source.status, JSON.stringify(source.error)).toBe('completed') + model.requests = [] + + const replayed = await run(workflowId, { + dry: true, + mocksFrom: { runId: source.executionId, blocks: ['assistant'] }, + selectedOutputs: ['assistant'], + }) + + expect(replayed.status, JSON.stringify(replayed.error)).toBe('completed') + expect(model.requests).toEqual([]) + const output = toRecord(replayed.blockOutputs?.assistant) + expect(output.content).toBe('Done') + for (const field of ['cost', 'tokens', 'model', 'providerTiming']) { + expect(output).not.toHaveProperty(field) + } + expect(replayed.dryRun).toEqual({ + allowBlocks: [], + mockedBlocks: [], + mocksFrom: { runId: source.executionId, blockIds: [fixture.idOf('assistant')] }, + }) + expect(replayed.sideEffects?.unused).toEqual([]) + expect(replayed.sideEffects?.droppedMockFields).toEqual([ + { + workflowId, + blockId: fixture.idOf('assistant'), + block: 'assistant', + fields: expect.arrayContaining(['model', 'tokens', 'cost']), + }, + ]) + }) + + it('refuses a block the earlier run did not execute, and a run that is not this workflow’s', async () => { + const tableId = await createTable() + const gate = condition('gate', 'false') + const workflowId = await saveWorkflow( + graph( + [ + block('start', 'start_trigger'), + queryLeads('lookup', tableId), + gate, + upsertLead('save', tableId, 'a@b.co'), + ], + [ + ['start', 'lookup'], + ['lookup', 'gate'], + ['gate', 'save', `condition-${gate.id}-if`], + ] + ).state + ) + const source = await run(workflowId, { dry: true }) + expect(source.status, JSON.stringify(source.error)).toBe('completed') + const otherRun = await run(await saveWorkflow(lookupThenSave(tableId, 'b@b.co').state), { + dry: true, + }) + + await expect( + run(workflowId, { dry: true, mocksFrom: { runId: source.executionId, blocks: ['save'] } }) + ).rejects.toMatchObject({ ...validationError, message: expect.stringContaining('did not run') }) + await expect( + run(workflowId, { dry: true, mocksFrom: { runId: otherRun.executionId, blocks: ['lookup'] } }) + ).rejects.toMatchObject({ code: 'not_found' }) + await expect( + run(workflowId, { mocksFrom: { runId: source.executionId, blocks: ['lookup'] } }) + ).rejects.toMatchObject({ + ...validationError, + message: expect.stringContaining('requires run.dry'), + }) + }) + + it('cannot be named twice, by a mock and by the earlier run', async () => { + const tableId = await createTable() + const workflowId = await saveWorkflow(lookupThenSave(tableId, 'a@b.co').state) + const source = await run(workflowId, { dry: true }) + + await expect( + run(workflowId, { + dry: true, + mocks: { lookup: { rows: [] } }, + mocksFrom: { runId: source.executionId, blocks: ['Lookup'] }, + }) + ).rejects.toMatchObject({ + ...validationError, + message: expect.stringContaining('run.mocks "lookup" and run.mocksFrom.blocks "Lookup"'), + }) + }) +}) + +/** POSTs a run to the v2 execute route as the fixture API key, answering its status and body. */ +async function postRun(workflowId: string, runSelection: Record) { + const response = await v2Execute( + new NextRequest(`http://localhost:3000/api/v2/workflows/${workflowId}/execute`, { + method: 'POST', + headers: { + 'content-type': 'application/json', + 'x-api-key': API_KEY, + 'x-forwarded-for': '127.0.0.1', + }, + body: JSON.stringify({ input: {}, run: runSelection }), + }), + { params: Promise.resolve({ workflowId }) } + ) + return { status: response.status, body: (await response.json()) as Record } +} + +describe('a dry run’s block selectors', () => { + it('read a dotted selector as . unless a block of this workflow is named so exactly', async () => { + const tableId = await createTable() + const childName = `Slack ${generateId()}` + const child = graph( + [block('start', 'start_trigger'), upsertLead('Send', tableId, 'child@b.co')], + [['start', 'Send']] + ) + const childId = await saveWorkflow(child.state, childName) + const parent = graph( + [ + block('start', 'start_trigger'), + upsertLead(`${childName} Send`, tableId, 'parent@b.co'), + block('call', 'workflow', { workflowId: childId }), + ], + [ + ['start', `${childName} Send`], + [`${childName} Send`, 'call'], + ] + ) + const parentId = await saveWorkflow(parent.state) + + const result = await run(parentId, { dry: true, allowBlocks: [`${childName}.Send`] }) + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + expect(result.sideEffects?.allowed.map((entry) => [entry.workflowId, entry.blockId])).toEqual([ + [childId, child.idOf('Send')], + ]) + expect(await tableRows(tableId)).toEqual([expect.stringContaining('child@b.co')]) + }) + + it('are at most 256 characters, so a selector cannot fan out into thousands of lookups', async () => { + const { parentId } = await parentFixture() + const long = `${'a.'.repeat(128)}save` + + for (const selection of [ + { allowBlocks: [long] }, + { mocks: { [long]: { rows: [] } } }, + { mocksFrom: { runId: generateId(), blocks: [long] } }, + ]) { + const { status, body } = await postRun(parentId, { + source: 'manual', + dry: true, + ...selection, + }) + expect(status, JSON.stringify(body)).toBe(400) + expect(JSON.stringify(body)).toContain('at most 256 characters') + } + expect(await logTriggers(parentId)).toEqual([]) + }) +}) + +describe('a dry run’s mocks from an earlier run, read as that run shows them', () => { + it('replay a block’s output redacted, never the run secret it resolved', async () => { + const workflowId = await saveWorkflow( + graph( + [ + block('start', 'start_trigger'), + block('reveal', 'function', { + language: 'javascript', + code: 'return { key: "{{DRY_SECRET}}" }', + }), + ], + [['start', 'reveal']] + ).state + ) + const source = await run(workflowId, { dry: true }) + expect(source.status, JSON.stringify(source.error)).toBe('completed') + + const replayed = await run(workflowId, { + dry: true, + mocksFrom: { runId: source.executionId, blocks: ['reveal'] }, + selectedOutputs: ['reveal'], + }) + + expect(replayed.status, JSON.stringify(replayed.error)).toBe('completed') + expect(JSON.stringify(replayed.blockOutputs?.reveal)).toContain('key') + expect(JSON.stringify(replayed.blockOutputs)).not.toContain(SECRET) + }) + + it('refuse a block a test run answered with a placeholder, but read one it mocked', async () => { + const tableId = await createTable() + const workflowId = await saveWorkflow(lookupThenSave(tableId, 'a@b.co').state) + const source = await run(workflowId, { + dry: true, + mocks: { lookup: { rows: [], rowCount: 0, totalCount: 7 } }, + }) + expect(source.status, JSON.stringify(source.error)).toBe('completed') + + await expect( + run(workflowId, { dry: true, mocksFrom: { runId: source.executionId, blocks: ['save'] } }) + ).rejects.toMatchObject({ + ...validationError, + message: expect.stringContaining('answered this block with a placeholder'), + }) + const replayed = await run(workflowId, { + dry: true, + mocksFrom: { runId: source.executionId, blocks: ['lookup'] }, + }) + expect(replayed.status, JSON.stringify(replayed.error)).toBe('completed') + expect(replayed.sideEffects?.stubbed[0]?.request).toMatchObject({ data: { note: 'count 7' } }) + }) + + it('are refused while the run is running, when its outputs are hidden, and before it has any', async () => { + const tableId = await createTable() + const workflowId = await saveWorkflow(lookupThenSave(tableId, 'a@b.co').state) + const source = await run(workflowId, { dry: true }) + const mocksFrom = (runId: string) => ({ + dry: true, + mocksFrom: { runId, blocks: ['lookup'] }, + }) + + viewer.hidesTraceSpans = true + await expect(run(workflowId, mocksFrom(source.executionId))).rejects.toMatchObject({ + code: 'forbidden', + message: expect.stringContaining('permission group'), + }) + viewer.hidesTraceSpans = false + + const pausedId = generateId() + const attemptId = generateId() + await db.insert(pausedExecutions).values({ + id: pausedId, + workflowId, + executionId: source.executionId, + executionSnapshot: {}, + pausePoints: [], + totalPauseCount: 1, + status: 'resumed', + }) + await db.insert(resumeQueue).values({ + id: generateId(), + pausedExecutionId: pausedId, + parentExecutionId: source.executionId, + newExecutionId: attemptId, + contextId: 'context', + status: 'failed', + completedAt: new Date(), + failureReason: 'Resume execution failed', + }) + await expect(run(workflowId, mocksFrom(attemptId))).rejects.toMatchObject({ + code: 'conflict', + message: expect.stringContaining('no recorded block outputs yet'), + }) + + await db + .update(workflowExecutionLogs) + .set({ status: 'running' }) + .where(eq(workflowExecutionLogs.executionId, source.executionId)) + await expect(run(workflowId, mocksFrom(source.executionId))).rejects.toMatchObject({ + code: 'conflict', + message: expect.stringContaining('is still running'), + }) + }) +}) diff --git a/apps/sim/lib/workflows/application/execute-manual-workflow.ts b/apps/sim/lib/workflows/application/execute-manual-workflow.ts index 95a6a795f77..c1eaaa1a194 100644 --- a/apps/sim/lib/workflows/application/execute-manual-workflow.ts +++ b/apps/sim/lib/workflows/application/execute-manual-workflow.ts @@ -1,17 +1,19 @@ import { requirePrincipalSubjectUserId, type WorkflowExecutionPrincipal } from '@sim/auth/principal' -import { formatQuotedNameList } from '@sim/utils/string' import { mergeSubblockStateWithValues } from '@sim/workflow-persistence/subblocks' -import { isWorkflowBlockProtected, normalizeWorkflowBlockName } from '@sim/workflow-types/workflow' import { OrchestrationError } from '@/lib/core/orchestration/types' import { inlinesRunFiles, withholdUnadmittedInlineFiles, } from '@/lib/workflows/application/admit-run-files' import { defineAuthorizedWorkflowUseCase } from '@/lib/workflows/application/authorized-workflow-use-case' +import { resolveBlockSelector } from '@/lib/workflows/application/block-selector' import { resolveActiveWorkflowApplicationContext } from '@/lib/workflows/application/context' +import { + type DryRunRequest, + resolveRunOverrides, +} from '@/lib/workflows/application/dry-run-overrides' import type { ExecuteWorkflowInput } from '@/lib/workflows/application/execute-workflow' import { workflowOperations } from '@/lib/workflows/application/operations' -import { PAUSING_BLOCK_TYPES, runsAnotherWorkflow, WriteStubPolicy } from '@/lib/workflows/dry-run' import { type ExecuteWorkflowServiceResult, executeWorkflowService, @@ -25,19 +27,11 @@ import { resolveTriggerRunOptions, validateTriggerInput, } from '@/lib/workflows/triggers/run-options' -import { mockOutputRefusal } from '@/executor/utils/mock-output' -import { TEST_TRIGGER } from '@/stores/logs/filters/types' -interface ManualExecutionInput extends Omit { +interface ManualExecutionInput extends Omit, DryRunRequest { input?: unknown mode: 'sync' | 'stream' | 'sync-result-stream' stopAfterBlockId?: string - /** Answer writes with placeholders and return what each would have sent (`run.dry`). */ - dry?: boolean - /** Blocks, by selector, whose writes a dry run sends for real (`run.allowBlocks`). */ - allowBlocks?: string[] - /** Block selector to the output that answers the block in a dry run (`run.mocks`). */ - mocks?: Record> } export interface ExecuteManualWorkflowInput extends ManualExecutionInput { @@ -67,44 +61,6 @@ async function loadManualState(workflowId: string) { type ManualWorkflowState = Awaited> -/** At most this many block names are listed when a block selector matches none. */ -const MAX_LISTED_BLOCKS = 25 - -/** `"name" (id)` for each block of `ids`, at most {@link MAX_LISTED_BLOCKS} of them. */ -function listBlocks(state: ManualWorkflowState, ids: string[]): string { - return formatQuotedNameList( - ids, - MAX_LISTED_BLOCKS, - (id) => `"${state.blocks[id]?.name ?? id}" (${id})` - ) -} - -/** - * The id of the saved block `selector` names: its id, else the one block whose display name or - * reference key (the name lowercased, whitespace and dots removed: "Score lead" and `scorelead`) - * matches it. A selector matching no block, or several, is refused with the candidates, so a - * caller never has to read block ids out of the stored workflow. `field` names the wire field. - */ -function resolveBlockSelector(state: ManualWorkflowState, selector: string, field: string): string { - if (Object.hasOwn(state.blocks, selector)) return selector - const key = normalizeWorkflowBlockName(selector) - const matches = Object.keys(state.blocks).filter((id) => { - const name = state.blocks[id]?.name - return typeof name === 'string' && normalizeWorkflowBlockName(name) === key - }) - if (matches.length === 1) return matches[0] - if (matches.length > 1) { - throw new OrchestrationError( - 'validation', - `${field} "${selector}" names ${matches.length} blocks: ${listBlocks(state, matches)}. Pass one of their ids.` - ) - } - throw new OrchestrationError( - 'validation', - `${field} "${selector}" is not a block in the current saved workflow. Pass a block's id, name or key: ${listBlocks(state, Object.keys(state.blocks))}.` - ) -} - /** Blocks a run entering at `entryBlockId` can reach; the executor skips disabled blocks. */ function reachableFrom(state: ManualWorkflowState, entryBlockId: string): Set { const targetsBySource = new Map() @@ -140,7 +96,7 @@ function resolveStopAfterBlock( entryBlockId: string ): string | undefined { if (selector === undefined) return undefined - const blockId = resolveBlockSelector(state, selector, 'run.stopAfterBlockId') + const blockId = resolveBlockSelector(state.blocks, selector, 'run.stopAfterBlockId') const block = state.blocks[blockId] if (block.enabled === false) { throw new OrchestrationError( @@ -163,82 +119,11 @@ function resolveStopAfterBlock( return blockId } -/** - * The dry run a manual run asked for, its allowed and mocked blocks resolved like - * {@link resolveBlockSelector}. A dry run is logged under the `test` trigger, never as a manual - * run, and returns its side effects with the result it waits for, so it cannot stream or detach. - * Mocks need a dry run, so a fixed output reaches a real write only through a block the caller - * allows. A mock is data ({@link mockOutputRefusal}), and never replaces a locked block, whose - * configured behaviour only an admin may change. - */ -function resolveRunOverrides( - state: ManualWorkflowState, - input: ManualExecutionInput, - workflowId: string -) { - if (!input.dry) { - if (input.allowBlocks?.length) { - throw new OrchestrationError('validation', 'run.allowBlocks requires run.dry') - } - if (input.mocks && Object.keys(input.mocks).length > 0) { - throw new OrchestrationError( - 'validation', - 'run.mocks requires run.dry: a mocked block must never steer a run that sends its writes' - ) - } - return { triggerType: 'manual' as const } - } - if (input.mode === 'stream' || input.detachable) { - throw new OrchestrationError( - 'validation', - 'run.dry returns its side effects with the run result, so it cannot be combined with stream or waitTimeoutSeconds' - ) - } - const allowBlockIds = new Set() - for (const selector of input.allowBlocks ?? []) { - const blockId = resolveBlockSelector(state, selector, 'run.allowBlocks') - const blockType = state.blocks[blockId].type - if (PAUSING_BLOCK_TYPES.has(blockType)) { - throw new OrchestrationError( - 'validation', - `run.allowBlocks "${selector}" is a Human in the loop or Wait block, which a dry run always answers with a placeholder and never pauses on; mock its output with run.mocks to choose it.` - ) - } - if (runsAnotherWorkflow(blockType)) { - throw new OrchestrationError( - 'validation', - `run.allowBlocks "${selector}" runs another workflow (a Workflow or custom block), whose writes a dry run never sends; mock its output with run.mocks instead.` - ) - } - allowBlockIds.add(blockId) - } - const blockMocks = new Map>() - for (const [selector, output] of Object.entries(input.mocks ?? {})) { - const blockId = resolveBlockSelector(state, selector, 'run.mocks') - if (blockMocks.has(blockId)) { - throw new OrchestrationError('validation', `run.mocks names block "${blockId}" twice`) - } - if (isWorkflowBlockProtected(blockId, state.blocks)) { - throw new OrchestrationError( - 'validation', - `run.mocks "${selector}" is a locked block (or inside a locked loop or parallel); its configured behaviour cannot be replaced.` - ) - } - const refusal = mockOutputRefusal(`run.mocks "${selector}"`, output) - if (refusal) throw new OrchestrationError('validation', refusal) - blockMocks.set(blockId, output) - } - return { - triggerType: TEST_TRIGGER, - sideEffectPolicy: new WriteStubPolicy({ workflowId, allowBlockIds, blockMocks }), - } -} - function listTriggers(options: ReturnType): string { return options.map((option) => `${option.triggerBlockId} (${option.blockName})`).join(', ') } -function executionServiceInput(params: { +async function executionServiceInput(params: { principal: WorkflowExecutionPrincipal context: Awaited> input: ManualExecutionInput @@ -247,7 +132,15 @@ function executionServiceInput(params: { stopAfterBlockId: string | undefined }) { return { - ...resolveRunOverrides(params.draftState, params.input, params.context.workflowId), + ...(await resolveRunOverrides({ + principal: params.principal, + workspaceId: params.context.workspaceId, + workflow: params.context.workflow, + blocks: params.draftState.blocks, + mode: params.input.mode, + detachable: params.input.detachable, + request: params.input, + })), workflowId: params.context.workflowId, principal: params.principal, userId: requirePrincipalSubjectUserId(params.principal), @@ -326,7 +219,13 @@ export const executeManualWorkflowOperation = defineAuthorizedWorkflowUseCase({ } const result = await executeWorkflowService({ - ...executionServiceInput({ principal, context, input, draftState: state, stopAfterBlockId }), + ...(await executionServiceInput({ + principal, + context, + input, + draftState: state, + stopAfterBlockId, + })), input: executionInput, triggerBlockId: selected.triggerBlockId, }) @@ -339,7 +238,7 @@ export const executeManualWorkflowFromBlockOperation = defineAuthorizedWorkflowU resolveContext: resolveContext, async execute({ principal, context, input }): Promise { const state = await loadManualState(context.workflowId) - const blockId = resolveBlockSelector(state, input.blockId, 'run.entry.blockId') + const blockId = resolveBlockSelector(state.blocks, input.blockId, 'run.entry.blockId') const stopAfterBlockId = resolveStopAfterBlock(state, input.stopAfterBlockId, blockId) const sourceSnapshot = await getExecutionStateForWorkflow( @@ -355,7 +254,13 @@ export const executeManualWorkflowFromBlockOperation = defineAuthorizedWorkflowU } const result = await executeWorkflowService({ - ...executionServiceInput({ principal, context, input, draftState: state, stopAfterBlockId }), + ...(await executionServiceInput({ + principal, + context, + input, + draftState: state, + stopAfterBlockId, + })), input: input.input, runFromBlock: { startBlockId: blockId, diff --git a/apps/sim/lib/workflows/application/read-workflow-run.ts b/apps/sim/lib/workflows/application/read-workflow-run.ts index a1916ef5799..dea92ea5c34 100644 --- a/apps/sim/lib/workflows/application/read-workflow-run.ts +++ b/apps/sim/lib/workflows/application/read-workflow-run.ts @@ -197,6 +197,8 @@ export const readWorkflowRun = defineAuthorizedWorkflowUseCase({ failedBlock, rerunFromBlockId, dryRun, + /** Whether the viewer's group withheld `blockOutputs` and `finalOutput`. */ + outputsHidden: projection.hideTraceSpans, } } catch (error) { if (error instanceof FunctionalOutputsUnavailableError) { diff --git a/apps/sim/lib/workflows/dry-run/index.ts b/apps/sim/lib/workflows/dry-run/index.ts index 4d13be40722..2671bd3b71d 100644 --- a/apps/sim/lib/workflows/dry-run/index.ts +++ b/apps/sim/lib/workflows/dry-run/index.ts @@ -1,7 +1,11 @@ export { sampleBlockOutput, sampleToolOutput } from './samples' export { + type DryRunMock, + type DryRunOverride, + overrideKey, PAUSING_BLOCK_TYPES, runsAnotherWorkflow, + SELF_DIRECTED_BLOCK_TYPES, type SideEffectsSummary, WriteStubPolicy, } from './side-effects' diff --git a/apps/sim/lib/workflows/dry-run/side-effects.ts b/apps/sim/lib/workflows/dry-run/side-effects.ts index 7bb12bbb07b..50445a35aa0 100644 --- a/apps/sim/lib/workflows/dry-run/side-effects.ts +++ b/apps/sim/lib/workflows/dry-run/side-effects.ts @@ -23,7 +23,10 @@ const MAX_RECORDED = 50 const CODE_TOOL_ID = 'function_execute' /** Blocks whose handlers change state outside the tool seam, so a policy answers them whole. */ -const SELF_DIRECTED_BLOCK_TYPES: ReadonlySet = new Set([BlockType.MOTHERSHIP, BlockType.PI]) +export const SELF_DIRECTED_BLOCK_TYPES: ReadonlySet = new Set([ + BlockType.MOTHERSHIP, + BlockType.PI, +]) /** * Blocks that pause the run. A test run is never resumed, so a policy answers them whole and the @@ -72,6 +75,35 @@ interface UncheckedSideEffect extends RecordedSite { reason: string } +/** A block a dry run's `run.allowBlocks` or `run.mocks` names: a block of the run's workflow or a child's. */ +export interface DryRunOverride { + workflowId: string + blockId: string + /** Its display name, which {@link SideEffectsSummary.unused} reports. */ + block: string +} + +/** A block a dry run answers with a fixed output instead of running it. */ +export interface DryRunMock extends DryRunOverride { + output: NormalizedBlockOutput + /** The run the output was read from (`run.mocksFrom`); unset for an output the caller passed. */ + sourceRunId?: string + /** Top-level fields of the output the block does not declare, which the summary reports. */ + undeclaredFields: string[] + /** Fields of the recorded output only its handler may set, left out of a mock read from a run. */ + droppedFields: string[] +} + +/** An allowed or mocked block the run never reached. */ +interface UnusedOverride extends DryRunOverride { + override: 'allow' | 'mock' +} + +/** Fields of a mock: ones its block does not declare, or ones left out of a recorded output. */ +interface MockFields extends DryRunOverride { + fields: string[] +} + /** What a dry run did with each write it reached; each list holds at most {@link MAX_RECORDED}. */ export interface SideEffectsSummary { stubbed: StubbedSideEffect[] @@ -79,6 +111,14 @@ export interface SideEffectsSummary { unchecked: UncheckedSideEffect[] /** Entries each list left out once it was full. */ omitted: { stubbed: number; allowed: number; unchecked: number } + unused: UnusedOverride[] + undeclaredMockFields: MockFields[] + droppedMockFields: MockFields[] +} + +/** The key an allowed or mocked block is matched by: its workflow and block id. */ +export function overrideKey(site: { workflowId: string; blockId: string | null }): string { + return `${site.workflowId}:${site.blockId}` } function recordedSite(site: SideEffectSite): RecordedSite { @@ -147,44 +187,44 @@ class RecordedList { * sent and any other request is answered with an empty 200 and recorded like a write, while code * in a remote sandbox, whose network the run cannot see, is listed unchecked. Custom blocks and * {@link PAUSING_BLOCK_TYPES} are answered whole, as is a block that acts outside the tool seam - * unless it is allowed, and `blockMocks` answers its blocks with fixed outputs. Allowed and mocked - * blocks are blocks of the workflow the run started, never of a child it calls, and an allowed - * Agent's own tool calls are sent, not a workflow or custom block it calls. + * unless it is allowed, and `blockMocks` answers its blocks with fixed outputs. An allowed or + * mocked block is keyed by its workflow and block id, so one of a child applies wherever that + * child runs, at every depth, and an allowed Agent's own tool calls are sent, not a workflow or + * custom block it calls. */ export class WriteStubPolicy implements SideEffectPolicy { private readonly stubbed = new RecordedList() private readonly allowed = new RecordedList() private readonly unchecked = new RecordedList() - private readonly allowBlockIds: ReadonlySet - private readonly blockMocks: ReadonlyMap + private readonly allowBlocks: ReadonlyMap + private readonly blockMocks: ReadonlyMap + /** Keys of the allowed and mocked blocks the run reached. */ + private readonly reached = new Set() constructor( private readonly options: { /** The workflow the run started. */ workflowId: string - /** Its blocks whose writes are sent. */ - allowBlockIds?: ReadonlySet - /** Its blocks answered with these outputs instead of running. */ - blockMocks?: ReadonlyMap + /** Blocks whose writes are sent. */ + allowBlocks?: readonly DryRunOverride[] + /** Blocks answered with these outputs instead of running. */ + blockMocks?: readonly DryRunMock[] } ) { - this.allowBlockIds = options.allowBlockIds ?? new Set() - this.blockMocks = options.blockMocks ?? new Map() - } - - /** The block's id when it is a block of the workflow the run started. */ - private runBlockId(site: SideEffectSite): string | null { - return site.workflowId === this.options.workflowId ? site.blockId : null + this.allowBlocks = new Map( + (options.allowBlocks ?? []).map((entry) => [overrideKey(entry), entry]) + ) + this.blockMocks = new Map( + (options.blockMocks ?? []).map((entry) => [overrideKey(entry), entry]) + ) } private allows(site: SideEffectSite): boolean { - const blockId = this.runBlockId(site) - return blockId !== null && this.allowBlockIds.has(blockId) + return site.blockId !== null && this.allowBlocks.has(overrideKey(site)) } private mockOf(site: SideEffectSite): NormalizedBlockOutput | undefined { - const blockId = this.runBlockId(site) - return blockId === null ? undefined : this.blockMocks.get(blockId) + return site.blockId === null ? undefined : this.blockMocks.get(overrideKey(site))?.output } /** @@ -248,6 +288,8 @@ export class WriteStubPolicy implements SideEffectPolicy { } answersBlock(block: SideEffectBlockSite): boolean { + const key = overrideKey(block) + if (this.allowBlocks.has(key) || this.blockMocks.has(key)) this.reached.add(key) if (this.mockOf(block)) return true if (PAUSING_BLOCK_TYPES.has(block.blockType)) return true if (isCustomBlockType(block.blockType)) return true @@ -268,11 +310,38 @@ export class WriteStubPolicy implements SideEffectPolicy { /** * The allowed and mocked blocks, by id, which the run's log records so a rerun of this run passes - * them again. Never the mock outputs, which a rerun passes again: the log shows a mocked block's - * output only as that block's output, redacted like any other. + * them again; a child's are listed apart with its workflow id, and a mock read from another run + * by that run's id. Never the mock outputs, which a rerun passes again: the log shows a mocked + * block's output only as that block's output, redacted like any other. */ runOptions(): DryRunOptions { - return { allowBlocks: [...this.allowBlockIds], mockedBlocks: [...this.blockMocks.keys()] } + const own = (entry: DryRunOverride) => entry.workflowId === this.options.workflowId + const ref = ({ workflowId, blockId }: DryRunOverride) => ({ workflowId, blockId }) + const allowed = [...this.allowBlocks.values()] + const passed = [...this.blockMocks.values()].filter((mock) => mock.sourceRunId === undefined) + const read = [...this.blockMocks.values()].filter((mock) => mock.sourceRunId !== undefined) + const childAllowBlocks = allowed.filter((entry) => !own(entry)).map(ref) + const childMockedBlocks = passed.filter((entry) => !own(entry)).map(ref) + return { + allowBlocks: allowed.filter(own).map((entry) => entry.blockId), + mockedBlocks: passed.filter(own).map((entry) => entry.blockId), + ...(childAllowBlocks.length > 0 ? { childAllowBlocks } : {}), + ...(childMockedBlocks.length > 0 ? { childMockedBlocks } : {}), + ...(read[0]?.sourceRunId + ? { mocksFrom: { runId: read[0].sourceRunId, blockIds: read.map((mock) => mock.blockId) } } + : {}), + } + } + + private mockFields(fieldsOf: (mock: DryRunMock) => string[]): MockFields[] { + return [...this.blockMocks.values()] + .filter((mock) => fieldsOf(mock).length > 0) + .map((mock) => ({ + workflowId: mock.workflowId, + blockId: mock.blockId, + block: mock.block, + fields: fieldsOf(mock), + })) } summary(): SideEffectsSummary { @@ -285,6 +354,20 @@ export class WriteStubPolicy implements SideEffectPolicy { allowed: this.allowed.omitted, unchecked: this.unchecked.omitted, }, + unused: [ + ...[...this.allowBlocks.values()].map((entry) => ({ + ...entry, + override: 'allow' as const, + })), + ...[...this.blockMocks.values()].map(({ workflowId, blockId, block }) => ({ + workflowId, + blockId, + block, + override: 'mock' as const, + })), + ].filter((entry) => !this.reached.has(overrideKey(entry))), + undeclaredMockFields: this.mockFields((mock) => mock.undeclaredFields), + droppedMockFields: this.mockFields((mock) => mock.droppedFields), } } } diff --git a/apps/sim/lib/workflows/executor/execution-status.ts b/apps/sim/lib/workflows/executor/execution-status.ts index 1bfc67468be..5953e9bedc7 100644 --- a/apps/sim/lib/workflows/executor/execution-status.ts +++ b/apps/sim/lib/workflows/executor/execution-status.ts @@ -270,8 +270,8 @@ export interface ProjectedWorkflowExecutionStatus { */ failedBlock: FailedTraceBlock | null /** - * A failed dry run's allowed and mocked blocks, which a rerun of it names again; null for any - * other run, or when the viewer's group withholds execution data. + * A dry run's allowed and mocked blocks, whatever its status; null for any other run, or when + * the viewer's group withholds execution data. * * permission-group-enforced: logs.trace_spans */ @@ -373,7 +373,7 @@ interface ResolvedExecutionStatus { pausePoints: unknown /** The failing block the recorded trace names, when the answered `error` is the run's own. */ failedBlock: FailedTraceBlock | null - /** A failed dry run's allowed and mocked blocks, as its log's trigger recorded them. */ + /** A dry run's allowed and mocked blocks, as its log's trigger recorded them. */ dryRun: DryRunOptions | null } @@ -630,8 +630,7 @@ async function readWorkflowExecutionStatus( stateExecutionId: executionId, pausePoints: paused ? pausedRow?.pausePoints : null, failedBlock: error ? findFailedTraceBlock(executionData?.traceSpans, error) : null, - dryRun: - status === 'failed' && logRow.trigger === TEST_TRIGGER ? readDryRun(executionData) : null, + dryRun: logRow.trigger === TEST_TRIGGER ? readDryRun(executionData) : null, } } diff --git a/apps/sim/lib/workflows/queries.ts b/apps/sim/lib/workflows/queries.ts index 8e9081aeb6a..6e86cde1ca9 100644 --- a/apps/sim/lib/workflows/queries.ts +++ b/apps/sim/lib/workflows/queries.ts @@ -1,6 +1,6 @@ import { db } from '@sim/db' -import { workflow } from '@sim/db/schema' -import { and, asc, eq, inArray, isNotNull, isNull, type SQL, sql } from 'drizzle-orm' +import { customBlock, workflow } from '@sim/db/schema' +import { and, asc, eq, inArray, isNotNull, isNull, or, type SQL, sql } from 'drizzle-orm' import type { WorkflowListItem } from '@/lib/api/contracts/workflows' import { type CursorKey, @@ -137,6 +137,42 @@ export async function listActiveWorkflowsNamed(workspaceId: string, name: string .limit(2) } +/** At most this many workflows answer {@link listActiveWorkflowIdsByIdOrName}. */ +const MAX_WORKFLOWS_BY_ID_OR_NAME = 100 + +/** + * Ids of the active workflows of `workspaceId` whose id or exact name is one of `keys`, in one + * query, at most {@link MAX_WORKFLOWS_BY_ID_OR_NAME}. + */ +export async function listActiveWorkflowIdsByIdOrName( + workspaceId: string, + keys: readonly string[] +): Promise { + if (keys.length === 0) return [] + const rows = await db + .select({ id: workflow.id }) + .from(workflow) + .where( + and( + eq(workflow.workspaceId, workspaceId), + isNull(workflow.archivedAt), + or(inArray(workflow.id, [...keys]), inArray(workflow.name, [...keys])) + ) + ) + .limit(MAX_WORKFLOWS_BY_ID_OR_NAME) + return rows.map((row) => row.id) +} + +/** Whether `workflowId` is the source workflow a custom block runs. */ +export async function isCustomBlockSourceWorkflow(workflowId: string): Promise { + const [row] = await db + .select({ id: customBlock.id }) + .from(customBlock) + .where(eq(customBlock.workflowId, workflowId)) + .limit(1) + return row !== undefined +} + /** An active workflow's name by id, or null when it is archived or gone. */ export async function getActiveWorkflowName(workflowId: string): Promise { const [row] = await db diff --git a/apps/sim/tools/index.test.ts b/apps/sim/tools/index.test.ts index c6bbfaa439d..e75c8a10f90 100644 --- a/apps/sim/tools/index.test.ts +++ b/apps/sim/tools/index.test.ts @@ -7523,7 +7523,7 @@ describe('MCP Tool Execution', () => { ) const allowed = new WriteStubPolicy({ workflowId: 'test-workflow', - allowBlockIds: new Set(['agent-1']), + allowBlocks: [{ workflowId: 'test-workflow', blockId: 'agent-1', block: 'Agent 1' }], }) await executeTool('mcp-123-delete_file', params, { executionContext: createToolExecutionContext({ sideEffects: allowed }), diff --git a/apps/sim/tools/side-effects.test.ts b/apps/sim/tools/side-effects.test.ts index bc8d8d72b5a..1b274812f54 100644 --- a/apps/sim/tools/side-effects.test.ts +++ b/apps/sim/tools/side-effects.test.ts @@ -194,7 +194,10 @@ describe('code a dry run runs', () => { }) it('is listed unchecked, not allowed, when its block is allowed and it runs in a remote sandbox', () => { - const policy = new WriteStubPolicy({ workflowId: 'wf-1', allowBlockIds: new Set(['python']) }) + const policy = new WriteStubPolicy({ + workflowId: 'wf-1', + allowBlocks: [{ workflowId: 'wf-1', blockId: 'python', block: 'python' }], + }) const code = policy.codeNetwork({ workflowId: 'wf-1', blockId: 'python', diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts b/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts index 0d048e3463a..35e6939c86d 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts @@ -752,6 +752,28 @@ describe('sim workflows run --dry', () => { }) }) + it('sends bare --mock blocks as the blocks --mock-from answers, beside passed mocks', async () => { + vi.spyOn(console, 'log').mockImplementation(() => {}) + + await run( + WORKFLOW_ID, + '--dry', + '--mock-from', + 'run-1', + '--mock', + 'Score lead', + '--mock', + 'child.Router={"route":"vip"}' + ) + + expect(requestRaw.mock.calls[0][1].body.run).toEqual({ + source: 'manual', + dry: true, + mocks: { 'child.Router': { route: 'vip' } }, + mocksFrom: { runId: 'run-1', blocks: ['Score lead'] }, + }) + }) + it('refuses combinations a dry run cannot honour before sending anything', async () => { await expect(run(WORKFLOW_ID, '--allow', 'Save lead')).rejects.toThrow('add --dry') await expect(run(WORKFLOW_ID, '--mock', 'Score={"content":"spam"}')).rejects.toThrow( @@ -763,7 +785,16 @@ describe('sim workflows run --dry', () => { ) await expect(run(WORKFLOW_ID, '--dry', '--async')).rejects.toThrow('drop --async') await expect(run(WORKFLOW_ID, '--dry', '--mock', '{"content":"spam"}')).rejects.toThrow( - 'must be =' + 'names no output: pass =, or add --mock-from ' + ) + await expect(run(WORKFLOW_ID, '--dry', '--mock', 'blk_2=')).rejects.toThrow( + "replace with the block's output" + ) + await expect(run(WORKFLOW_ID, '--dry', '--mock-from', 'run_1')).rejects.toThrow( + 'name at least one' + ) + await expect(run(WORKFLOW_ID, '--mock-from', 'run_1', '--mock', 'Score')).rejects.toThrow( + '--mock-from answers a block during a dry run' ) await expect(run(WORKFLOW_ID, '--dry', '--mock', 'Score=spam')).rejects.toThrow( 'is not valid JSON' diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts index e5cb3bafd49..19e83e6b8de 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts @@ -66,6 +66,7 @@ type WorkflowRunSelection = dry?: true allowBlocks?: string[] mocks?: Record> + mocksFrom?: { runId: string; blocks: string[] } } /** The flags that run the saved draft, which a pinned deployment version never runs. */ @@ -79,6 +80,7 @@ const DRAFT_RUN_FLAGS = [ ['sourceRun', '--source-run'], ['allow', '--allow'], ['mock', '--mock'], + ['mockFrom', '--mock-from'], ] as const /** @@ -105,12 +107,33 @@ function pinnedDeployment( return { source: 'deployment', version } } -/** `--mock =` values as the block selector each names and its output object. */ -async function readBlockMocks(values: string[]): Promise>> { +/** + * `--mock =` values as the block selector each names and its output object, and + * the blocks of each bare `--mock `, which `--mock-from ` answers with the output + * that run recorded. + */ +async function readBlockMocks( + values: string[], + mockFrom: string | undefined +): Promise<{ mocks: Record>; recorded: string[] }> { const mocks: Record> = {} + const recorded: string[] = [] for (const value of values) { const separator = value.indexOf('=') - const block = separator > 0 ? value.slice(0, separator).trim() : '' + if (separator === -1) { + const block = value.trim() + if (!block) throw new SimApiError('--mock requires a block id, name or key', 0) + if (mockFrom === undefined) { + throw new SimApiError( + `--mock ${block} names no output: pass =, or add --mock-from to answer it with the output that run recorded`, + 0 + ) + } + if (recorded.includes(block)) throw new SimApiError(`--mock names ${block} twice`, 0) + recorded.push(block) + continue + } + const block = value.slice(0, separator).trim() if (!block) { throw new SimApiError(`--mock "${value}" must be =`, 0) } @@ -118,6 +141,12 @@ async function readBlockMocks(values: string[]): Promise') { + throw new SimApiError( + `--mock ${block}=: replace with the block's output (next cannot repeat a passed mock)`, + 0 + ) + } const source = await readArgumentSource(value.slice(separator + 1), 'mock') let output: unknown try { @@ -134,7 +163,13 @@ async function readBlockMocks(values: string[]): Promise; name at least one', + 0 + ) + } + return { mocks, recorded } } /** Projects friendly CLI flags into the API's strict nested run selector. */ @@ -149,6 +184,7 @@ async function resolveWorkflowRunSelection( const dry = flags.dry === true const allowBlocks = toArray(flags.allow) const mockValues = toArray(flags.mock) + const mockFrom = typeof flags.mockFrom === 'string' ? flags.mockFrom : undefined /** These flags only apply to the draft, so each implies `--manual`. */ const manual = flags.manual === true || @@ -162,12 +198,15 @@ async function resolveWorkflowRunSelection( if (allowBlocks.length > 0 && !dry) { throw new SimApiError("--allow sends one block's writes during a dry run; add --dry", 0) } - if (mockValues.length > 0 && !dry) { + if ((mockValues.length > 0 || mockFrom !== undefined) && !dry) { throw new SimApiError( - '--mock answers a block during a dry run, so its output never drives real writes; add --dry', + `${mockFrom !== undefined ? '--mock-from' : '--mock'} answers a block during a dry run, so its output never drives real writes; add --dry`, 0 ) } + if (mockFrom !== undefined && mockFrom.trim() === '') { + throw new SimApiError('--mock-from requires a run id', 0) + } if (allowBlocks.some((block) => block.trim() === '')) { throw new SimApiError('--allow requires a block id, name or key', 0) } @@ -206,12 +245,13 @@ async function resolveWorkflowRunSelection( throw new SimApiError('--stop-after requires a block id, name or key', 0) } - const mocks = await readBlockMocks(mockValues) + const { mocks, recorded } = await readBlockMocks(mockValues, mockFrom) const options = { ...(stopAfter !== undefined ? { stopAfterBlockId: stopAfter } : {}), ...(dry ? { dry: true as const } : {}), ...(allowBlocks.length > 0 ? { allowBlocks } : {}), - ...(mockValues.length > 0 ? { mocks } : {}), + ...(Object.keys(mocks).length > 0 ? { mocks } : {}), + ...(mockFrom !== undefined ? { mocksFrom: { runId: mockFrom, blocks: recorded } } : {}), } if (fromBlock && sourceRun) { return { @@ -236,8 +276,9 @@ async function resolveWorkflowRunSelection( /** * A dry run's side effects in a few lines on stderr, for the human formats: each write that was * not sent, sent because its block was allowed, or code in a remote sandbox the run cannot see, - * and a note for an allowed block whose writes all stayed stubbed (an Agent's call to a custom - * block). The request payloads are in the result itself (`--output json`). + * and notes for an allowed block whose writes all stayed stubbed (an Agent's call to a custom + * block), an allowed or mocked block the run never reached, and a mock setting fields its block + * does not declare. The request payloads are in the result itself (`--output json`). */ function printSideEffects(sideEffects: unknown, dryRun: unknown): void { if (!isRecordLike(sideEffects)) return @@ -272,6 +313,23 @@ function printSideEffects(sideEffects: unknown, dryRun: unknown): void { ` note ${safeOneLine(String(held.block))} was allowed but sent nothing: allowing an Agent sends only its own tool calls, not a workflow or custom block it calls` ) } + for (const entry of list('unused')) { + lines.push( + ` note ${safeOneLine(String(entry.block))} was ${entry.override === 'mock' ? 'mocked' : 'allowed'} but never ran: check the branch, the entry block, or the workflow you named` + ) + } + for (const entry of list('undeclaredMockFields')) { + const fields = toArray(entry.fields).map(String).join(', ') + lines.push( + ` note mock of ${safeOneLine(String(entry.block))} sets ${safeOneLine(fields)}, which the block does not declare; a block reading them gets nothing` + ) + } + for (const entry of list('droppedMockFields')) { + const fields = toArray(entry.fields).map(String).join(', ') + lines.push( + ` note mock of ${safeOneLine(String(entry.block))} from --mock-from left out ${safeOneLine(fields)}, which only a block sets; a block reading them gets nothing` + ) + } lines.push('Request payloads: sideEffects in --output json') writeStderr(styles().dim(`${lines.join('\n')}\n`)) } @@ -793,10 +851,17 @@ run dry too; custom, Human in the loop and Wait blocks are answered whole, so th pauses. Agents read memory but write none, and the run raises no workspace event. --allow sends that block's writes (a Function's fetches included) for real (use a test resource); allowing an Agent sends only its own tool calls, not a workflow or custom block it -calls. --mock = answers a block with fixed output, to steer a branch; a locked block -cannot be mocked, and a mock is data, so it cannot set a field the run's execution, trace or -billing reads (such as cost, tokens, model or a field starting with _). A dry run is the ---source-run only of another dry run, and is never resumed. +calls. --mock = answers a block with fixed output, to steer a branch; a locked block, +or one of a locked workflow or folder, cannot be mocked, and a mock is data, so it cannot set a +field the run's execution, trace or billing reads (such as cost, tokens, model or a field starting +with _). --mock-from with a bare --mock answers that block with the output it +recorded in that run of this workflow (not a block a test run answered with a placeholder); fields +only a block sets, such as cost or model, are left out and noted. --allow and --mock also name a +block of a workflow this one calls as . (the workflow's id or name); the entry +applies wherever that workflow runs, at every depth. Blocks for --from-block, --stop-after and a +bare --mock with --mock-from are this workflow's only. Blocks never reached, and mock fields a +block does not declare, are noted. A dry run is the --source-run only of another dry run, and is +never resumed. The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: @@ -805,10 +870,10 @@ instead: success and output. A run that failed in a block has next: the command that reruns the saved draft from that block (or from the outermost loop or parallel holding it) with this run as --source-run, so after a fix -only that block and those after it run again; a dry run's keeps --dry and --allow. The run records -only which blocks were mocked, so pass each --mock again; its log shows a mocked block's output -like any other. Add --stop-after to stop after a block; -naming the block next starts from reruns only it. +only that block and those after it run again; a dry run's keeps --dry and --allow, and reads its +mocks again with --mock-from (this run, for mocks you passed). A mock of a child's block, or one +passed beside --mock-from, comes back as --mock =: replace with the output. +Add --stop-after to stop after a block; naming the block next starts from reruns only it. Exit codes: 0 completed or paused (--async: queued); 1 failed or cancelled (the result is printed first, then the error on stderr), or the command failed; ${STILL_RUNNING_EXIT_CODE} still running when --wait-timeout @@ -848,14 +913,18 @@ export function attachWorkflowRunFollow(workflows: Command): void { ) .option( '--allow ', - "Send this block's writes for real during a --dry run (its id, display name or key); for an Agent, only its own tool calls, not a workflow or custom block it calls; repeatable", + "Send this block's writes for real during a --dry run (its id, display name or key, or . for a workflow it calls); for an Agent, only its own tool calls, not a workflow or custom block it calls; repeatable", collectRepeated ) .option( '--mock =', - 'Answer this block with the given JSON object instead of running it during a --dry run (its id, display name or key), to steer a branch or give a stubbed write a realistic result. Not a locked block; data only, so no cost, tokens, model or other field the run’s trace or billing reads, and no field starting with _. The run records only which blocks were mocked, so a rerun passes it again (its log shows the output like any other block’s); repeatable', + 'Answer this block with the given JSON object instead of running it during a --dry run (its id, display name or key, or . for a workflow it calls), to steer a branch or give a stubbed write a realistic result; a bare --mock takes its output from --mock-from. Not a locked block, or one of a locked workflow or folder; data only, so no cost, tokens, model or other field the run’s trace or billing reads, and no field starting with _. The run records only which blocks were mocked, not the outputs (its log shows each like any other block’s output), so a rerun reads them again with --mock-from; repeatable', collectRepeated ) + .option( + '--mock-from ', + "Answer each block a bare --mock names (this workflow's blocks only) with the output it recorded in this earlier run of the workflow, redacted as the run shows it; fields only a block sets, such as cost or model, are left out (requires --dry)" + ) .option( '--trigger ', 'Enter the run through this runnable trigger, by its block id; runs the current saved workflow state (implies --manual)' diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index 4837a15594e..743689b4152 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -7127,6 +7127,10 @@ export type ExecuteWorkflowBody = { dry?: boolean allowBlocks?: Array mocks?: Record> + mocksFrom?: { + runId: string + blocks: Array + } } async?: boolean executionTimeoutSeconds?: number @@ -7186,11 +7190,41 @@ type ExecuteWorkflowResponseRef1 = { allowed: number unchecked: number } + unused: Array<{ + workflowId: string + blockId: string + block: string + override: 'allow' | 'mock' + }> + undeclaredMockFields: Array<{ + workflowId: string + blockId: string + block: string + fields: Array + }> + droppedMockFields: Array<{ + workflowId: string + blockId: string + block: string + fields: Array + }> } type ExecuteWorkflowResponseRef2 = { allowBlocks: Array mockedBlocks: Array + childAllowBlocks?: Array<{ + workflowId: string + blockId: string + }> + childMockedBlocks?: Array<{ + workflowId: string + blockId: string + }> + mocksFrom?: { + runId: string + blockIds: Array + } } type ExecuteWorkflowResponseRef3 = { @@ -10391,6 +10425,18 @@ type GetWorkflowRunResponseRef3 = { type GetWorkflowRunResponseRef4 = { allowBlocks: Array mockedBlocks: Array + childAllowBlocks?: Array<{ + workflowId: string + blockId: string + }> + childMockedBlocks?: Array<{ + workflowId: string + blockId: string + }> + mocksFrom?: { + runId: string + blockIds: Array + } } type GetWorkflowRunResponseRef5 = { diff --git a/packages/sim-cli/src/runtime/run-next.test.ts b/packages/sim-cli/src/runtime/run-next.test.ts index a18413fca3b..0d1342ca6eb 100644 --- a/packages/sim-cli/src/runtime/run-next.test.ts +++ b/packages/sim-cli/src/runtime/run-next.test.ts @@ -105,7 +105,7 @@ describe('withRunNext on a failed run', () => { }) it('keeps a test run a test: a dry run with its allowed blocks, a workflow test dry', () => { - const dryRun = { allowBlocks: ['blk_1'], mockedBlocks: ['blk_2'] } + const dryRun = { allowBlocks: ['blk_1'], mockedBlocks: [] } const next = 'sim workflows run wf_1 --from-block blk_3 --source-run run_9 --dry --allow blk_1' expect(withRunNext('executeWorkflow', { ...failed, dryRun })).toMatchObject({ next }) expect(withRunNext('getWorkflowRun', { ...failed, trigger: 'test', dryRun })).toMatchObject({ @@ -121,6 +121,31 @@ describe('withRunNext on a failed run', () => { expect(withRunNext('executeWorkflow', hostile)).toBe(hostile) }) + it('repeats a dry run’s child blocks and mocks, reading passed ones from the run itself when it can', () => { + const dryRun = { + allowBlocks: [], + mockedBlocks: ['blk_2'], + childAllowBlocks: [{ workflowId: 'wf_child', blockId: 'blk_c1' }], + childMockedBlocks: [{ workflowId: 'wf_child', blockId: 'blk_c2' }], + mocksFrom: { runId: 'run_1', blockIds: ['blk_4'] }, + } + expect(withRunNext('executeWorkflow', { ...failed, dryRun })).toMatchObject({ + next: "sim workflows run wf_1 --from-block blk_3 --source-run run_9 --dry --allow wf_child.blk_c1 --mock-from run_1 --mock blk_4 --mock 'blk_2=' --mock 'wf_child.blk_c2='", + }) + const passedOnly = { allowBlocks: [], mockedBlocks: ['blk_2', 'blk_5'] } + expect(withRunNext('executeWorkflow', { ...failed, dryRun: passedOnly })).toMatchObject({ + next: 'sim workflows run wf_1 --from-block blk_3 --source-run run_9 --dry --mock-from run_9 --mock blk_2 --mock blk_5', + }) + for (const hostile of [ + { ...dryRun, childAllowBlocks: [{ workflowId: '$(id)', blockId: 'blk_c1' }] }, + { ...dryRun, mocksFrom: { runId: 'run 1', blockIds: ['blk_4'] } }, + { ...dryRun, childMockedBlocks: [{ workflowId: 'wf_child', blockId: "x'y" }] }, + ]) { + const record = { ...failed, dryRun: hostile } + expect(withRunNext('executeWorkflow', record)).toBe(record) + } + }) + it('names no resume for a paused test run, which is never resumed', () => { const pausedTest = { ...paused, trigger: 'test' } expect(withRunNext('getWorkflowRun', pausedTest)).toBe(pausedTest) diff --git a/packages/sim-cli/src/runtime/run-next.ts b/packages/sim-cli/src/runtime/run-next.ts index 47e220f81e0..e8cfd3b3117 100644 --- a/packages/sim-cli/src/runtime/run-next.ts +++ b/packages/sim-cli/src/runtime/run-next.ts @@ -50,20 +50,57 @@ function isTestRun(record: Record): boolean { return record.trigger === 'test' || toRecordOrNull(record.dryRun) !== null } +/** `.` for a child block a dry run recorded; null when either id is not issued. */ +function childSelector(entry: unknown): string | null { + const { workflowId, blockId } = toRecordOrNull(entry) ?? {} + return issuedId(workflowId) && issuedId(blockId) ? `${workflowId}.${blockId}` : null +} + /** * The flags that keep a rerun of a test run a test: `--dry`, with a dry run's own `--allow` - * blocks (`dryRun.allowBlocks`), so following `next` never sends what the run held back. A - * workflow test's run has no `dryRun` but held its writes back all the same. A dry run records - * only which blocks were mocked, not their outputs, so `next` cannot repeat its `--mock` flags; - * the caller passes them again. Null when a block id is not in the format the server issues. + * blocks (`dryRun.allowBlocks`, and a child's as `.`), so following `next` + * never sends what the run held back. A workflow test's run has no `dryRun` but held its writes + * back all the same. A mock is recorded only by block, never its output, so `next` reads it again + * from a run: the run it was read from (`--mock-from`), or, for a mock the caller passed to this + * workflow's block, this run itself, which recorded the output the block answered with. Only one + * run can be read from, and a child's block never is, so a passed mock left over holds a `` + * placeholder the caller replaces with the output. Null when an id is not in the format the server + * issues. */ function dryRerunFlags(record: Record): string | null { if (!isTestRun(record)) return '' + const dryRun = toRecordOrNull(record.dryRun) const flags = [' --dry'] - for (const blockId of toArray(toRecordOrNull(record.dryRun)?.allowBlocks)) { + for (const blockId of toArray(dryRun?.allowBlocks)) { if (!issuedId(blockId)) return null flags.push(` --allow ${shellArgument(blockId)}`) } + for (const entry of toArray(dryRun?.childAllowBlocks)) { + const selector = childSelector(entry) + if (selector === null) return null + flags.push(` --allow ${shellArgument(selector)}`) + } + const mocksFrom = toRecordOrNull(dryRun?.mocksFrom) + const passed = toArray(dryRun?.mockedBlocks) + const [readFrom, read, unread] = mocksFrom + ? [mocksFrom.runId, toArray(mocksFrom.blockIds), passed] + : [record.runId, passed, []] + if (read.length > 0) { + if (!issuedId(readFrom)) return null + flags.push(` --mock-from ${shellArgument(readFrom)}`) + for (const blockId of read) { + if (!issuedId(blockId)) return null + flags.push(` --mock ${shellArgument(blockId)}`) + } + } + const placeholders = [ + ...unread.map((blockId) => (issuedId(blockId) ? blockId : null)), + ...toArray(dryRun?.childMockedBlocks).map(childSelector), + ] + for (const selector of placeholders) { + if (selector === null) return null + flags.push(` --mock ${shellArgument(`${selector}=`)}`) + } return flags.join('') } From 620e392881f3aacd4ff5b724eb32d9365798d2b8 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 25 Nov 2026 12:04:30 -0800 Subject: [PATCH 2/2] fix(workflows): judge mock-from sources by their run's snapshot, keep unreached mocks as placeholders in next - run.mocksFrom checks loop ancestry and placeholder answers against the source run's workflow snapshot, not the draft edited since - next reads a passed mock back with --mock-from only when the run reached it (sideEffects.unused); otherwise it prints a placeholder - refuse . selectors whose workflow names match more than the lookup cap instead of resolving a partial list - walk mock outputs without spreading into push --- apps/docs/content/docs/cli/reference.mdx | 5 +- apps/docs/content/docs/cli/workflows.mdx | 5 +- apps/sim/executor/utils/mock-output.ts | 2 +- .../application/dry-run-overrides.ts | 23 ++++++- .../application/dry-run.integration.ts | 61 +++++++++++++++++++ .../workflows/executor/execution-status.ts | 8 ++- apps/sim/lib/workflows/queries.ts | 49 +++++++++++++-- packages/sim-cli/src/runtime/run-next.test.ts | 16 ++++- packages/sim-cli/src/runtime/run-next.ts | 34 +++++++++-- 9 files changed, 178 insertions(+), 25 deletions(-) diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index a3c9d34773d..8f2ad08af0f 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8516,6 +8516,7 @@ sim workflows run [options] | `--base64-max-bytes ` | No | Maximum total bytes of file content to inline as base64, lowering but never raising the server limit of 16 MiB. Rejected when `async` is true. | | `--run-id ` | No | One-shot identifier for this run; NOT an idempotency key — reusing a claimed value fails with RUN_ID_CONFLICT instead of replaying the first result, and a fresh value starts another run. | | `--manual` | No | Run the current saved workflow state instead of the active deployment. | +| `--deployment-version ` | No | Run this deployed version instead of the active one (a version number from `sim workflows versions list`); a Workflow block in it still runs its child workflow's active deployment. Needs workspace write access, through a full-access API key or an OAuth token with api:write. Not with --manual or any flag that runs the draft. | | `--dry` | No | Dry run of the saved draft (implies --manual): writes are not sent but answered with placeholders and listed with their request payloads in sideEffects; reads, model calls and code run for real. Logged as a test run. Not with --follow, --async or --wait-timeout. | | `--allow ` | No | Send this block's writes for real during a --dry run (its id, display name or key, or <workflow>.<block> for a workflow it calls); for an Agent, only its own tool calls, not a workflow or custom block it calls; repeatable. | | `--mock =` | No | Answer this block with the given JSON object instead of running it during a --dry run (its id, display name or key, or <workflow>.<block> for a workflow it calls), to steer a branch or give a stubbed write a realistic result; a bare --mock <block> takes its output from --mock-from. Not a locked block, or one of a locked workflow or folder; data only, so no cost, tokens, model or other field the run’s trace or billing reads, and no field starting with _. The run records only which blocks were mocked, not the outputs (its log shows each like any other block’s output), so a rerun reads them again with --mock-from; repeatable. | @@ -8533,9 +8534,9 @@ sim workflows run [options] -Without --manual (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --manual runs the saved draft, as the source loop leaves it. +Without --manual (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --deployment-version <n> runs that deployed version instead, as a pin for comparing or reproducing (it needs workspace write access, through a full-access API key or an OAuth token with api:write); the child workflows it calls still run their own active deployment. --manual runs the saved draft, as the source loop leaves it. ---dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes) runs and is listed in sideEffects.unchecked. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. Agents read memory but write none, and the run raises no workspace event. --allow <block> sends that block's writes for real (use a test resource); allowing an Agent sends only its own tool calls, not a workflow or custom block it calls. --mock <block>=<json> answers a block with fixed output, to steer a branch; a locked block, or one of a locked workflow or folder, cannot be mocked, and a mock is data, so it cannot set a field the run's execution, trace or billing reads (such as cost, tokens, model or a field starting with _). --mock-from <runId> with a bare --mock <block> answers that block with the output it recorded in that run of this workflow (not a block a test run answered with a placeholder); fields only a block sets, such as cost or model, are left out and noted. --allow and --mock also name a block of a workflow this one calls as <workflow>.<block> (the workflow's id or name); the entry applies wherever that workflow runs, at every depth. Blocks for --from-block, --stop-after and a bare --mock with --mock-from are this workflow's only. Blocks never reached, and mock fields a block does not declare, are noted. A dry run is the --source-run only of another dry run, and is never resumed. +--dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls other than GET/HEAD/OPTIONS, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes) runs: its GET/HEAD/OPTIONS fetches are sent (an API that writes on a GET is not stubbed), and any other fetch, or one with a method-override header, gets an empty 200 and is listed in sideEffects.stubbed. Code in a remote sandbox (shell, Python, imports) is listed in sideEffects.unchecked, since its network cannot be seen. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. Agents read memory but write none, and the run raises no workspace event. --allow <block> sends that block's writes (a Function's fetches included) for real (use a test resource); allowing an Agent sends only its own tool calls, not a workflow or custom block it calls. --mock <block>=<json> answers a block with fixed output, to steer a branch; a locked block, or one of a locked workflow or folder, cannot be mocked, and a mock is data, so it cannot set a field the run's execution, trace or billing reads (such as cost, tokens, model or a field starting with _). --mock-from <runId> with a bare --mock <block> answers that block with the output it recorded in that run of this workflow (not a block a test run answered with a placeholder); fields only a block sets, such as cost or model, are left out and noted. --allow and --mock also name a block of a workflow this one calls as <workflow>.<block> (the workflow's id or name); the entry applies wherever that workflow runs, at every depth. Blocks for --from-block, --stop-after and a bare --mock with --mock-from are this workflow's only. Blocks never reached, and mock fields a block does not declare, are noted. A dry run is the --source-run only of another dry run, and is never resumed. The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: branch on status, or on the exit code. With --follow it is the stream's final frame instead: success and output. diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index e4e02e678bd..125e0cf396e 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -833,6 +833,7 @@ sim workflows run [options] | `--base64-max-bytes ` | No | Maximum total bytes of file content to inline as base64, lowering but never raising the server limit of 16 MiB. Rejected when `async` is true. | | `--run-id ` | No | One-shot identifier for this run; NOT an idempotency key — reusing a claimed value fails with RUN_ID_CONFLICT instead of replaying the first result, and a fresh value starts another run. | | `--manual` | No | Run the current saved workflow state instead of the active deployment. | +| `--deployment-version ` | No | Run this deployed version instead of the active one (a version number from `sim workflows versions list`); a Workflow block in it still runs its child workflow's active deployment. Needs workspace write access, through a full-access API key or an OAuth token with api:write. Not with --manual or any flag that runs the draft. | | `--dry` | No | Dry run of the saved draft (implies --manual): writes are not sent but answered with placeholders and listed with their request payloads in sideEffects; reads, model calls and code run for real. Logged as a test run. Not with --follow, --async or --wait-timeout. | | `--allow ` | No | Send this block's writes for real during a --dry run (its id, display name or key, or <workflow>.<block> for a workflow it calls); for an Agent, only its own tool calls, not a workflow or custom block it calls; repeatable. | | `--mock =` | No | Answer this block with the given JSON object instead of running it during a --dry run (its id, display name or key, or <workflow>.<block> for a workflow it calls), to steer a branch or give a stubbed write a realistic result; a bare --mock <block> takes its output from --mock-from. Not a locked block, or one of a locked workflow or folder; data only, so no cost, tokens, model or other field the run’s trace or billing reads, and no field starting with _. The run records only which blocks were mocked, not the outputs (its log shows each like any other block’s output), so a rerun reads them again with --mock-from; repeatable. | @@ -850,9 +851,9 @@ sim workflows run [options] -Without --manual (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --manual runs the saved draft, as the source loop leaves it. +Without --manual (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --deployment-version <n> runs that deployed version instead, as a pin for comparing or reproducing (it needs workspace write access, through a full-access API key or an OAuth token with api:write); the child workflows it calls still run their own active deployment. --manual runs the saved draft, as the source loop leaves it. ---dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes) runs and is listed in sideEffects.unchecked. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. Agents read memory but write none, and the run raises no workspace event. --allow <block> sends that block's writes for real (use a test resource); allowing an Agent sends only its own tool calls, not a workflow or custom block it calls. --mock <block>=<json> answers a block with fixed output, to steer a branch; a locked block, or one of a locked workflow or folder, cannot be mocked, and a mock is data, so it cannot set a field the run's execution, trace or billing reads (such as cost, tokens, model or a field starting with _). --mock-from <runId> with a bare --mock <block> answers that block with the output it recorded in that run of this workflow (not a block a test run answered with a placeholder); fields only a block sets, such as cost or model, are left out and noted. --allow and --mock also name a block of a workflow this one calls as <workflow>.<block> (the workflow's id or name); the entry applies wherever that workflow runs, at every depth. Blocks for --from-block, --stop-after and a bare --mock with --mock-from are this workflow's only. Blocks never reached, and mock fields a block does not declare, are noted. A dry run is the --source-run only of another dry run, and is never resumed. +--dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls other than GET/HEAD/OPTIONS, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes) runs: its GET/HEAD/OPTIONS fetches are sent (an API that writes on a GET is not stubbed), and any other fetch, or one with a method-override header, gets an empty 200 and is listed in sideEffects.stubbed. Code in a remote sandbox (shell, Python, imports) is listed in sideEffects.unchecked, since its network cannot be seen. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. Agents read memory but write none, and the run raises no workspace event. --allow <block> sends that block's writes (a Function's fetches included) for real (use a test resource); allowing an Agent sends only its own tool calls, not a workflow or custom block it calls. --mock <block>=<json> answers a block with fixed output, to steer a branch; a locked block, or one of a locked workflow or folder, cannot be mocked, and a mock is data, so it cannot set a field the run's execution, trace or billing reads (such as cost, tokens, model or a field starting with _). --mock-from <runId> with a bare --mock <block> answers that block with the output it recorded in that run of this workflow (not a block a test run answered with a placeholder); fields only a block sets, such as cost or model, are left out and noted. --allow and --mock also name a block of a workflow this one calls as <workflow>.<block> (the workflow's id or name); the entry applies wherever that workflow runs, at every depth. Blocks for --from-block, --stop-after and a bare --mock with --mock-from are this workflow's only. Blocks never reached, and mock fields a block does not declare, are noted. A dry run is the --source-run only of another dry run, and is never resumed. The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: branch on status, or on the exit code. With --follow it is the stream's final frame instead: success and output. diff --git a/apps/sim/executor/utils/mock-output.ts b/apps/sim/executor/utils/mock-output.ts index 599c6684bed..4bf611e7c31 100644 --- a/apps/sim/executor/utils/mock-output.ts +++ b/apps/sim/executor/utils/mock-output.ts @@ -17,7 +17,7 @@ function holdsLargeValueRef(value: unknown): boolean { const next = pending.pop() if (next === null || typeof next !== 'object') continue if (Object.hasOwn(next, LARGE_VALUE_REF_MARKER)) return true - pending.push(...Object.values(next)) + for (const child of Object.values(next)) pending.push(child) } return false } diff --git a/apps/sim/lib/workflows/application/dry-run-overrides.ts b/apps/sim/lib/workflows/application/dry-run-overrides.ts index d918b460c8e..62a077a2c0f 100644 --- a/apps/sim/lib/workflows/application/dry-run-overrides.ts +++ b/apps/sim/lib/workflows/application/dry-run-overrides.ts @@ -23,7 +23,9 @@ import { import { isCustomBlockSourceWorkflow, listActiveWorkflowIdsByIdOrName, + loadRunSnapshotBlocks, loadWorkflowReadSnapshots, + MAX_WORKFLOWS_BY_ID_OR_NAME, } from '@/lib/workflows/queries' import { getWorkflowInvocationTarget } from '@/lib/workflows/streaming/nested-output-options' import { getBlock } from '@/blocks/registry' @@ -239,6 +241,12 @@ class OverrideResolver { ), ] const ids = await listActiveWorkflowIdsByIdOrName(this.workspaceId, names) + if (ids === null) { + throw new OrchestrationError( + 'validation', + `The workflow parts of these . selectors name more than ${MAX_WORKFLOWS_BY_ID_OR_NAME} workflows of this workspace; name each workflow by its id.` + ) + } return loadWorkspaceWorkflows(ids, this.workspaceId) })() return this.inWorkspace @@ -366,6 +374,7 @@ interface RecordedMock { * Refused: a block the run did not execute; one inside a loop or parallel, whose recorded output * is one iteration's, unless the run mocked it (every iteration answered alike); and, when the * run was itself a test run, a block it answered with a placeholder rather than mocked or allowed. + * Each block is judged as that run's snapshot holds it, not as the draft has since been edited. */ async function readRecordedOutputs( principal: WorkflowExecutionPrincipal, @@ -423,6 +432,13 @@ async function readRecordedOutputs( `run.mocksFrom.runId "${runId}" has no recorded block outputs yet; mock from a run whose log is written.` ) } + const sourceBlocks = await loadRunSnapshotBlocks(root.id, runId) + if (!sourceBlocks) { + throw new OrchestrationError( + 'conflict', + `run.mocksFrom.runId "${runId}" has no recorded workflow state; mock from a run whose log is written.` + ) + } const sourceIsTestRun = run.trigger === TEST_TRIGGER const sourceMocked = new Set([ ...(run.dryRun?.mockedBlocks ?? []), @@ -431,14 +447,15 @@ async function readRecordedOutputs( const sourceAllowed = new Set(run.dryRun?.allowBlocks ?? []) return selected.map(({ label, blockId }) => { const mockedThere = sourceMocked.has(blockId) - if (!mockedThere && blockAndAncestors(root.blocks, blockId).length > 1) { + const sourceBlock = sourceBlocks[blockId] + if (!mockedThere && blockAndAncestors(sourceBlocks, blockId).length > 1) { throw new OrchestrationError( 'validation', `${label} is inside a loop or parallel, whose recorded output is one iteration's; pass its output with run.mocks instead.` ) } const output = blockOutputs[blockId] - if (output === undefined) { + if (output === undefined || !sourceBlock) { throw new OrchestrationError( 'validation', mockedThere @@ -456,7 +473,7 @@ async function readRecordedOutputs( sourceIsTestRun && !mockedThere && !sourceAllowed.has(blockId) && - answeredWithPlaceholder(root.blocks[blockId]) + answeredWithPlaceholder(sourceBlock) ) { throw new OrchestrationError( 'validation', diff --git a/apps/sim/lib/workflows/application/dry-run.integration.ts b/apps/sim/lib/workflows/application/dry-run.integration.ts index 4a8764278d8..abbddc73ef4 100644 --- a/apps/sim/lib/workflows/application/dry-run.integration.ts +++ b/apps/sim/lib/workflows/application/dry-run.integration.ts @@ -23,6 +23,7 @@ import { apiKey, customBlock, customTools, + folder, mcpServers, memory, organization, @@ -2415,6 +2416,39 @@ describe('a dry run’s block selectors', () => { } expect(await logTriggers(parentId)).toEqual([]) }) + + it('refuse a workflow name shared by more workflows than a lookup returns, rather than resolve a partial list', async () => { + const { parentId } = await parentFixture() + const crowded = `Crowded ${generateId()}` + const now = new Date() + const folders = Array.from({ length: 101 }, () => ({ + id: generateId(), + resourceType: 'workflow' as const, + name: `Folder ${generateId()}`, + userId: ownerId, + workspaceId, + })) + await db.insert(folder).values(folders) + const crowd = folders.map((entry) => ({ + id: generateId(), + userId: ownerId, + workspaceId, + folderId: entry.id, + name: crowded, + lastSynced: now, + createdAt: now, + updatedAt: now, + })) + await db.insert(workflow).values(crowd) + workflowIds.push(...crowd.map((entry) => entry.id)) + + await expect( + run(parentId, { dry: true, allowBlocks: [`${crowded}.save`] }) + ).rejects.toMatchObject({ + ...validationError, + message: expect.stringContaining('name more than 100 workflows'), + }) + }) }) describe('a dry run’s mocks from an earlier run, read as that run shows them', () => { @@ -2468,6 +2502,33 @@ describe('a dry run’s mocks from an earlier run, read as that run shows them', expect(replayed.sideEffects?.stubbed[0]?.request).toMatchObject({ data: { note: 'count 7' } }) }) + it('judge a block as the earlier run ran it, not as the draft has since been edited', async () => { + const tableId = await createTable() + const fixture = lookupThenSave(tableId, 'a@b.co') + const workflowId = await saveWorkflow(fixture.state) + const source = await run(workflowId, { dry: true }) + expect(source.status, JSON.stringify(source.error)).toBe('completed') + const lookupId = fixture.idOf('lookup') + const saveId = fixture.idOf('save') + const edited = structuredClone(fixture.state) + edited.blocks[lookupId] = { ...upsertLead('lookup', tableId, 'c@b.co'), id: lookupId } + edited.blocks[saveId] = { ...queryLeads('save', tableId), id: saveId } + const saved = await saveWorkflowToNormalizedTables(workflowId, edited) + expect(saved.success, saved.error).toBe(true) + + await expect( + run(workflowId, { dry: true, mocksFrom: { runId: source.executionId, blocks: ['save'] } }) + ).rejects.toMatchObject({ + ...validationError, + message: expect.stringContaining('answered this block with a placeholder'), + }) + const replayed = await run(workflowId, { + dry: true, + mocksFrom: { runId: source.executionId, blocks: ['lookup'] }, + }) + expect(replayed.status, JSON.stringify(replayed.error)).toBe('completed') + }) + it('are refused while the run is running, when its outputs are hidden, and before it has any', async () => { const tableId = await createTable() const workflowId = await saveWorkflow(lookupThenSave(tableId, 'a@b.co').state) diff --git a/apps/sim/lib/workflows/executor/execution-status.ts b/apps/sim/lib/workflows/executor/execution-status.ts index 5953e9bedc7..7ebced9110a 100644 --- a/apps/sim/lib/workflows/executor/execution-status.ts +++ b/apps/sim/lib/workflows/executor/execution-status.ts @@ -270,8 +270,10 @@ export interface ProjectedWorkflowExecutionStatus { */ failedBlock: FailedTraceBlock | null /** - * A dry run's allowed and mocked blocks, whatever its status; null for any other run, or when - * the viewer's group withholds execution data. + * A dry run's allowed and mocked blocks, whatever its status, when the read loads execution data + * (a failed run, or one read with its output or selected block outputs); null otherwise, for any + * other run, or when the viewer's group withholds execution data. The v2 run read returns only + * a failed run's, and a `run.mocksFrom` read always selects block outputs. * * permission-group-enforced: logs.trace_spans */ @@ -373,7 +375,7 @@ interface ResolvedExecutionStatus { pausePoints: unknown /** The failing block the recorded trace names, when the answered `error` is the run's own. */ failedBlock: FailedTraceBlock | null - /** A dry run's allowed and mocked blocks, as its log's trigger recorded them. */ + /** A dry run's allowed and mocked blocks, as its log's trigger recorded them, when execution data was read. */ dryRun: DryRunOptions | null } diff --git a/apps/sim/lib/workflows/queries.ts b/apps/sim/lib/workflows/queries.ts index 6e86cde1ca9..8a4b9a7a5b6 100644 --- a/apps/sim/lib/workflows/queries.ts +++ b/apps/sim/lib/workflows/queries.ts @@ -1,5 +1,11 @@ import { db } from '@sim/db' -import { customBlock, workflow } from '@sim/db/schema' +import { + customBlock, + workflow, + workflowExecutionLogs, + workflowExecutionSnapshots, +} from '@sim/db/schema' +import type { BlockState } from '@sim/workflow-types/workflow' import { and, asc, eq, inArray, isNotNull, isNull, or, type SQL, sql } from 'drizzle-orm' import type { WorkflowListItem } from '@/lib/api/contracts/workflows' import { @@ -138,16 +144,17 @@ export async function listActiveWorkflowsNamed(workspaceId: string, name: string } /** At most this many workflows answer {@link listActiveWorkflowIdsByIdOrName}. */ -const MAX_WORKFLOWS_BY_ID_OR_NAME = 100 +export const MAX_WORKFLOWS_BY_ID_OR_NAME = 100 /** * Ids of the active workflows of `workspaceId` whose id or exact name is one of `keys`, in one - * query, at most {@link MAX_WORKFLOWS_BY_ID_OR_NAME}. + * query; null when more than {@link MAX_WORKFLOWS_BY_ID_OR_NAME} match, so no caller resolves + * against a partial answer. */ export async function listActiveWorkflowIdsByIdOrName( workspaceId: string, keys: readonly string[] -): Promise { +): Promise { if (keys.length === 0) return [] const rows = await db .select({ id: workflow.id }) @@ -159,8 +166,38 @@ export async function listActiveWorkflowIdsByIdOrName( or(inArray(workflow.id, [...keys]), inArray(workflow.name, [...keys])) ) ) - .limit(MAX_WORKFLOWS_BY_ID_OR_NAME) - return rows.map((row) => row.id) + .limit(MAX_WORKFLOWS_BY_ID_OR_NAME + 1) + return rows.length > MAX_WORKFLOWS_BY_ID_OR_NAME ? null : rows.map((row) => row.id) +} + +/** + * The blocks of the workflow state `executionId`, a run of `workflowId`, executed, as its log's + * snapshot holds them; null when the run has no log. + */ +export async function loadRunSnapshotBlocks( + workflowId: string, + executionId: string +): Promise | null> { + const [row] = await db + .select({ + blocks: sql | null>`${workflowExecutionSnapshots.stateData} -> 'blocks'`, + }) + .from(workflowExecutionLogs) + .innerJoin( + workflowExecutionSnapshots, + eq(workflowExecutionSnapshots.id, workflowExecutionLogs.stateSnapshotId) + ) + .where( + and( + eq(workflowExecutionLogs.executionId, executionId), + eq(workflowExecutionLogs.workflowId, workflowId) + ) + ) + .limit(1) + return row?.blocks ?? null } /** Whether `workflowId` is the source workflow a custom block runs. */ diff --git a/packages/sim-cli/src/runtime/run-next.test.ts b/packages/sim-cli/src/runtime/run-next.test.ts index 0d1342ca6eb..7c25eadd11d 100644 --- a/packages/sim-cli/src/runtime/run-next.test.ts +++ b/packages/sim-cli/src/runtime/run-next.test.ts @@ -121,7 +121,7 @@ describe('withRunNext on a failed run', () => { expect(withRunNext('executeWorkflow', hostile)).toBe(hostile) }) - it('repeats a dry run’s child blocks and mocks, reading passed ones from the run itself when it can', () => { + it('repeats a dry run’s child blocks and mocks, reading passed ones from the run only where it reached them', () => { const dryRun = { allowBlocks: [], mockedBlocks: ['blk_2'], @@ -133,8 +133,18 @@ describe('withRunNext on a failed run', () => { next: "sim workflows run wf_1 --from-block blk_3 --source-run run_9 --dry --allow wf_child.blk_c1 --mock-from run_1 --mock blk_4 --mock 'blk_2=' --mock 'wf_child.blk_c2='", }) const passedOnly = { allowBlocks: [], mockedBlocks: ['blk_2', 'blk_5'] } - expect(withRunNext('executeWorkflow', { ...failed, dryRun: passedOnly })).toMatchObject({ - next: 'sim workflows run wf_1 --from-block blk_3 --source-run run_9 --dry --mock-from run_9 --mock blk_2 --mock blk_5', + const sideEffects = { + unused: [{ workflowId: 'wf_1', blockId: 'blk_5', block: 'Notify', override: 'mock' }], + } + expect( + withRunNext('executeWorkflow', { ...failed, dryRun: passedOnly, sideEffects }) + ).toMatchObject({ + next: "sim workflows run wf_1 --from-block blk_3 --source-run run_9 --dry --mock-from run_9 --mock blk_2 --mock 'blk_5='", + }) + expect( + withRunNext('getWorkflowRun', { ...failed, trigger: 'test', dryRun: passedOnly }) + ).toMatchObject({ + next: "sim workflows run wf_1 --from-block blk_3 --source-run run_9 --dry --mock 'blk_2=' --mock 'blk_5='", }) for (const hostile of [ { ...dryRun, childAllowBlocks: [{ workflowId: '$(id)', blockId: 'blk_c1' }] }, diff --git a/packages/sim-cli/src/runtime/run-next.ts b/packages/sim-cli/src/runtime/run-next.ts index e8cfd3b3117..34a7ac02677 100644 --- a/packages/sim-cli/src/runtime/run-next.ts +++ b/packages/sim-cli/src/runtime/run-next.ts @@ -56,16 +56,35 @@ function childSelector(entry: unknown): string | null { return issuedId(workflowId) && issuedId(blockId) ? `${workflowId}.${blockId}` : null } +/** + * The run's own mocked blocks it reached, so recorded an output for: every mocked block of this + * workflow its `sideEffects.unused` does not list. None when the record carries no such list (a run + * read back later, which keeps no side effects), so no `--mock-from` names an output never recorded. + */ +function reachedMocks(record: Record): Set { + const unused = toRecordOrNull(record.sideEffects)?.unused + if (!Array.isArray(unused)) return new Set() + const unreached = new Set( + unused.flatMap((entry) => + isRecordLike(entry) && entry.override === 'mock' && entry.workflowId === record.workflowId + ? [entry.blockId] + : [] + ) + ) + const mocked = toArray(toRecordOrNull(record.dryRun)?.mockedBlocks) + return new Set(mocked.filter((blockId) => !unreached.has(blockId))) +} + /** * The flags that keep a rerun of a test run a test: `--dry`, with a dry run's own `--allow` * blocks (`dryRun.allowBlocks`, and a child's as `.`), so following `next` * never sends what the run held back. A workflow test's run has no `dryRun` but held its writes * back all the same. A mock is recorded only by block, never its output, so `next` reads it again * from a run: the run it was read from (`--mock-from`), or, for a mock the caller passed to this - * workflow's block, this run itself, which recorded the output the block answered with. Only one - * run can be read from, and a child's block never is, so a passed mock left over holds a `` - * placeholder the caller replaces with the output. Null when an id is not in the format the server - * issues. + * workflow's block, this run itself, which recorded the output the block answered with if the run + * reached it ({@link reachedMocks}). Only one run can be read from, and a child's block never is, + * so a passed mock left over holds a `` placeholder the caller replaces with the output. + * Null when an id is not in the format the server issues. */ function dryRerunFlags(record: Record): string | null { if (!isTestRun(record)) return '' @@ -82,9 +101,14 @@ function dryRerunFlags(record: Record): string | null { } const mocksFrom = toRecordOrNull(dryRun?.mocksFrom) const passed = toArray(dryRun?.mockedBlocks) + const reached = reachedMocks(record) const [readFrom, read, unread] = mocksFrom ? [mocksFrom.runId, toArray(mocksFrom.blockIds), passed] - : [record.runId, passed, []] + : [ + record.runId, + passed.filter((blockId) => reached.has(blockId)), + passed.filter((blockId) => !reached.has(blockId)), + ] if (read.length > 0) { if (!issuedId(readFrom)) return null flags.push(` --mock-from ${shellArgument(readFrom)}`)