Skip to content

Commit 3c8357a

Browse files
committed
chore(workflow-code): simplify round 12 — one lock parse per apply, batched child reads, childSources on the per-apply loads
1 parent 6f11bca commit 3c8357a

10 files changed

Lines changed: 170 additions & 124 deletions

File tree

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

Lines changed: 35 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,10 @@ import {
3939
import { recordSourceRead } from '@/lib/workflows/application/source-analytics'
4040
import {
4141
type ChildResultsMemo,
42-
loadChildResults,
42+
loadChildGraphs,
43+
loadChildResultsFrom,
44+
type StoredGraphs,
45+
storedChildWorkflowIds,
4346
} from '@/lib/workflows/application/source-child-results'
4447
import type { WorkflowSourceDiagnostic } from '@/lib/workflows/application/source-error'
4548
import { buildSourceCatalog, storedCatalogTypes } from '@/lib/workflows/code/catalog/workspace'
@@ -237,6 +240,8 @@ interface LoadedSource {
237240
prefetched: PrefetchedStoredResources
238241
/** The child workflows read for this read, shared by the workflows a batched read prints. */
239242
childMemo: ChildResultsMemo
243+
/** The graphs of the workflows this one may call ({@link storedChildWorkflowIds}), by id. */
244+
childGraphs: StoredGraphs
240245
}
241246

242247
/**
@@ -260,19 +265,17 @@ async function printLoadedSource(
260265
{ organizationId: scope.workspaceOrganizationId, gate, prefetched, stored: loaded.stored },
261266
async ({ canonical, resources }, catalog) => {
262267
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
268+
const childResults = await loadChildResultsFrom(
269+
{
270+
workspaceId: scope.workspaceId,
271+
workspaceOrganizationId: scope.workspaceOrganizationId,
272+
gate,
273+
memo: loaded.childMemo,
274+
},
275+
calledWorkflowKeys(canonical.workflow),
276+
loaded.childGraphs,
277+
(key) => resources.toId('workflow', key)
278+
)
276279
const printed = printStoredSource({
277280
state,
278281
meta,
@@ -281,7 +284,7 @@ async function printLoadedSource(
281284
sourceMeta,
282285
functionCode,
283286
lockless: canonical,
284-
...(childResults ? { childResults } : {}),
287+
childResults,
285288
})
286289
assertFitsSourceLimits(printed, counts)
287290
return {
@@ -319,8 +322,14 @@ export const readWorkflowSource = defineAuthorizedWorkflowUseCase({
319322
operation: workflowOperations.readSource,
320323
resolveContext: resolvePrincipalWorkflowContext<GetWorkflowSourceInput>,
321324
async execute({ principal, input, context }): Promise<ReadWorkflowSourceResult> {
322-
const [stored, gate, sourceMeta, prefetched] = await Promise.all([
323-
loadStoredSource(context),
325+
const [{ stored, childGraphs }, gate, sourceMeta, prefetched] = await Promise.all([
326+
loadStoredSource(context).then(async (stored) => ({
327+
stored,
328+
childGraphs: await loadChildGraphs(
329+
context.workspaceId,
330+
storedChildWorkflowIds(Object.values(stored.state.blocks))
331+
),
332+
})),
324333
resolveCatalogGate(principal, context, { customBlockInputs: true }),
325334
readWorkflowSourceMeta(db, context.workflowId),
326335
prefetchStoredResources({
@@ -331,7 +340,7 @@ export const readWorkflowSource = defineAuthorizedWorkflowUseCase({
331340
}),
332341
])
333342
const read = await printLoadedSource(
334-
{ scope: context, stored, gate, sourceMeta, prefetched, childMemo: new Map() },
343+
{ scope: context, stored, gate, sourceMeta, prefetched, childMemo: new Map(), childGraphs },
335344
input.functionCode ?? 'files'
336345
)
337346
if (!input.plan) recordSourceRead(principal, context)
@@ -392,6 +401,13 @@ export const readWorkflowSources = defineAuthorizedWorkflowUseCase({
392401
input.workflowIds
393402
),
394403
])
404+
const childGraphs = await loadChildGraphs(
405+
workspaceId,
406+
[...graphs.values()].flatMap((loaded) =>
407+
storedChildWorkflowIds(Object.values(loaded.graph.blocks))
408+
),
409+
graphs
410+
)
395411
const childMemo: ChildResultsMemo = new Map()
396412
const printed = await mapWithConcurrency(
397413
input.workflowIds,
@@ -416,6 +432,7 @@ export const readWorkflowSources = defineAuthorizedWorkflowUseCase({
416432
sourceMeta: sourceMetas.get(workflowId) ?? null,
417433
prefetched: { ...prefetched, workflowId },
418434
childMemo,
435+
childGraphs,
419436
},
420437
'files'
421438
)

‎apps/sim/lib/workflows/application/source-child-results.ts‎

Lines changed: 86 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
type ResourceKeyResolver,
1515
} from '@sim/workflow-code'
1616
import { SOURCE_ENTRY_FILE } from '@sim/workflow-code/limits'
17+
import type { BlockState } from '@sim/workflow-types/workflow'
1718
import { type CatalogGate, withCatalogBlockScope } from '@/lib/catalog/application/context'
1819
import { loadWorkflowGraphs } from '@/lib/workflows/application/read-workflow-graph'
1920
import { buildSourceCatalog, storedCatalogTypes } from '@/lib/workflows/code/catalog/workspace'
@@ -28,17 +29,21 @@ type ChildFields = ChildResultFields | null
2829
*/
2930
export type ChildResultsMemo = Map<string, Promise<ChildFields>>
3031

32+
/**
33+
* The files of each workflow folder a workspace source apply writes, by key: a workflow calling
34+
* one is typed by the child's Response data as the folder holds it, as the directory's check
35+
* types it, not as stored.
36+
*/
37+
export type ChildSources = ReadonlyMap<string, Readonly<Record<string, string>>>
38+
3139
export interface ChildResultsScope {
3240
workspaceId: string
3341
workspaceOrganizationId: string | null
3442
/** The caller's catalog gate, which the children are compiled or canonicalized under. */
3543
gate: CatalogGate
3644
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>>>
45+
/** The folders the enclosing workspace source apply writes: such a child is read as submitted. */
46+
submitted?: ChildSources
4247
}
4348

4449
/**
@@ -67,6 +72,31 @@ function submittedFields(
6772
return workflow ? childResultFields(workflow, catalog) : null
6873
}
6974

75+
/** Stored workflow graphs by id, as `loadWorkflowGraphs` reads them. */
76+
export type StoredGraphs = Awaited<ReturnType<typeof loadWorkflowGraphs>>
77+
78+
/** The fields of a stored child workflow, canonicalized under its own source catalog. */
79+
function storedGraphFields(
80+
loaded: NonNullable<ReturnType<StoredGraphs['get']>>,
81+
scope: ChildResultsScope
82+
): ChildFields {
83+
const { blocks, edges, loops, parallels, variables } = loaded.graph
84+
const catalog = buildSourceCatalog({
85+
gate: scope.gate,
86+
organizationId: scope.workspaceOrganizationId,
87+
storedTypes: storedCatalogTypes(Object.values(blocks)),
88+
})
89+
const { workflow } = canonicalize(
90+
{ blocks, edges, loops, parallels, variables },
91+
{
92+
catalog,
93+
meta: { name: loaded.name, description: loaded.description ?? null },
94+
resources: UNRESOLVED,
95+
}
96+
)
97+
return childResultFields(workflow, catalog)
98+
}
99+
70100
/** The fields of each stored workflow `keys` name in the workspace, by key. */
71101
async function storedFields(
72102
keys: readonly string[],
@@ -84,29 +114,38 @@ async function storedFields(
84114
for (const key of keys) {
85115
const id = ids.get(key)
86116
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))
117+
fields.set(key, loaded ? storedGraphFields(loaded, scope) : null)
106118
}
107119
return fields
108120
}
109121

