Skip to content

Commit 69ad970

Browse files
committed
fix(workflow-code): type child results through chains and stored() children, the same on CLI and server
- An offline compile (storedUnread) leaves stored() on a block the lock binds unread instead of refusing it, so a child holding a secret still compiles and types its callers; the server compiles a submitted child folder with its lock through the same folderCompileInput. - resolveChildResults types each workflow's Response fields by its callees' fields, callees first (strongly connected components; a call within a cycle stays untyped), shared by the workspace check, the stored-edges records, the apply and the read paths. - The stored read lifts a child's own calls to keys, so a forwarded field is typed as the compile types it. - The primers say source commands refuse a -w naming another workspace.
1 parent 16ff93a commit 69ad970

15 files changed

Lines changed: 733 additions & 135 deletions

File tree

Lines changed: 132 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,29 @@
11
/**
22
* How the server types a child workflow call's `<call.result.data.<field>>` in a JSON field: by
33
* 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.
4+
* as stored, or as the workspace source apply that holds the call submits it, each typed in turn
5+
* by the workflows it calls (`resolveChildResults`). Every source compile and print of a workflow
6+
* goes through the same reading, so a get prints a reference in the form the next apply stores
7+
* again, and a workspace directory's check (which reads the children from the directory the same
8+
* way) agrees with both.
89
*/
910
import {
1011
type ChildResultFields,
12+
type ChildResultNode,
1113
canonicalize,
12-
childResultFields,
13-
compileWorkflow,
14+
canonicalResultNode,
15+
compiledResultNode,
16+
folderCompileInput,
17+
parseWorkflowLock,
1418
type ResourceKeyResolver,
19+
resolveChildResults,
1520
} from '@sim/workflow-code'
1621
import { SOURCE_ENTRY_FILE } from '@sim/workflow-code/limits'
1722
import type { BlockState } from '@sim/workflow-types/workflow'
1823
import { type CatalogGate, withCatalogBlockScope } from '@/lib/catalog/application/context'
1924
import { loadWorkflowGraphs } from '@/lib/workflows/application/read-workflow-graph'
2025
import { buildSourceCatalog, storedCatalogTypes } from '@/lib/workflows/code/catalog/workspace'
21-
import { resolveIds } from '@/lib/workspaces/resource-keys'
26+
import { resolveIds, resolveKeys } from '@/lib/workspaces/resource-keys'
2227

2328
/** A child's typed result fields, or `null` when it can end without responding or is unreadable. */
2429
type ChildFields = ChildResultFields | null
@@ -29,12 +34,18 @@ type ChildFields = ChildResultFields | null
2934
*/
3035
export type ChildResultsMemo = Map<string, Promise<ChildFields>>
3136

37+
/** A workflow folder as a workspace source apply submits it: its files and `.sim/lock.json`. */
38+
interface ChildSource {
39+
files: Readonly<Record<string, string>>
40+
lock: unknown
41+
}
42+
3243
/**
33-
* The files of each workflow folder a workspace source apply writes, by key: a workflow calling
44+
* The workflow folders a workspace source apply writes with files, by key: a workflow calling
3445
* one is typed by the child's Response data as the folder holds it, as the directory's check
3546
* types it, not as stored.
3647
*/
37-
export type ChildSources = ReadonlyMap<string, Readonly<Record<string, string>>>
48+
export type ChildSources = ReadonlyMap<string, ChildSource>
3849

