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
12 changes: 12 additions & 0 deletions .changeset/29719-flow-region-shape-error.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@objectstack/spec': patch
---

feat(spec): `validateControlFlow` throws `FlowRegionShapeError`, carrying the faulty container's path and node id

Clause-②: yes (widening)
Metadata-protocol: none

`validateControlFlow` (`@objectstack/spec/automation`) now throws an exported `FlowRegionShapeError` at each of its three refusals: a region its schema refuses, a region that is not single-entry, single-exit and acyclic, and a `parallel` block with fewer than two branches. The error carries `path`, the key path from the flow root to the container node that owns the fault (the spelling of `collectFlowGraphs`' `FlowGraph.path` plus `['nodes', i]`, for example `['nodes', 1, 'config', 'try', 'nodes', 0]`), and `nodeId`, that container's id. A reader can now locate the fault without parsing the sentence, including a `parallel` block nested inside another container, whose sentence names no enclosing scope.

The message is unchanged byte for byte, and the class extends `Error`, so a caller that reads `err.message` or tests `instanceof Error` sees no difference. Nothing a flow author writes is accepted or refused differently.
1 change: 1 addition & 0 deletions packages/spec/api-surface/automation.json
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@
"FlowRegionArity (type)",
"FlowRegionParsed (type)",
"FlowRegionSchema (const)",
"FlowRegionShapeError (class)",
"FlowRegionSlotDecl (interface)",
"FlowRunGateSummary (type)",
"FlowRunGateSummarySchema (const)",
Expand Down
1 change: 1 addition & 0 deletions packages/spec/export-origins/automation.json
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,7 @@
"FlowRegionArity": "src/automation/region-slots.ts#FlowRegionArity (type)",
"FlowRegionParsed": "src/automation/control-flow.zod.ts#FlowRegionParsed (type)",
"FlowRegionSchema": "src/automation/control-flow.zod.ts#FlowRegionSchema (const)",
"FlowRegionShapeError": "src/automation/control-flow.zod.ts#FlowRegionShapeError (class)",
"FlowRegionSlotDecl": "src/automation/region-slots.ts#FlowRegionSlotDecl (interface)",
"FlowRunGateSummary": "src/automation/execution.zod.ts#FlowRunGateSummary (type)",
"FlowRunGateSummarySchema": "src/automation/execution.zod.ts#FlowRunGateSummarySchema (const)",
Expand Down
113 changes: 113 additions & 0 deletions packages/spec/src/automation/control-flow.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import {
analyzeRegion,
findRegionEntry,
validateControlFlow,
collectFlowGraphs,
FlowRegionShapeError,
LOOP_MAX_ITERATIONS_CEILING,
LOOP_NODE_TYPE,
PARALLEL_NODE_TYPE,
Expand Down Expand Up @@ -643,3 +645,114 @@ describe('validateControlFlow and the unknown-key gate meet at the region-slot s
expect(message).toContain('A region is not labelled');
});
});