122+
/**
123+
* The ids of the workflows stored `blocks` may run as children (each `workflowId` value), for a
124+
* read to load their graphs with its own: a superset of the calls its canonical model names.
125+
*/
126+
export function storedChildWorkflowIds(blocks: Iterable<BlockState>): string[] {
127+
const ids = new Set<string>()
128+
for (const block of blocks) {
129+
const value = block.subBlocks?.workflowId?.value
130+
if (typeof value === 'string' && value !== '') ids.add(value)
131+
}
132+
return [...ids]
133+
}
134+
135+
/**
136+
* Loads the graphs of the workflows `ids` name that `loaded` lacks, in one read, and returns them
137+
* with `loaded`'s ({@link storedChildWorkflowIds}).
138+
*/
139+
export async function loadChildGraphs(
140+
workspaceId: string,
141+
ids: readonly string[],
142+
loaded: StoredGraphs = new Map()
143+
): Promise<StoredGraphs> {
144+
const missing = [...new Set(ids)].filter((id) => !loaded.has(id))
145+
if (missing.length === 0) return loaded
146+
return new Map([...loaded, ...(await loadWorkflowGraphs(workspaceId, missing))])
147+
}
148+
110149
/**
111150
* The typed result fields of each child workflow `keys` name that always responds, by key: a
112151
* child the enclosing apply submits as submitted, any other as its stored draft in the workspace
@@ -140,3 +179,26 @@ export async function loadChildResults(
140179
for (const [key, fields] of read) if (fields) results.set(key, fields)
141180
return results
142181
}
182+
183+
/**
184+
* {@link loadChildResults} for a read of stored workflows that loaded their children's graphs with
185+
* {@link loadChildGraphs} (`toId` names the workflow a key resolves to): a child read from there,
186+
* where one the workspace does not hold or holds archived is left out, so a read makes no query of
187+
* its own. A key that resolves to no workflow is read as {@link loadChildResults} reads it.
188+
*/
189+
export async function loadChildResultsFrom(
190+
scope: ChildResultsScope,
191+
keys: readonly string[],
192+
graphs: StoredGraphs,
193+
toId: (key: string) => string | null
194+
): Promise<Map<string, ChildResultFields>> {
195+
await withCatalogBlockScope(scope.gate, async () => {
196+
for (const key of keys) {
197+
const id = toId(key)
198+
if (id === null || scope.memo.has(key) || scope.submitted?.has(key)) continue
199+
const loaded = graphs.get(id)
200+
scope.memo.set(key, Promise.resolve(loaded ? storedGraphFields(loaded, scope) : null))
201+
}
202+
})
203+
return loadChildResults(scope, keys)
204+
}

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

