Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/sim/executor/execution/block-executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -469,7 +469,7 @@ export class BlockExecutor {
stateOutput,
duration,
stateProvenance,
site !== undefined && sideEffects?.answeredWithPlaceholder(site) === true
site !== undefined && sideEffects?.answeredWithPlaceholder(site, stateOutput) === true
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
)

if (!isSentinel && blockLog) {
Expand Down
4 changes: 2 additions & 2 deletions apps/sim/executor/execution/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -468,9 +468,9 @@ export interface SideEffectPolicy {
answersBlock(block: SideEffectBlockSite): boolean
/**
* Whether the run has answered this block, or a call it made, with a placeholder (its mock is
* not one), so its output may hold made-up values.
* not one), or its `output` carries one it was handed, so the output may hold made-up values.
*/
answeredWithPlaceholder(block: SideEffectBlockSite): boolean
answeredWithPlaceholder(block: SideEffectBlockSite, output: unknown): boolean
/** The output answering a block that does not run: its mock, or a recorded placeholder. */
answerBlock(call: AnsweredBlockCall): Promise<NormalizedBlockOutput>
}
Expand Down
35 changes: 19 additions & 16 deletions apps/sim/lib/logs/execution/trace-spans/factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,14 +202,18 @@ function childDeploymentVersionOf(
}

/**
* The deployment version a workflow run as an Agent tool reported. Read only for
* `workflow_executor`, so another tool returning the same key records nothing.
* Moves the deployment version a workflow run as an Agent tool reported from its output onto the
* span, as a workflow block span has it. Trusted only when the raw tool name is
* `workflow_executor`: a streamed custom tool titled that way still carries its `custom_` prefix
* here, and the Agent drops the key from a non-streamed custom tool's result.
*/
function workflowToolVersion(
toolName: string,
function liftWorkflowToolVersion(
rawToolName: string | undefined,
output: Record<string, unknown> | undefined
): Pick<TraceSpan, 'childDeploymentVersionId'> {
return toolName === WORKFLOW_TOOL_ID ? childDeploymentVersionOf(output) : {}
): { output: Record<string, unknown> | undefined } & Pick<TraceSpan, 'childDeploymentVersionId'> {
const version = rawToolName === WORKFLOW_TOOL_ID ? childDeploymentVersionOf(output) : {}
if (!output || !version.childDeploymentVersionId) return { output }
return { output: omit(output, ['childDeploymentVersionId']), ...version }
}

/** Enriches a span with provider timing, cost, tokens, and model from block output. */
Expand Down Expand Up @@ -301,9 +305,8 @@ function buildChildrenFromTimeSegments(
const currentIndex = toolCallIndices.get(normalizedName) ?? 0
const match = callsForName[currentIndex]
toolCallIndices.set(normalizedName, currentIndex + 1)
const { output, handle } = liftChildTraceHandle(
normalizeTraceOutput(match?.result ?? match?.output)
)
const lifted = liftChildTraceHandle(normalizeTraceOutput(match?.result ?? match?.output))
const { output, ...version } = liftWorkflowToolVersion(segment.name, lifted.output)

const toolChild: TraceSpan = {
id: `${span.id}-segment-${index}`,
Expand All @@ -315,8 +318,8 @@ function buildChildrenFromTimeSegments(
status: match?.error || segment.errorMessage ? 'error' : 'success',
input: match?.arguments ?? match?.input,
output: match?.error ? { error: match.error, ...output } : output,
...handle,
...workflowToolVersion(normalizedName, output),
...lifted.handle,
...version,
}
if (segment.toolCallId) toolChild.toolCallId = segment.toolCallId
if (segment.errorType) toolChild.errorType = segment.errorType
Expand Down Expand Up @@ -383,20 +386,20 @@ function buildChildrenFromToolCalls(span: TraceSpan, log: ValidBlockLog): TraceS
return toolCalls.map((tc, index) => {
const startTime = tc.startTime ?? log.startedAt
const endTime = tc.endTime ?? log.endedAt
const { output, handle } = liftChildTraceHandle(normalizeTraceOutput(tc.result ?? tc.output))
const name = stripCustomToolPrefix(tc.name ?? 'unnamed-tool')
const lifted = liftChildTraceHandle(normalizeTraceOutput(tc.result ?? tc.output))
const { output, ...version } = liftWorkflowToolVersion(tc.name, lifted.output)
return {
id: `${span.id}-tool-${index}`,
name,
name: stripCustomToolPrefix(tc.name ?? 'unnamed-tool'),
type: 'tool',
duration: tc.duration ?? 0,
startTime,
endTime,
status: tc.error ? 'error' : 'success',
input: tc.arguments ?? tc.input,
output: tc.error ? { error: tc.error, ...output } : output,
...handle,
...workflowToolVersion(name, output),
...lifted.handle,
...version,
}
})
}
Expand Down
15 changes: 15 additions & 0 deletions apps/sim/lib/logs/execution/trace-spans/trace-spans.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1747,6 +1747,21 @@ describe('child deployment version on spans', () => {
)

expect(toolSpan?.childDeploymentVersionId).toBe('dv-9')
expect(toolSpan?.output).not.toHaveProperty('childDeploymentVersionId')
}
)

it.each([true, false])(
'ignores the key on a streamed custom tool titled like the workflow tool (time segments: %s)',
(withSegments) => {
const toolSpan = agentToolSpan(
'custom_workflow_executor',
{ childDeploymentVersionId: 'forged' },
withSegments
)

expect(toolSpan).toBeDefined()
expect(toolSpan?.childDeploymentVersionId).toBeUndefined()
}
)

Expand Down
9 changes: 6 additions & 3 deletions apps/sim/lib/mcp/output-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export function readMcpToolOutputSchema(value: unknown): McpToolSchema | undefin
}

/** Reduce a declared JSON Schema to the structure a block output can declare. */
function toMcpToolOutputShape(schema: McpToolSchema): McpToolOutputShape {
export function toMcpToolOutputShape(schema: McpToolSchema): McpToolOutputShape {
const budget = { nodes: MAX_SHAPE_NODES }
return reduceNode(schema, 0, budget)
}
Expand Down Expand Up @@ -107,12 +107,15 @@ function reduceNode(node: unknown, depth: number, budget: { nodes: number }): Mc
}
}