// ─── [#29719] The refusal carries the container's location as data ─────────
//
// `validateControlFlow` throws a `FlowRegionShapeError` at each of its three
// throw sites: the container's `path` (spelled as `collectFlowGraphs`'
// `FlowGraph.path`, plus `['nodes', i]`) and its `nodeId` ride on the error,
// so a reader such as the `flow-region-shape-invalid` lint rule anchors the
// fault without parsing the sentence. The sentence itself is unchanged: each
// case pins the engine's own words literally and derives only the part a
// judge it calls (Zod, `analyzeRegion`) words.
describe('validateControlFlow throws FlowRegionShapeError with the container path and id', () => {
const refusalOf = (flow: unknown): FlowRegionShapeError => {
try {
validateControlFlow(flow as never);
} catch (err) {
expect(err).toBeInstanceOf(FlowRegionShapeError);
expect(err).toBeInstanceOf(Error);
expect((err as Error).name).toBe('FlowRegionShapeError');
return err as FlowRegionShapeError;
}
throw new Error('expected validateControlFlow to refuse the flow');
};
/** The path's graph half must be a path `collectFlowGraphs` hands out — one spelling. */
const expectGraphPathSpelling = (flow: unknown, path: readonly (string | number)[]) => {
const graphPaths = collectFlowGraphs(flow as never).map((g) => JSON.stringify(g.path));
expect(path.slice(-2)[0]).toBe('nodes');
expect(graphPaths).toContain(JSON.stringify(path.slice(0, -2)));
};
const loopCfg = (body: unknown) => ({ collection: { dialect: 'cel', source: 'items' }, iteratorVariable: 'item', body });
const twoStep = { nodes: [node('a'), node('b')], edges: [edge('e1', 'a', 'b')] };

it('an invalid region (the region schema refuses it): a top-level try_catch', () => {
const tryRegion = { nodes: [node('a')], edges: [], bogus: true };
const flow = { nodes: [node('start', 'start'), { ...node('tc', TRY_CATCH_NODE_TYPE), config: { try: tryRegion } }] };
const err = refusalOf(flow);
expect(err.path).toEqual(['nodes', 1]);
expect(err.nodeId).toBe('tc');
const issues = FlowRegionSchema.safeParse(tryRegion).error!.issues.map((i) => i.message).join('; ');
expect(err.message).toBe(`try_catch 'tc' try: invalid region — ${issues}`);
expectGraphPathSpelling(flow, err.path);
});

it('a region analysis error: a loop nested in a parallel branch', () => {
const body = { nodes: [node('x'), node('y')], edges: [] }; // two entries, two exits
const flow = {
nodes: [
node('start', 'start'),
{
...node('fan', PARALLEL_NODE_TYPE),
config: {
branches: [
twoStep,
{ nodes: [node('c'), { ...node('sweep', LOOP_NODE_TYPE), config: loopCfg(body) }], edges: [edge('e2', 'c', 'sweep')] },
],
},
},
],
};
const err = refusalOf(flow);
expect(err.path).toEqual(['nodes', 1, 'config', 'branches', 1, 'nodes', 1]);
expect(err.nodeId).toBe('sweep');
expect(err.message).toBe(
`parallel 'fan' branch 1 → loop 'sweep' body: ${analyzeRegion(body as never).errors.join('; ')}`,
);
expect(err.message.startsWith("parallel 'fan' branch 1 → loop 'sweep' body: region must be single-entry but has 2: x, y; ")).toBe(true);
expectGraphPathSpelling(flow, err.path);
});

it('a parallel block with fewer than 2 branches, at the top level', () => {
const flow = { nodes: [{ ...node('p', PARALLEL_NODE_TYPE), config: { branches: [twoStep] } }] };
const err = refusalOf(flow);
expect(err.path).toEqual(['nodes', 0]);
expect(err.nodeId).toBe('p');
expect(err.message).toBe("parallel 'p': a parallel block needs at least 2 branches");
expectGraphPathSpelling(flow, err.path);
});

it('the nested case: a one-branch parallel inside a try region, whose sentence names no scope', () => {
const flow = {
nodes: [
node('start', 'start'),
{
...node('guard', TRY_CATCH_NODE_TYPE),
config: {
try: {
nodes: [{ ...node('fan', PARALLEL_NODE_TYPE), config: { branches: [{ nodes: [node('only_step')], edges: [] }] } }],
edges: [],
},
catch: { nodes: [node('catch_step')], edges: [] },
},
},
],
};
const err = refusalOf(flow);
// The sentence the draft-publish verdict pins, byte for byte.
expect(err.message).toBe("parallel 'fan': a parallel block needs at least 2 branches");
expect(err.path).toEqual(['nodes', 1, 'config', 'try', 'nodes', 0]);
expect(err.nodeId).toBe('fan');
expectGraphPathSpelling(flow, err.path);
});

it('the index is the RAW list\'s: a dropped non-record member does not renumber the container', () => {
// `collectFlowGraphs` hands out `nodes` without the `null`, while
// `FlowGraph.path` keeps indexing the raw list; the container's index follows
// `path`, so it reads 2 here, not 1.
const flow = { nodes: [node('start', 'start'), null, { ...node('p', PARALLEL_NODE_TYPE), config: { branches: [twoStep] } }] };
const err = refusalOf(flow);
expect(err.path).toEqual(['nodes', 2]);
expect(err.nodeId).toBe('p');
});
});
81 changes: 76 additions & 5 deletions packages/spec/src/automation/control-flow.zod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -621,8 +621,44 @@ function singularize(key: string): string {
const MAX_REGION_DEPTH = 32;

/**
* Validate every structured control-flow construct in a flow, throwing on the
* first malformed region (ADR-0031 — "reject the malformed before run"). Covers
* The refusal {@link validateControlFlow} throws: a malformed ADR-0031 region,
* or a `parallel` block with fewer than two branches.
*
* `message` is the engine's sentence, unchanged — the registration log, the
* `registerFlow` answer and every pinned copy of it read the same text they
* always did. What the class adds is the location as data, so a reader can
* anchor the fault without parsing that sentence (which would be a second
* spelling of this judge, and could not place a nested `parallel` at all —
* its sentence names no enclosing scope):
*
* - `path` — the key path from the flow root to the faulty CONTAINER node,
* spelled as {@link FlowGraph.path} is plus `['nodes', i]`:
* `['nodes', 1]` for a top-level container,
* `['nodes', 1, 'config', 'try', 'nodes', 0]` for one inside a `try` region.
* - `nodeId` — that container's `id`.
*
* Both name the container that owns the faulty region (or, for the branch
* count, the `parallel` block itself); which of its slots is at fault stays in
* the sentence, as before. Carries no `status`: `registerFlow`'s HTTP doors
* class every refusal of the definition as the author's fault on their own,
* and a declared status would overrule that.
*/
export class FlowRegionShapeError extends Error {
readonly path: readonly (string | number)[];
readonly nodeId: string;

constructor(path: readonly (string | number)[], nodeId: string, message: string) {
super(message);
this.name = 'FlowRegionShapeError';
this.path = path;
this.nodeId = nodeId;
}
}

/**
* Validate every structured control-flow construct in a flow, throwing a
* {@link FlowRegionShapeError} on the first malformed region (ADR-0031 —
* "reject the malformed before run"). Covers
* `loop` bodies, `parallel` branches, and `try_catch` try/catch regions —
* **at every depth** (#4389), so a container nested inside another container's
* region is checked too. Only validates the *nested structure* when present, so
Expand All @@ -648,27 +684,62 @@ export function validateControlFlow(flow: { nodes: FlowNodeParsed[] }): void {
const cfg = node.config as Record<string, unknown> | undefined;
if (!cfg) continue;
if (node.type === PARALLEL_NODE_TYPE && Array.isArray(cfg.branches) && cfg.branches.length < 2) {
throw new Error(`parallel '${node.id}': a parallel block needs at least 2 branches`);
throw new FlowRegionShapeError(
containerPathOf(flow, graph, node),
node.id,
`parallel '${node.id}': a parallel block needs at least 2 branches`,
);
}
for (const slot of regionSlotsOf(node)) {
const where = graph.scope ? `${graph.scope} → ${slot.label}` : slot.label;
const parsed = slot.schema.safeParse(slot.raw);
if (!parsed.success) {
throw new Error(
throw new FlowRegionShapeError(
containerPathOf(flow, graph, node),
node.id,
`${where}: invalid region — ${parsed.error.issues.map(i => i.message).join('; ')}`,
);
}
// Both region schemas produce `{ nodes, edges }` (a parallel branch adds
// `name` — a superset); `z.ZodTypeAny` just cannot say so.
const analysis = analyzeRegion(parsed.data as { nodes: FlowNodeParsed[]; edges?: FlowEdgeParsed[] });
if (analysis.errors.length > 0) {
throw new Error(`${where}: ${analysis.errors.join('; ')}`);
throw new FlowRegionShapeError(
containerPathOf(flow, graph, node),
node.id,
`${where}: ${analysis.errors.join('; ')}`,
);
}
}
}
}
}

/**
* The key path from the flow root to `node`, a member of `graph`: `graph.path`
* plus `['nodes', i]` — the spelling {@link FlowGraph.path} uses, so a reader
* can hand a {@link FlowRegionShapeError} straight to whatever already anchors
* on a graph's path.
*
* `i` is the node's index in the RAW list, read back through `graph.path`, not
* its position in `graph.nodes`: the walk drops a non-record member from what
* it hands out while `path` keeps indexing the raw list (the reason
* {@link FlowGraph.nodes} states), so a position in the handed-out array would
* renumber the siblings after a dropped member. A handed-out member is the raw
* member itself (the walk filters, it never copies), so identity finds it.
* Reached only on a refusal, so the happy path pays nothing for it.
*/
function containerPathOf(
flow: { nodes: FlowNodeParsed[] },
graph: FlowGraph,
node: FlowNodeParsed,
): readonly (string | number)[] {
let holder: unknown = flow;
for (const key of graph.path) holder = (holder as Record<string | number, unknown>)[key];
const raw = (holder as { nodes: readonly unknown[] }).nodes;
return [...graph.path, 'nodes', raw.indexOf(node)];
}


// ─── Region parsing (the FlowNodeSchema transform) ───────────────────

Expand Down
Loading