Lines changed: 22 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import {
22
type CanonicalizeResult,
33
type CanonicalWorkflowMeta,
4-
type ChildResultFields,
54
calledWorkflowKeys,
65
canonicalizeUnderLock,
76
type Diagnostic,
@@ -37,26 +36,13 @@ export interface CompiledSubmission {
3736
* Parses the submitted lock and compiles the files against the live catalog and the stored graph
3837
* read under that lock, typing child calls' results by the fields of the children the compiled
3938
* 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).
39+
* source calling a child that responds is compiled again with those fields (the lock and the
40+
* stored graph are read once). Refuses a lock that does not parse, or a source that does not
41+
* compile (noting a catalog that moved since the read, which can explain the errors).
4342
*/
4443
export async function compileSubmission(
4544
input: SourceEvaluationInput
4645
): 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>
59-
): { refused: WorkflowSourceDiagnostic[] } | CompiledSubmission {
6046
const { catalog, files } = input
6147

6248
const parsedLock = parseWorkflowLock(input.lock)
@@ -65,9 +51,8 @@ function compileUnder(
6551
}
6652
const lock = parsedLock.lock
6753

68-
const { state } = input.stored
6954
const storedCanonical = canonicalizeUnderLock(
70-
state,
55+
input.stored.state,
7156
{ catalog, meta: input.stored.meta, resources: input.storedCanonical.resources },
7257
input.storedCanonical.canonical,
7358
lock
@@ -82,8 +67,25 @@ function compileUnder(
8267
...Object.keys(storedCanonical.identity.blocks),
8368
]),
8469
envNames: input.envNames,
85-
...(childResults ? { childResults } : {}),
8670
}
71+
const read = { lock, storedCanonical, compileInput }
72+
73+
const untyped = compileUnder(input, read)
74+
if ('refused' in untyped || !input.loadChildResults) return untyped
75+
const called = calledWorkflowKeys(untyped.compiledWorkflow)
76+
if (called.length === 0) return untyped
77+
const childResults = await input.loadChildResults(called)
78+
if (childResults.size === 0) return untyped
79+
return compileUnder(input, { ...read, compileInput: { ...compileInput, childResults } })
80+
}
81+
82+
/** Compiles the files under the lock and stored graph {@link compileSubmission} read. */
83+
function compileUnder(
84+
input: SourceEvaluationInput,
85+
read: Pick<CompiledSubmission, 'lock' | 'storedCanonical' | 'compileInput'>
86+
): { refused: WorkflowSourceDiagnostic[] } | CompiledSubmission {
87+
const { catalog, files } = input
88+
const { lock, storedCanonical, compileInput } = read
8789
const compiled = compileSource({ ...compileInput, stored: storedCanonical.workflow, lock })
8890
const compiledWorkflow = compiled.workflow
8991
if (!compiledWorkflow || hasErrors(compiled.diagnostics)) {

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

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,10 @@ 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'
18+
import type {
19+
ChildResultsMemo,
20+
ChildSources,
21+
} from '@/lib/workflows/application/source-child-results'
1922
import type { SourceScope } from '@/lib/workflows/application/source-pipeline/evaluate'
2023
import { buildSourceCatalog, storedCatalogTypes } from '@/lib/workflows/code/catalog/workspace'
2124
import { type StoredSource, storedSourceFingerprint } from '@/lib/workflows/code/print-stored'
@@ -76,6 +79,8 @@ export interface SourceLoads {
7679
envNames?: Promise<string[]>
7780
/** The child workflows read to type their callers' results (`loadChildResults`). */
7881
childResults?: ChildResultsMemo
82+
/** The workflow folders the workspace source apply writes, which its callers are typed by. */
83+
childSources?: ChildSources
7984
}
8085

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

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

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -42,11 +42,6 @@ interface SourceSubmission {
4242
lock: WorkflowLockV1
4343
/** Resources the enclosing workspace source apply creates or adopts first. */
4444
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>>>
5045
}
5146

5247
/**
@@ -275,7 +270,7 @@ export async function planSource(
275270
workspaceOrganizationId: scope.workspaceOrganizationId,
276271
gate: loaded.gate,
277272
memo: options.loads ? (options.loads.childResults ??= new Map()) : new Map(),
278-
...(submission.childSources ? { submitted: submission.childSources } : {}),
273+
...(options.loads?.childSources ? { submitted: options.loads.childSources } : {}),
279274
}
280275
const evaluation = await evaluateSource({
281276
principal,

0 commit comments

Comments
 (0)