/** `anyOf: [X, {type: 'null'}]`, the common encoding of an optional field, reads as X. */
/**
* `anyOf: [X, {type: 'null'}]`, the common encoding of an optional field, reads as X, as does a
* union of X alone.
*/
function singleNonNullVariant(node: Record<string, unknown>): unknown {
const variants = Array.isArray(node.anyOf) ? node.anyOf : node.oneOf
if (!Array.isArray(variants)) return undefined
const nonNull = variants.filter((variant) => !(isRecordLike(variant) && variant.type === 'null'))
return nonNull.length === 1 && nonNull.length < variants.length ? nonNull[0] : undefined
return nonNull.length === 1 ? nonNull[0] : undefined
}

function declaredType(node: Record<string, unknown>): string | undefined {
Expand Down
31 changes: 30 additions & 1 deletion apps/sim/lib/workflows/application/dry-run.integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2285,7 +2285,9 @@ return created.id.toString()`

expect(result.status).toBe('failed')
expect(JSON.stringify(result.error)).toContain(
"1 network write this code made got an empty stubbed response; --allow 'code' sends them"
JSON.stringify(
'1 network write this code made got an empty stubbed response; allowing block "code" sends them'
).slice(1, -1)
)
})

Expand Down Expand Up @@ -2888,6 +2890,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('refuse a block whose output carries a placeholder it was handed', async () => {
const tableId = await createTable()
const fixture = lookupThenSave(tableId, 'a@b.co')
const workflowId = await saveWorkflow(
graph(
[
...Object.values(fixture.state.blocks),
block('format', 'function', { language: 'javascript', code: 'return { saved: <save> }' }),
],
[
['start', 'lookup'],
['lookup', 'save'],
['save', 'format'],
]
).state
)
const source = await run(workflowId, { dry: true })
expect(source.status, JSON.stringify(source.error)).toBe('completed')

await expect(
run(workflowId, { dry: true, mocksFrom: { runId: source.executionId, blocks: ['format'] } })
).rejects.toMatchObject({
...validationError,
message: expect.stringContaining('with a placeholder'),
})
})

it('refuse a block a test run logged before placeholders were recorded did not mock', async () => {
const tableId = await createTable()
const workflowId = await saveWorkflow(lookupThenSave(tableId, 'a@b.co').state)
Expand Down
1 change: 1 addition & 0 deletions apps/sim/lib/workflows/dry-run/placeholders.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ describe('a dry run’s placeholder tokens', () => {
['quoted in free text', 'Re: dry_run_title_2'],
['as a number', 900_000_003],
['as digits in a URL', 'https://api.github.com/repos/o/r/issues/900000003'],
['as zero-padded digits', 'ticket 0900000003'],
])('are found %s', (_, sent) => {
expect(registered().occursIn({ sent })).toBe(true)
})
Expand Down
12 changes: 7 additions & 5 deletions apps/sim/lib/workflows/dry-run/placeholders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,13 @@ const TOKEN_PREFIX = 'dry_run_'
const TOKEN_RUN = /^[a-z0-9_]+/
/** Where a token can end inside a run: after a whole `_<digits>`. */
const TOKEN_END = /_\d+/g
const DIGIT_RUN = /\d+/g
/** Digits a placeholder number has: every one is above {@link DRY_RUN_NUMBER_BASE}. */
const PLACEHOLDER_NUMBER_DIGITS = String(DRY_RUN_NUMBER_BASE).length
/**
* A whole run of that many digits, zero-padded or not (`0900000003` is still the number), so a long
* string is scanned without listing every run of digits it holds.
*/
const PLACEHOLDER_NUMBER_RUN = new RegExp(`(?<!\\d)0*\\d{${PLACEHOLDER_NUMBER_DIGITS}}(?!\\d)`, 'g')
/** Longest token a scan reads at one `dry_run_`. */
const MAX_TOKEN_LENGTH = 256

Expand Down Expand Up @@ -115,10 +119,8 @@ export class PlaceholderTokens {
if (this.tokens.has(token)) return true
}
if (this.numbers.size === 0) return false
for (const digits of value.match(DIGIT_RUN) ?? []) {
if (digits.length >= PLACEHOLDER_NUMBER_DIGITS && this.numbers.has(Number(digits))) {
return true
}
for (const [digits] of value.matchAll(PLACEHOLDER_NUMBER_RUN)) {
if (this.numbers.has(Number(digits))) return true
}
return false
})
Expand Down
56 changes: 18 additions & 38 deletions apps/sim/lib/workflows/dry-run/samples.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { isPlainRecord } from '@sim/utils/object'
import {
type McpToolOutputShape,
readMcpToolOutputSchema,
toMcpToolOutputShape,
} from '@/lib/mcp/output-schema'
import { getEffectiveBlockOutputs } from '@/lib/workflows/blocks/outputs'
import { generateMockPayloadFromOutputsDefinition } from '@/lib/workflows/triggers/mock-payload'
import { isRunControlledOutputField } from '@/executor/utils/mock-output'
Expand Down Expand Up @@ -129,55 +134,29 @@ function overlayFields(
)
}

/** Nesting of a discovered JSON Schema an output declaration follows. */
const MAX_SCHEMA_DEPTH = 10

/**
* A discovered JSON Schema (an MCP tool's `outputSchema`) as an output declaration the sample
* reads: `integer` is a `number`, a union reads as its first non-null member, and a field whose
* type cannot be told is left out rather than sampled as a guess.
* A discovered output schema (an MCP tool's `outputSchema`), reduced within the same node and
* depth budget a block's saved MCP output snapshot uses, as an output declaration the sample
* reads. A field whose type cannot be told is left out rather than sampled as a guess.
*/
function outputFromJsonSchema(schema: unknown, depth = 0): Record<string, unknown> | undefined {
if (!isPlainRecord(schema) || depth > MAX_SCHEMA_DEPTH) return undefined
const variants = Array.isArray(schema.anyOf) ? schema.anyOf : schema.oneOf
if (Array.isArray(variants)) {
const member = variants.find((variant) => !(isPlainRecord(variant) && variant.type === 'null'))
return outputFromJsonSchema(member, depth + 1)
}
const declared = Array.isArray(schema.type)
? schema.type.find((type) => type !== 'null')
: schema.type
const type =
typeof declared === 'string'
? declared
: isPlainRecord(schema.properties)
? 'object'
: schema.items !== undefined
? 'array'
: undefined
switch (type) {
function outputFromShape(shape: McpToolOutputShape): Record<string, unknown> | undefined {
switch (shape.type) {
case 'object': {
const properties: Record<string, unknown> = {}
for (const [field, child] of Object.entries(
isPlainRecord(schema.properties) ? schema.properties : {}
)) {
const output = outputFromJsonSchema(child, depth + 1)
for (const [field, child] of Object.entries(shape.properties ?? {})) {
const output = outputFromShape(child)
if (output) properties[field] = output
}
return { type: 'object', properties }
}
case 'array': {
const items = outputFromJsonSchema(schema.items, depth + 1)
const items = shape.items && outputFromShape(shape.items)
return items ? { type: 'array', items } : undefined
}
case 'integer':
case 'number':
return { type: 'number' }
case 'string':
case 'boolean':
return { type }
default:
case 'any':
return undefined
default:
return { type: shape.type }
}
}

Expand All @@ -196,7 +175,8 @@ export function sampleToolOutput(
if (!declared && !discovered) return {}
const outputs: Record<string, unknown> = { ...declared }
for (const [field, schema] of Object.entries(discovered ?? {})) {
const output = outputFromJsonSchema(schema)
const objectSchema = readMcpToolOutputSchema(schema)
const output = objectSchema && outputFromShape(toMcpToolOutputShape(objectSchema))
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
if (output) outputs[field] = output
}
const sample = withEmptyFileLists(
Expand Down
4 changes: 2 additions & 2 deletions apps/sim/lib/workflows/dry-run/side-effects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -341,8 +341,8 @@ export class WriteStubPolicy implements SideEffectPolicy {
return false
}

answeredWithPlaceholder(block: SideEffectBlockSite): boolean {
return this.answeredSites.has(overrideKey(block))
answeredWithPlaceholder(block: SideEffectBlockSite, output: unknown): boolean {
return this.answeredSites.has(overrideKey(block)) || this.placeholders.occursIn(output)
}

async answerBlock(call: AnsweredBlockCall): Promise<NormalizedBlockOutput> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ import { GET as listMembers } from '@/app/api/v2/workspaces/[workspaceId]/member
import { addGroupMember, insertScimGroup } from '@/ee/scim/lib/repository/groups'

/** Directory provisioning on a self-hosted deployment, so a locked SCIM member is refused. */

vi.mock('@/lib/core/config/env-flags', () => ({ ...envFlagsMock, isScimEnabled: true }))

const USER_NAMES = [
Expand Down
8 changes: 7 additions & 1 deletion apps/sim/tools/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7550,6 +7550,7 @@ describe('MCP Tool Execution', () => {
total: { type: 'integer' },
label: { type: ['null', 'string'] },
owner: { anyOf: [{ type: 'null' }, { type: 'string' }] },
alias: { oneOf: [{ type: 'string' }] },
untyped: {},
},
},
Expand All @@ -7569,7 +7570,12 @@ describe('MCP Tool Execution', () => {
)

expect(held.output).toEqual({
structuredContent: { total: 900_000_001, label: 'dry_run_label_1', owner: 'dry_run_owner_1' },
structuredContent: {
total: 900_000_001,
label: 'dry_run_label_1',
owner: 'dry_run_owner_1',
alias: 'dry_run_alias_1',
},
})
expect(dryRun.summary().stubbed).toMatchObject([
{ tool: 'mcp-123-count_files', reason: 'mcp-read-only' },
Expand Down
2 changes: 1 addition & 1 deletion apps/sim/tools/side-effects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -581,6 +581,6 @@ export function codeNetworkFor(input: {
failureHint: () =>
stubbed === 0 || !site.blockName
? null
: `Dry run: ${stubbed} network write${stubbed === 1 ? '' : 's'} this code made got an empty stubbed response; --allow '${site.blockName}' sends them.`,
: `Dry run: ${stubbed} network write${stubbed === 1 ? '' : 's'} this code made got an empty stubbed response; allowing block ${JSON.stringify(site.blockName)} sends them.`,
}
}
Loading