Skip to content

Commit 8df79b0

Browse files
committed
improvement(workflow-code): type a child call's result.data fields by the child's Response body
A parent reading <call.result.data.<field>> of a child workflow that responds on every run had no declared type, so a JSON field stored it bare with W_JSON_REF_UNTYPED and every such edit paid an extra check cycle. compileWorkflow and printWorkflow now take childResults (child workflow key -> typed top-level fields of its Response data, from childResultFields), so compile and print type the reference the same way: a text field is stored quoted and prints bare, a typed one is stored and printed bare. - CLI: a check in a workspace directory reads the fields from the workflows it already compiles. Block digests for .sim/stored-edges.json stay untyped, so a printed block a child types does not count as edited. - Server: every source apply, dry run and get reads the fields of the children the workflow calls. A workspace apply reads a child it submits from its folder, and any other child from its stored draft in the workspace (loadChildResults, once per request). A single-workflow apply or get reads the stored children, so a workspace folder applied on its own stores what a workspace apply stores.
1 parent 927594b commit 8df79b0

24 files changed

Lines changed: 855 additions & 45 deletions

File tree

‎apps/sim/lib/workflows/application/read-workflow-source.ts‎

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { mapWithConcurrency } from '@sim/utils/concurrency'
44
import { compareStrings } from '@sim/utils/string'
55
import {
66
type CanonicalWorkflow,
7+
calledWorkflowKeys,
78
type Diagnostic,
89
type SourceBase,
910
type SourceFingerprint,
@@ -36,6 +37,10 @@ import {
3637
loadWorkflowGraphs,
3738
} from '@/lib/workflows/application/read-workflow-graph'
3839
import { recordSourceRead } from '@/lib/workflows/application/source-analytics'
40+
import {
41+
type ChildResultsMemo,
42+
loadChildResults,
43+
} from '@/lib/workflows/application/source-child-results'
3944
import type { WorkflowSourceDiagnostic } from '@/lib/workflows/application/source-error'
4045
import { buildSourceCatalog, storedCatalogTypes } from '@/lib/workflows/code/catalog/workspace'
4146
import {
@@ -230,11 +235,14 @@ interface LoadedSource {
230235
gate: CatalogGate
231236
sourceMeta: WorkflowSourceMetaV1 | null
232237
prefetched: PrefetchedStoredResources
238+
/** The child workflows read for this read, shared by the workflows a batched read prints. */
239+
childMemo: ChildResultsMemo
233240
}
234241

235242
/**
236243
* Prints a loaded workflow as source: builds its catalog, canonicalizes the stored graph with its
237-
* resource keys and prints it with its source meta, refusing one over `SOURCE_LIMITS`.
244+
* resource keys and prints it with its source meta and the result fields of the children it calls
245+
* (as an apply of the printed source types them), refusing one over `SOURCE_LIMITS`.
238246
*/
239247
async function printLoadedSource(
240248
loaded: LoadedSource,
@@ -252,6 +260,19 @@ async function printLoadedSource(
252260
{ organizationId: scope.workspaceOrganizationId, gate, prefetched, stored: loaded.stored },
253261
async ({ canonical, resources }, catalog) => {
254262
const canonicalHash = storedCanonicalHash(canonical, resources)
263+
const called = calledWorkflowKeys(canonical.workflow)
264+
const childResults =
265+
called.length > 0
266+
? await loadChildResults(
267+
{
268+
workspaceId: scope.workspaceId,
269+
workspaceOrganizationId: scope.workspaceOrganizationId,
270+
gate,
271+
memo: loaded.childMemo,
272+
},
273+
called
274+
)
275+
: undefined
255276
const printed = printStoredSource({
256277
state,
257278
meta,
@@ -260,6 +281,7 @@ async function printLoadedSource(
260281
sourceMeta,
261282
functionCode,
262283
lockless: canonical,
284+
...(childResults ? { childResults } : {}),
263285
})
264286
assertFitsSourceLimits(printed, counts)
265287
return {
@@ -309,7 +331,7 @@ export const readWorkflowSource = defineAuthorizedWorkflowUseCase({
309331
}),
310332
])
311333
const read = await printLoadedSource(
312-
{ scope: context, stored, gate, sourceMeta, prefetched },
334+
{ scope: context, stored, gate, sourceMeta, prefetched, childMemo: new Map() },
313335
input.functionCode ?? 'files'
314336
)
315337
if (!input.plan) recordSourceRead(principal, context)
@@ -370,6 +392,7 @@ export const readWorkflowSources = defineAuthorizedWorkflowUseCase({
370392
input.workflowIds
371393
),
372394
])
395+
const childMemo: ChildResultsMemo = new Map()
373396
const printed = await mapWithConcurrency(
374397
input.workflowIds,
375398
PRINT_CONCURRENCY,
@@ -392,6 +415,7 @@ export const readWorkflowSources = defineAuthorizedWorkflowUseCase({
392415
gate,
393416
sourceMeta: sourceMetas.get(workflowId) ?? null,
394417
prefetched: { ...prefetched, workflowId },
418+
childMemo,
395419
},
396420
'files'
397421
)
Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
/**
2+
* How the server types a child workflow call's `<call.result.data.<field>>` in a JSON field: by
3+
* the fields the child's Response data holds (`childResultFields`), read from the child's draft
4+
* as stored, or as the workspace source apply that holds the call submits it. Every source compile
5+
* and print of a workflow goes through the same reading, so a get prints a reference in the form
6+
* the next apply stores again, and a workspace directory's check (which reads the children from
7+
* the directory) agrees with both.
8+
*/
9+
import {
10+
type ChildResultFields,
11+
canonicalize,
12+
childResultFields,
13+
compileWorkflow,
14+
type ResourceKeyResolver,
15+
} from '@sim/workflow-code'
16+
import { SOURCE_ENTRY_FILE } from '@sim/workflow-code/limits'
17+
import { type CatalogGate, withCatalogBlockScope } from '@/lib/catalog/application/context'
18+
import { loadWorkflowGraphs } from '@/lib/workflows/application/read-workflow-graph'
19+
import { buildSourceCatalog, storedCatalogTypes } from '@/lib/workflows/code/catalog/workspace'
20+
import { resolveIds } from '@/lib/workspaces/resource-keys'
21+
22+
/** A child's typed result fields, or `null` when it can end without responding or is unreadable. */
23+
type ChildFields = ChildResultFields | null
24+
25+
/**
26+
* One request's readings of child workflows by key, each read at most once: a workspace apply
27+
* shares one across every workflow it evaluates.
28+
*/
29+
export type ChildResultsMemo = Map<string, Promise<ChildFields>>
30+
31+
export interface ChildResultsScope {
32+
workspaceId: string
33+
workspaceOrganizationId: string | null
34+
/** The caller's catalog gate, which the children are compiled or canonicalized under. */
35+
gate: CatalogGate
36+
memo: ChildResultsMemo
37+
/**
38+
* The files of each workflow folder the enclosing workspace source apply writes, by key: such a
39+
* child is read as submitted, not as stored.
40+
*/
41+
submitted?: ReadonlyMap<string, Readonly<Record<string, string>>>
42+
}
43+
44+
/**
45+
* Canonicalize reads resources only to lift ids to keys, which no Response field's type depends
46+
* on, so the children are read without the workspace's resource keys.
47+
*/
48+
const UNRESOLVED: ResourceKeyResolver = { toKey: () => null, toId: () => null }
49+
50+
/** The fields of a submitted folder, compiled on its own as the directory's check compiles it. */
51+
function submittedFields(
52+
files: Readonly<Record<string, string>>,
53+
scope: ChildResultsScope
54+
): ChildFields {
55+
const entry = files[SOURCE_ENTRY_FILE]
56+
if (entry === undefined) return null
57+
const catalog = buildSourceCatalog({
58+
gate: scope.gate,
59+
organizationId: scope.workspaceOrganizationId,
60+
})
61+
const { workflow } = compileWorkflow({
62+
entry: { path: SOURCE_ENTRY_FILE, text: entry },
63+
files: new Map(Object.entries(files).filter(([path]) => path !== SOURCE_ENTRY_FILE)),
64+
catalog,
65+
sdkMajor: catalog.sdkMajor,
66+
})
67+
return workflow ? childResultFields(workflow, catalog) : null
68+
}
69+
70+
/** The fields of each stored workflow `keys` name in the workspace, by key. */
71+
async function storedFields(
72+
keys: readonly string[],
73+
scope: ChildResultsScope
74+
): Promise<Map<string, ChildFields>> {
75+
const ids =
76+
(
77+
await resolveIds(
78+
scope.workspaceId,
79+
keys.map((key) => ({ kind: 'workflow' as const, key }))
80+
)
81+
).get('workflow') ?? new Map<string, string>()
82+
const graphs = await loadWorkflowGraphs(scope.workspaceId, [...ids.values()])
83+
const fields = new Map<string, ChildFields>()
84+
for (const key of keys) {
85+
const id = ids.get(key)
86+
const loaded = id === undefined ? undefined : graphs.get(id)
87+
if (!loaded) {
88+
fields.set(key, null)
89+
continue
90+
}
91+
const { blocks, edges, loops, parallels, variables } = loaded.graph
92+
const catalog = buildSourceCatalog({
93+
gate: scope.gate,
94+
organizationId: scope.workspaceOrganizationId,
95+
storedTypes: storedCatalogTypes(Object.values(blocks)),
96+
})
97+
const { workflow } = canonicalize(
98+
{ blocks, edges, loops, parallels, variables },
99+
{
100+
catalog,
101+
meta: { name: loaded.name, description: loaded.description ?? null },
102+
resources: UNRESOLVED,
103+
}
104+
)
105+
fields.set(key, childResultFields(workflow, catalog))
106+
}
107+
return fields
108+
}
109+
110+
/**
111+
* The typed result fields of each child workflow `keys` name that always responds, by key: a
112+
* child the enclosing apply submits as submitted, any other as its stored draft in the workspace
113+
* (one the workspace does not hold, or holds archived, is left out). Each key is read once per
114+
* `scope.memo`.
115+
*/
116+
export async function loadChildResults(
117+
scope: ChildResultsScope,
118+
keys: readonly string[]
119+
): Promise<Map<string, ChildResultFields>> {
120+
const unread = keys.filter((key) => !scope.memo.has(key))
121+
const stored = unread.filter((key) => !scope.submitted?.has(key))
122+
if (unread.length > 0) {
123+
const reading = withCatalogBlockScope(scope.gate, async () => {
124+
const fields = stored.length > 0 ? await storedFields(stored, scope) : new Map()
125+
for (const key of unread) {
126+
const files = scope.submitted?.get(key)
127+
if (files) fields.set(key, submittedFields(files, scope))
128+
}
129+
return fields
130+
})
131+
for (const key of unread) {
132+
scope.memo.set(
133+
key,
134+
reading.then((fields) => fields.get(key) ?? null)
135+
)
136+
}
137+
}
138+
const read = await Promise.all(keys.map(async (key) => [key, await scope.memo.get(key)] as const))
139+
const results = new Map<string, ChildResultFields>()
140+
for (const [key, fields] of read) if (fields) results.set(key, fields)
141+
return results
142+
}

‎apps/sim/lib/workflows/application/source-pipeline/evaluate/compile.ts‎

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import {
22
type CanonicalizeResult,
33
type CanonicalWorkflowMeta,
4+
type ChildResultFields,
5+
calledWorkflowKeys,
46
canonicalizeUnderLock,
57
type Diagnostic,
68
parseWorkflowLock,
@@ -33,11 +35,27 @@ export interface CompiledSubmission {
3335

3436
/**
3537
* Parses the submitted lock and compiles the files against the live catalog and the stored graph
36-
* read under that lock. Refuses a lock that does not parse, or a source that does not compile
37-
* (noting a catalog that moved since the read, which can explain the errors).
38+
* read under that lock, typing child calls' results by the fields of the children the compiled
39+
* source calls (`input.loadChildResults`): a compile names its calls only once it has run, so a
40+
* source calling a child that responds is compiled again with those fields. Refuses a lock that
41+
* does not parse, or a source that does not compile (noting a catalog that moved since the read,
42+
* which can explain the errors).
3843
*/
39-
export function compileSubmission(
44+
export async function compileSubmission(
4045
input: SourceEvaluationInput
46+
): Promise<{ refused: WorkflowSourceDiagnostic[] } | CompiledSubmission> {
47+
const untyped = compileUnder(input)
48+
if ('refused' in untyped || !input.loadChildResults) return untyped
49+
const called = calledWorkflowKeys(untyped.compiledWorkflow)
50+
if (called.length === 0) return untyped
51+
const childResults = await input.loadChildResults(called)
52+
return childResults.size === 0 ? untyped : compileUnder(input, childResults)
53+
}
54+
55+
/** {@link compileSubmission} with child calls' results typed by `childResults`. */
56+
function compileUnder(
57+
input: SourceEvaluationInput,
58+
childResults?: ReadonlyMap<string, ChildResultFields>
4159
): { refused: WorkflowSourceDiagnostic[] } | CompiledSubmission {
4260
const { catalog, files } = input
4361

@@ -64,6 +82,7 @@ export function compileSubmission(
6482
...Object.keys(storedCanonical.identity.blocks),
6583
]),
6684
envNames: input.envNames,
85+
...(childResults ? { childResults } : {}),
6786
}
6887
const compiled = compileSource({ ...compileInput, stored: storedCanonical.workflow, lock })
6988
const compiledWorkflow = compiled.workflow

‎apps/sim/lib/workflows/application/source-pipeline/evaluate/finalize.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -329,6 +329,9 @@ export async function finalizePlan(
329329
resources: resolved.resources,
330330
references: compiledKeys,
331331
envReferences: compiled.envReferences,
332+
...(submission.compileInput.childResults
333+
? { childResults: submission.compileInput.childResults }
334+
: {}),
332335
},
333336
}
334337
}

‎apps/sim/lib/workflows/application/source-pipeline/evaluate/run.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import type {
1616
* in the submitted text, or the plan the write stores.
1717
*/
1818
export async function evaluateSource(input: SourceEvaluationInput): Promise<SourceEvaluation> {
19-
const submission = compileSubmission(input)
19+
const submission = await compileSubmission(input)
2020
if ('refused' in submission) return { refused: submission.refused }
2121
const resolved = await resolveSubmission(input, submission)
2222
if ('refused' in resolved) return resolved

‎apps/sim/lib/workflows/application/source-pipeline/evaluate/types.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import type {
33
BlockCatalog,
44
CanonicalWorkflow,
55
CanonicalWorkflowMeta,
6+
ChildResultFields,
67
LockIdentity,
78
ResourceKeyResolver,
89
ResourceKind,
@@ -62,6 +63,12 @@ export interface SourceEvaluationInput {
6263
* created in the same apply resolves instead of failing `E_MAT_UNKNOWN_RESOURCE`.
6364
*/
6465
pendingResources?: readonly PendingResource[]
66+
/**
67+
* Reads the typed result fields of the child workflows the source calls, by key
68+
* (`loadChildResults`), which type a call's `<call.result.data.<field>>`. Absent, those
69+
* references are untyped.
70+
*/
71+
loadChildResults?: (keys: readonly string[]) => Promise<ReadonlyMap<string, ChildResultFields>>
6572
}
6673

6774
/**
@@ -128,6 +135,8 @@ export interface SourcePlan {
128135
references: SourceReference[]
129136
/** Every env name the submitted source reads, as the compiler read it. */
130137
envReferences: string[]
138+
/** The child result fields the compile typed with, which every print of the plan types with. */
139+
childResults?: ReadonlyMap<string, ChildResultFields>
131140
}
132141

133142
/** What the submitted source references, as the compiler read it. */

‎apps/sim/lib/workflows/application/source-pipeline/load.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
} from '@/lib/catalog/application/context'
1616
import type { ActiveWorkflowApplicationContext } from '@/lib/workflows/application/context'
1717
import { loadStoredSource } from '@/lib/workflows/application/read-workflow-source'
18+
import type { ChildResultsMemo } from '@/lib/workflows/application/source-child-results'
1819
import type { SourceScope } from '@/lib/workflows/application/source-pipeline/evaluate'
1920
import { buildSourceCatalog, storedCatalogTypes } from '@/lib/workflows/code/catalog/workspace'
2021
import { type StoredSource, storedSourceFingerprint } from '@/lib/workflows/code/print-stored'
@@ -73,6 +74,8 @@ export type SourceTarget =
7374
export interface SourceLoads {
7475
catalogGate?: Promise<CatalogGate>
7576
envNames?: Promise<string[]>
77+
/** The child workflows read to type their callers' results (`loadChildResults`). */
78+
childResults?: ChildResultsMemo
7679
}
7780

7881
/** Everything a plan reads before it evaluates: the stored draft, its catalog and fingerprint. */

‎apps/sim/lib/workflows/application/source-pipeline/outcome.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@ export function printPlanned(
114114
identity: plan.identity,
115115
codeFiles,
116116
...(lockless ? { lockless } : {}),
117+
...(plan.childResults ? { childResults: plan.childResults } : {}),
117118
})
118119
}
119120

‎apps/sim/lib/workflows/application/source-pipeline/plan.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import type {
99
import { diagnostic } from '@sim/workflow-code/diagnostics'
1010
import { isEqual } from 'es-toolkit'
1111
import { withCatalogBlockScope } from '@/lib/catalog/application/context'
12+
import { loadChildResults } from '@/lib/workflows/application/source-child-results'
1213
import { assertCreateNameFree } from '@/lib/workflows/application/source-commit'
1314
import { emptyDiffSummary, type SourceDiffSummary } from '@/lib/workflows/application/source-diff'
1415
import {
@@ -41,6 +42,11 @@ interface SourceSubmission {
4142
lock: WorkflowLockV1
4243
/** Resources the enclosing workspace source apply creates or adopts first. */
4344
pendingResources?: readonly PendingResource[]
45+
/**
46+
* The files of each workflow folder the enclosing workspace source apply writes, by key: a child
47+
* the source calls is typed as submitted there, not as stored.
48+
*/
49+
childSources?: ReadonlyMap<string, Readonly<Record<string, string>>>
4450
}
4551

4652
/**
@@ -264,6 +270,13 @@ export async function planSource(
264270
})
265271
}
266272

273+
const childScope = {
274+
workspaceId: scope.workspaceId,
275+
workspaceOrganizationId: scope.workspaceOrganizationId,
276+
gate: loaded.gate,
277+
memo: options.loads ? (options.loads.childResults ??= new Map()) : new Map(),
278+
...(submission.childSources ? { submitted: submission.childSources } : {}),
279+
}
267280
const evaluation = await evaluateSource({
268281
principal,
269282
scope,
@@ -276,6 +289,7 @@ export async function planSource(
276289
files: submission.files,
277290
lock: submission.lock,
278291
...(submission.pendingResources ? { pendingResources: submission.pendingResources } : {}),
292+
loadChildResults: (keys) => loadChildResults(childScope, keys),
279293
...(target.kind === 'existing'
280294
? { base: target.base, allowDelete: target.allowDelete }
281295
: { create: target.create }),

0 commit comments

Comments
 (0)