3950
export interface ChildResultsScope {
4051
workspaceId: string
@@ -46,77 +57,130 @@ export interface ChildResultsScope {
4657
submitted?: ChildSources
4758
}
4859

60+
/** Stored workflow graphs by id, as `loadWorkflowGraphs` reads them. */
61+
export type StoredGraphs = Awaited<ReturnType<typeof loadWorkflowGraphs>>
62+
63+
/** Graphs a read already loaded, and the workflow each child key resolves to for it. */
64+
interface LoadedChildren {
65+
graphs: StoredGraphs
66+
toId: (key: string) => string | null
67+
}
68+
4969
/**
50-
* Canonicalize reads resources only to lift ids to keys, which no Response field's type depends
51-
* on, so the children are read without the workspace's resource keys.
70+
* A submitted folder compiled as the directory's check compiles it ({@link folderCompileInput}):
71+
* continuing the stored workflow its lock binds, so a `stored()` param compiles unread.
5272
*/
53-
const UNRESOLVED: ResourceKeyResolver = { toKey: () => null, toId: () => null }
54-
55-
/** The fields of a submitted folder, compiled on its own as the directory's check compiles it. */
56-
function submittedFields(
57-
files: Readonly<Record<string, string>>,
58-
scope: ChildResultsScope
59-
): ChildFields {
60-
const entry = files[SOURCE_ENTRY_FILE]
73+
function submittedNode(source: ChildSource, scope: ChildResultsScope): ChildResultNode | null {
74+
const entry = source.files[SOURCE_ENTRY_FILE]
6175
if (entry === undefined) return null
6276
const catalog = buildSourceCatalog({
6377
gate: scope.gate,
6478
organizationId: scope.workspaceOrganizationId,
6579
})
66-
const { workflow } = compileWorkflow({
67-
entry: { path: SOURCE_ENTRY_FILE, text: entry },
68-
files: new Map(Object.entries(files).filter(([path]) => path !== SOURCE_ENTRY_FILE)),
69-
catalog,
70-
sdkMajor: catalog.sdkMajor,
71-
})
72-
return workflow ? childResultFields(workflow, catalog) : null
80+
const lock = source.lock === undefined ? undefined : parseWorkflowLock(source.lock).lock
81+
return compiledResultNode(folderCompileInput(entry, source.files, lock, catalog))
7382
}
7483

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(
84+
/**
85+
* A stored workflow canonicalized under its own source catalog, with only the workflows it calls
86+
* lifted to their keys: no Response field's type depends on any other resource's key.
87+
*/
88+
function storedNode(
8089
loaded: NonNullable<ReturnType<StoredGraphs['get']>>,
90+
workflowKeys: ReadonlyMap<string, string>,
8191
scope: ChildResultsScope
82-
): ChildFields {
92+
): ChildResultNode {
8393
const { blocks, edges, loops, parallels, variables } = loaded.graph
8494
const catalog = buildSourceCatalog({
8595
gate: scope.gate,
8696
organizationId: scope.workspaceOrganizationId,
8797
storedTypes: storedCatalogTypes(Object.values(blocks)),
8898
})
99+
const resources: ResourceKeyResolver = {
100+
toKey: (kind, id) => (kind === 'workflow' ? (workflowKeys.get(id) ?? null) : null),
101+
toId: () => null,
102+
}
89103
const { workflow } = canonicalize(
90104
{ blocks, edges, loops, parallels, variables },
91-
{
92-
catalog,
93-
meta: { name: loaded.name, description: loaded.description ?? null },
94-
resources: UNRESOLVED,
95-
}
105+
{ catalog, meta: { name: loaded.name, description: loaded.description ?? null }, resources }
96106
)
97-
return childResultFields(workflow, catalog)
107+
return canonicalResultNode(workflow, catalog)
98108
}
99109

100-
/** The fields of each stored workflow `keys` name in the workspace, by key. */
101-
async function storedFields(
110+
/**
111+
* The node of each stored workflow `keys` name in the workspace, by key (one the workspace does
112+
* not hold, or holds archived, is left out): from `loaded` when it holds the graph a key resolves
113+
* to, else read in one query.
114+
*/
115+
async function storedNodes(
102116
keys: readonly string[],
103-
scope: ChildResultsScope
104-
): Promise<Map<string, ChildFields>> {
105-
const ids =
106-
(
107-
await resolveIds(
108-
scope.workspaceId,
109-
keys.map((key) => ({ kind: 'workflow' as const, key }))
110-
)
111-
).get('workflow') ?? new Map<string, string>()
112-
const graphs = await loadWorkflowGraphs(scope.workspaceId, [...ids.values()])
113-
const fields = new Map<string, ChildFields>()
117+
scope: ChildResultsScope,
118+
loaded: LoadedChildren | undefined
119+
): Promise<Map<string, ChildResultNode>> {
120+
const ids = new Map<string, string>()
114121
for (const key of keys) {
115-
const id = ids.get(key)
116-
const loaded = id === undefined ? undefined : graphs.get(id)
117-
fields.set(key, loaded ? storedGraphFields(loaded, scope) : null)
122+
const id = loaded ? loaded.toId(key) : null
123+
if (id !== null && loaded?.graphs.has(id)) ids.set(key, id)
124+
}
125+
const unloaded = keys.filter((key) => !ids.has(key))
126+
if (unloaded.length > 0) {
127+
const resolved =
128+
(
129+
await resolveIds(
130+
scope.workspaceId,
131+
unloaded.map((key) => ({ kind: 'workflow' as const, key }))
132+
)
133+
).get('workflow') ?? new Map<string, string>()
134+
for (const [key, id] of resolved) ids.set(key, id)
118135
}
119-
return fields
136+
const graphs = await loadChildGraphs(scope.workspaceId, [...ids.values()], loaded?.graphs)
137+
const calledIds = [...graphs.values()].flatMap((graph) =>
138+
storedChildWorkflowIds(Object.values(graph.graph.blocks))
139+
)
140+
const workflowKeys =
141+
calledIds.length === 0
142+
? new Map<string, string>()
143+
: ((
144+
await resolveKeys(
145+
scope.workspaceId,
146+
calledIds.map((id) => ({ kind: 'workflow' as const, id })),
147+
{ allocate: false }
148+
)
149+
).get('workflow') ?? new Map<string, string>())
150+
const nodes = new Map<string, ChildResultNode>()
151+
for (const [key, id] of ids) {
152+
const graph = graphs.get(id)
153+
if (graph) nodes.set(key, storedNode(graph, workflowKeys, scope))
154+
}
155+
return nodes
156+
}
157+
158+
/**
159+
* The fields of each workflow `keys` name and every workflow they reach by calls, by key: read
160+
* level by level (a submitted folder as submitted, any other as stored), then resolved callees
161+
* first ({@link resolveChildResults}).
162+
*/
163+
async function readChildResults(
164+
scope: ChildResultsScope,
165+
keys: readonly string[],
166+
loaded: LoadedChildren | undefined
167+
): Promise<Map<string, ChildFields>> {
168+
const nodes = new Map<string, ChildResultNode | null>()
169+
let frontier = [...new Set(keys)]
170+
while (frontier.length > 0) {
171+
const stored = frontier.filter((key) => !scope.submitted?.has(key))
172+
const read = stored.length > 0 ? await storedNodes(stored, scope, loaded) : new Map()
173+
for (const key of frontier) {
174+
const source = scope.submitted?.get(key)
175+
nodes.set(key, source ? submittedNode(source, scope) : (read.get(key) ?? null))
176+
}
177+
const next = new Set(frontier.flatMap((key) => nodes.get(key)?.calls ?? []))
178+
frontier = [...next].filter((key) => !nodes.has(key))
179+
}
180+
const present = new Map<string, ChildResultNode>()
181+
for (const [key, node] of nodes) if (node) present.set(key, node)
182+
const resolved = resolveChildResults(present)
183+
return new Map([...nodes.keys()].map((key) => [key, resolved.get(key) ?? null]))
120184
}
121185

122186
/**
@@ -149,21 +213,21 @@ export async function loadChildGraphs(
149213
/**
150214
* The typed result fields of each child workflow `keys` name that always responds, by key: a
151215
* child the enclosing apply submits as submitted, any other as its stored draft in the workspace
152-
* (one the workspace does not hold, or holds archived, is left out). Each key is read once per
153-
* `scope.memo`.
216+
* (one the workspace does not hold, or holds archived, is left out), each typed by the workflows
217+
* it calls in turn. Each key is read once per `scope.memo`; the workflows a reading reaches
218+
* through calls are kept there too.
154219
*/
155220
export async function loadChildResults(
156221
scope: ChildResultsScope,
157-
keys: readonly string[]
222+
keys: readonly string[],
223+
loaded?: LoadedChildren
158224
): Promise<Map<string, ChildResultFields>> {
159225
const unread = keys.filter((key) => !scope.memo.has(key))
160-
const stored = unread.filter((key) => !scope.submitted?.has(key))
161226
if (unread.length > 0) {
162227
const reading = withCatalogBlockScope(scope.gate, async () => {
163-
const fields = stored.length > 0 ? await storedFields(stored, scope) : new Map()
164-
for (const key of unread) {
165-
const files = scope.submitted?.get(key)
166-
if (files) fields.set(key, submittedFields(files, scope))
228+
const fields = await readChildResults(scope, unread, loaded)
229+
for (const [key, value] of fields) {
230+
if (!scope.memo.has(key)) scope.memo.set(key, Promise.resolve(value))
167231
}
168232
return fields
169233
})
@@ -182,23 +246,15 @@ export async function loadChildResults(
182246

183247
/**
184248
* {@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.
249+
* {@link loadChildGraphs} (`toId` names the workflow a key resolves to): a child whose graph is
250+
* there is read from there, any other (a workflow those children call, or a key `toId` does not
251+
* resolve) as {@link loadChildResults} reads it.
188252
*/
189-
export async function loadChildResultsFrom(
253+
export function loadChildResultsFrom(
190254
scope: ChildResultsScope,
191255
keys: readonly string[],
192256
graphs: StoredGraphs,
193257
toId: (key: string) => string | null
194258
): 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)
259+
return loadChildResults(scope, keys, { graphs, toId })
204260
}

0 commit comments

Comments
 (0)