Compare commits
3 Commits
feat/graph
...
feat/analy
| Author | SHA1 | Date | |
|---|---|---|---|
| fa2223b90b | |||
| 3b52998f20 | |||
| 5cfc8882bd |
@@ -4,8 +4,7 @@ export {
|
||||
defaultEdgeType,
|
||||
resolveDefaultNodeAttrs,
|
||||
} from "./defaults.js";
|
||||
export { typeCompat, type TypeCompatResult, type TypeMismatch } from "./type-compat.js";
|
||||
export { buildTypeEdges } from "../graph/construction.js";
|
||||
export { typeCompat, buildTypeEdges, type TypeCompatResult, type TypeMismatch } from "./type-compat.js";
|
||||
export {
|
||||
validateSchema,
|
||||
validateGraph,
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
import { KindGuard, Kind, type TSchema } from "@alkdev/typebox";
|
||||
import { willCreateCycle } from "graphology-dag";
|
||||
import type { FlowGraph } from "../graph/construction.js";
|
||||
import {
|
||||
OperationNodeAttrs as OperationNodeAttrsSchema,
|
||||
OperationEdgeAttrs as OperationEdgeAttrsSchema,
|
||||
} from "../schema/index.js";
|
||||
import type { OperationNodeAttrs } from "../schema/index.js";
|
||||
|
||||
export interface TypeMismatch {
|
||||
path: string;
|
||||
@@ -275,4 +282,25 @@ export function typeCompat(outputSchema: TSchema, inputSchema: TSchema): TypeCom
|
||||
}
|
||||
|
||||
return { compatible: false, mismatches };
|
||||
}
|
||||
|
||||
export function buildTypeEdges(graph: FlowGraph<typeof OperationNodeAttrsSchema, typeof OperationEdgeAttrsSchema>): void {
|
||||
const nodeKeys = graph.nodes();
|
||||
for (const source of nodeKeys) {
|
||||
for (const target of nodeKeys) {
|
||||
if (source === target) continue;
|
||||
const sourceAttrs = graph.getNodeAttributes(source as never) as unknown as OperationNodeAttrs;
|
||||
const targetAttrs = graph.getNodeAttributes(target as never) as unknown as OperationNodeAttrs;
|
||||
const result = typeCompat(sourceAttrs.outputSchema as TSchema, targetAttrs.inputSchema as TSchema);
|
||||
if (result === undefined) continue;
|
||||
if (graph.hasEdge(source, target)) continue;
|
||||
if (willCreateCycle(graph.graph, source, target)) continue;
|
||||
const detail = result.detail ?? `${sourceAttrs.namespace}.${sourceAttrs.name}.output → ${targetAttrs.namespace}.${targetAttrs.name}.input`;
|
||||
graph.addTypedEdge(source, target, {
|
||||
compatible: result.compatible,
|
||||
detail,
|
||||
...(result.mismatches !== undefined ? { mismatches: result.mismatches } : {}),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
NodeNotFoundError,
|
||||
CycleError,
|
||||
InvalidInputError,
|
||||
InvalidTransitionError,
|
||||
} from "../error/index.js";
|
||||
import type { CallStatus, AnyValidationError, ValidationError } from "../error/index.js";
|
||||
import {
|
||||
@@ -21,11 +20,11 @@ import {
|
||||
OperationEdgeAttrs as OperationEdgeAttrsSchema,
|
||||
OperationGraphSerialized,
|
||||
CallGraphSerialized,
|
||||
CallNodeAttrs as CallNodeAttrsSchema,
|
||||
CallEdgeAttrs as CallEdgeAttrsSchema,
|
||||
} from "../schema/index.js";
|
||||
import type { OperationNodeAttrs, FlowGraphSerialized, CallNodeAttrs } from "../schema/index.js";
|
||||
import { typeCompat, type TypeCompatResult } from "../analysis/type-compat.js";
|
||||
import type { FlowGraphSerialized } from "../schema/index.js";
|
||||
import { buildTypeEdges, type TypeCompatResult } from "../analysis/type-compat.js";
|
||||
|
||||
export { buildTypeEdges } from "../analysis/type-compat.js";
|
||||
|
||||
export interface FlowGraphOptions {
|
||||
type?: "directed";
|
||||
@@ -44,55 +43,8 @@ export interface OperationSpec {
|
||||
tags?: string[];
|
||||
}
|
||||
|
||||
export interface CallRequestedEvent {
|
||||
type: "call.requested";
|
||||
requestId: string;
|
||||
operationId: string;
|
||||
input: unknown;
|
||||
timestamp: string;
|
||||
parentRequestId?: string;
|
||||
identity?: { id: string; scopes: string[]; resources?: Record<string, string[]> };
|
||||
startedAt?: string;
|
||||
}
|
||||
|
||||
export interface CallRespondedEvent {
|
||||
type: "call.responded";
|
||||
requestId: string;
|
||||
output: unknown;
|
||||
timestamp: string;
|
||||
}
|
||||
|
||||
export interface CallErrorEvent {
|
||||
type: "call.error";
|
||||
requestId: string;
|
||||
error: { code: string; message: string; details?: unknown };
|
||||
timestamp: string;
|
||||
}
|
||||
|
||||
export interface CallAbortedEvent {
|
||||
type: "call.aborted";
|
||||
requestId: string;
|
||||
timestamp: string;
|
||||
}
|
||||
|
||||
export interface CallCompletedEvent {
|
||||
type: "call.completed";
|
||||
requestId: string;
|
||||
output?: unknown;
|
||||
timestamp: string;
|
||||
}
|
||||
|
||||
export type CallEventMapValue =
|
||||
| CallRequestedEvent
|
||||
| CallRespondedEvent
|
||||
| CallErrorEvent
|
||||
| CallAbortedEvent
|
||||
| CallCompletedEvent;
|
||||
|
||||
type OperationGraph = FlowGraph<typeof OperationNodeAttrsSchema, typeof OperationEdgeAttrsSchema>;
|
||||
|
||||
type CallGraph = FlowGraph<typeof CallNodeAttrsSchema, typeof CallEdgeAttrsSchema>;
|
||||
|
||||
type TypedEdgeAttrs = {
|
||||
edgeType: "typed";
|
||||
compatible: boolean;
|
||||
@@ -102,14 +54,6 @@ type TypedEdgeAttrs = {
|
||||
|
||||
type Attrs = Record<string, unknown>;
|
||||
|
||||
const VALID_TRANSITIONS: Record<CallStatus, CallStatus[]> = {
|
||||
pending: ["running", "aborted"],
|
||||
running: ["completed", "failed", "aborted"],
|
||||
completed: [],
|
||||
failed: [],
|
||||
aborted: [],
|
||||
};
|
||||
|
||||
export class FlowGraph<
|
||||
NodeAttrs extends TSchema = TSchema,
|
||||
EdgeAttrs extends TSchema = TSchema,
|
||||
@@ -376,145 +320,6 @@ export class FlowGraph<
|
||||
return chain;
|
||||
}
|
||||
|
||||
updateFromEvent(event: CallEventMapValue): void {
|
||||
switch (event.type) {
|
||||
case "call.requested": {
|
||||
const attrs: CallNodeAttrs = {
|
||||
requestId: event.requestId,
|
||||
operationId: event.operationId,
|
||||
status: "pending",
|
||||
input: event.input,
|
||||
...(event.parentRequestId !== undefined ? { parentRequestId: event.parentRequestId } : {}),
|
||||
...(event.identity !== undefined ? { identity: event.identity } : {}),
|
||||
...(event.startedAt !== undefined ? { startedAt: event.startedAt } : {}),
|
||||
};
|
||||
this.addCall(attrs);
|
||||
break;
|
||||
}
|
||||
case "call.responded": {
|
||||
if (!this._graph.hasNode(event.requestId)) return;
|
||||
const current = this._graph.getNodeAttributes(event.requestId) as Record<string, unknown>;
|
||||
const currentStatus = current.status as CallStatus;
|
||||
if (currentStatus === "completed" || currentStatus === "failed" || currentStatus === "aborted") return;
|
||||
this._graph.mergeNodeAttributes(event.requestId, {
|
||||
status: "completed",
|
||||
output: event.output,
|
||||
completedAt: event.timestamp,
|
||||
} as Attrs);
|
||||
break;
|
||||
}
|
||||
case "call.error": {
|
||||
if (!this._graph.hasNode(event.requestId)) return;
|
||||
const current = this._graph.getNodeAttributes(event.requestId) as Record<string, unknown>;
|
||||
const currentStatus = current.status as CallStatus;
|
||||
if (currentStatus === "completed" || currentStatus === "failed" || currentStatus === "aborted") return;
|
||||
this._graph.mergeNodeAttributes(event.requestId, {
|
||||
status: "failed",
|
||||
error: event.error,
|
||||
completedAt: event.timestamp,
|
||||
} as Attrs);
|
||||
break;
|
||||
}
|
||||
case "call.aborted": {
|
||||
if (!this._graph.hasNode(event.requestId)) return;
|
||||
const current = this._graph.getNodeAttributes(event.requestId) as Record<string, unknown>;
|
||||
const currentStatus = current.status as CallStatus;
|
||||
if (currentStatus === "completed" || currentStatus === "failed" || currentStatus === "aborted") return;
|
||||
this._graph.mergeNodeAttributes(event.requestId, {
|
||||
status: "aborted",
|
||||
completedAt: event.timestamp,
|
||||
} as Attrs);
|
||||
break;
|
||||
}
|
||||
case "call.completed": {
|
||||
if (!this._graph.hasNode(event.requestId)) return;
|
||||
const current = this._graph.getNodeAttributes(event.requestId) as Record<string, unknown>;
|
||||
const currentStatus = current.status as CallStatus;
|
||||
if (currentStatus === "completed") {
|
||||
if (!current.completedAt) {
|
||||
this._graph.mergeNodeAttributes(event.requestId, { completedAt: event.timestamp } as Attrs);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (currentStatus === "failed" || currentStatus === "aborted") return;
|
||||
this._graph.mergeNodeAttributes(event.requestId, {
|
||||
status: "completed",
|
||||
...(event.output !== undefined ? { output: event.output } : {}),
|
||||
completedAt: event.timestamp,
|
||||
} as Attrs);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
addCall(attrs: CallNodeAttrs): void {
|
||||
if (this._graph.hasNode(attrs.requestId)) return;
|
||||
this._graph.addNode(attrs.requestId, attrs as Attrs);
|
||||
if (attrs.parentRequestId !== undefined) {
|
||||
if (this._graph.hasNode(attrs.parentRequestId)) {
|
||||
if (willCreateCycle(this._graph, attrs.parentRequestId, attrs.requestId)) {
|
||||
this._graph.dropNode(attrs.requestId);
|
||||
const path = this._findPath(attrs.requestId, attrs.parentRequestId);
|
||||
const cycle = [attrs.parentRequestId, ...path, attrs.parentRequestId];
|
||||
throw new CycleError([cycle]);
|
||||
}
|
||||
const edgeKey = this._edgeKey(attrs.parentRequestId, attrs.requestId);
|
||||
this._graph.addEdgeWithKey(edgeKey, attrs.parentRequestId, attrs.requestId, { edgeType: "triggered" } as Attrs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
addDependency(source: string, target: string): void {
|
||||
if (!this._graph.hasNode(source)) {
|
||||
throw new NodeNotFoundError(source);
|
||||
}
|
||||
if (!this._graph.hasNode(target)) {
|
||||
throw new NodeNotFoundError(target);
|
||||
}
|
||||
const edgeKey = `${source}->${target}:depends_on`;
|
||||
if (this._graph.hasEdge(edgeKey)) return;
|
||||
if (willCreateCycle(this._graph, source, target)) {
|
||||
const path = this._findPath(target, source);
|
||||
const cycle = [source, ...path, source];
|
||||
throw new CycleError([cycle]);
|
||||
}
|
||||
this._graph.addEdgeWithKey(edgeKey, source, target, { edgeType: "depends_on" } as Attrs);
|
||||
}
|
||||
|
||||
updateStatus(requestId: string, status: CallStatus, extra?: Partial<CallNodeAttrs>): void {
|
||||
if (!this._graph.hasNode(requestId)) {
|
||||
throw new NodeNotFoundError(requestId);
|
||||
}
|
||||
const current = this._graph.getNodeAttributes(requestId) as Record<string, unknown>;
|
||||
const currentStatus = current.status as CallStatus;
|
||||
if (currentStatus === status) return;
|
||||
const allowed = VALID_TRANSITIONS[currentStatus];
|
||||
if (!allowed || !allowed.includes(status)) {
|
||||
throw new InvalidTransitionError(requestId, currentStatus, status);
|
||||
}
|
||||
const update: Record<string, unknown> = { status };
|
||||
if (extra) {
|
||||
for (const [key, value] of Object.entries(extra)) {
|
||||
if (value !== undefined) {
|
||||
update[key] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
this._graph.mergeNodeAttributes(requestId, update as Attrs);
|
||||
}
|
||||
|
||||
updateCall(requestId: string, attrs: Partial<CallNodeAttrs>): void {
|
||||
if (!this._graph.hasNode(requestId)) {
|
||||
throw new NodeNotFoundError(requestId);
|
||||
}
|
||||
this._graph.mergeNodeAttributes(requestId, attrs as Attrs);
|
||||
}
|
||||
|
||||
removeCall(requestId: string): void {
|
||||
if (!this._graph.hasNode(requestId)) return;
|
||||
this._graph.dropNode(requestId);
|
||||
}
|
||||
|
||||
validate(schema: TSchema): AnyValidationError[] {
|
||||
return _validate(this, schema as NodeAttrs);
|
||||
}
|
||||
@@ -562,12 +367,10 @@ export class FlowGraph<
|
||||
return graph;
|
||||
}
|
||||
|
||||
static fromCallEvents(events: CallEventMapValue[]): CallGraph {
|
||||
const graph = new FlowGraph<typeof CallNodeAttrsSchema, typeof CallEdgeAttrsSchema>();
|
||||
for (const event of events) {
|
||||
graph.updateFromEvent(event);
|
||||
}
|
||||
return graph;
|
||||
static fromCallEvents(
|
||||
_events: unknown[],
|
||||
): FlowGraph<TSchema, TSchema> {
|
||||
throw new Error("not implemented");
|
||||
}
|
||||
|
||||
export(): FlowGraphSerialized {
|
||||
@@ -654,25 +457,4 @@ export class FlowGraph<
|
||||
}
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function buildTypeEdges(graph: OperationGraph): void {
|
||||
const nodeKeys = graph.nodes();
|
||||
for (const source of nodeKeys) {
|
||||
for (const target of nodeKeys) {
|
||||
if (source === target) continue;
|
||||
const sourceAttrs = graph.getNodeAttributes(source as never) as unknown as OperationNodeAttrs;
|
||||
const targetAttrs = graph.getNodeAttributes(target as never) as unknown as OperationNodeAttrs;
|
||||
const result = typeCompat(sourceAttrs.outputSchema as TSchema, targetAttrs.inputSchema as TSchema);
|
||||
if (result === undefined) continue;
|
||||
if (graph.hasEdge(source, target)) continue;
|
||||
if (willCreateCycle(graph.graph, source, target)) continue;
|
||||
const detail = result.detail ?? `${sourceAttrs.namespace}.${sourceAttrs.name}.output → ${targetAttrs.namespace}.${targetAttrs.name}.input`;
|
||||
graph.addTypedEdge(source, target, {
|
||||
compatible: result.compatible,
|
||||
detail,
|
||||
...(result.mismatches !== undefined ? { mismatches: result.mismatches } : {}),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
export { FlowGraph, buildTypeEdges, type FlowGraphOptions, type OperationSpec, type CallEventMapValue, type CallRequestedEvent, type CallRespondedEvent, type CallErrorEvent, type CallAbortedEvent, type CallCompletedEvent } from "./construction.js";
|
||||
export { FlowGraph, buildTypeEdges, type FlowGraphOptions, type OperationSpec } from "./construction.js";
|
||||
export {
|
||||
topologicalOrder,
|
||||
hasCycles,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
export * from "./error/index.js";
|
||||
|
||||
export { FlowGraph, buildTypeEdges, type FlowGraphOptions, type OperationSpec, type CallEventMapValue, type CallRequestedEvent, type CallRespondedEvent, type CallErrorEvent, type CallAbortedEvent, type CallCompletedEvent } from "./graph/index.js";
|
||||
export { FlowGraph, buildTypeEdges, type FlowGraphOptions, type OperationSpec } from "./graph/index.js";
|
||||
export { typeCompat, type TypeCompatResult, type TypeMismatch } from "./analysis/type-compat.js";
|
||||
export {
|
||||
validateSchema,
|
||||
validateGraph,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: graph/construction-json
|
||||
name: Implement fromJSON and export/toJSON serialization for FlowGraph
|
||||
status: pending
|
||||
status: completed
|
||||
depends_on:
|
||||
- graph/flowgraph-class
|
||||
- schema/graph-schemas
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { Type, type TSchema } from "@alkdev/typebox";
|
||||
import { typeCompat, type TypeCompatResult, type TypeMismatch } from "../../src/analysis/type-compat.js";
|
||||
import { typeCompat, buildTypeEdges, type TypeCompatResult, type TypeMismatch } from "../../src/analysis/type-compat.js";
|
||||
import { FlowGraph } from "../../src/graph/construction.js";
|
||||
import type { OperationSpec } from "../../src/graph/construction.js";
|
||||
|
||||
describe("typeCompat", () => {
|
||||
describe("exact match", () => {
|
||||
@@ -411,4 +413,111 @@ describe("typeCompat", () => {
|
||||
expect(typeof mismatch.actual).toBe("string");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildTypeEdges", () => {
|
||||
it("adds compatible edges for matching output→input schemas", () => {
|
||||
const fg = new FlowGraph();
|
||||
fg.addOperation({ name: "extract", namespace: "task", version: "1.0.0", type: "query", inputSchema: Type.Object({ raw: Type.String() }), outputSchema: Type.Object({ text: Type.String() }) });
|
||||
fg.addOperation({ name: "classify", namespace: "task", version: "1.0.0", type: "query", inputSchema: Type.Object({ text: Type.String() }), outputSchema: Type.Object({ label: Type.String(), score: Type.Number() }) });
|
||||
buildTypeEdges(fg);
|
||||
expect(fg.hasEdge("task.extract", "task.classify")).toBe(true);
|
||||
const attrs = fg.getEdgeAttributes("task.extract", "task.classify") as Record<string, unknown>;
|
||||
expect(attrs.edgeType).toBe("typed");
|
||||
expect(attrs.compatible).toBe(true);
|
||||
});
|
||||
|
||||
it("adds incompatible edges when schemas mismatch", () => {
|
||||
const fg = new FlowGraph();
|
||||
fg.addOperation({ name: "classify", namespace: "task", version: "1.0.0", type: "query", inputSchema: Type.Object({ text: Type.String() }), outputSchema: Type.Object({ label: Type.String(), score: Type.Number() }) });
|
||||
fg.addOperation({ name: "count", namespace: "task", version: "1.0.0", type: "query", inputSchema: Type.Object({ count: Type.Number() }), outputSchema: Type.Object({ result: Type.Number() }) });
|
||||
buildTypeEdges(fg);
|
||||
expect(fg.hasEdge("task.classify", "task.count")).toBe(true);
|
||||
const attrs = fg.getEdgeAttributes("task.classify", "task.count") as Record<string, unknown>;
|
||||
expect(attrs.edgeType).toBe("typed");
|
||||
expect(attrs.compatible).toBe(false);
|
||||
expect(attrs.mismatches).toBeDefined();
|
||||
});
|
||||
|
||||
it("incompatible edges include mismatches array", () => {
|
||||
const fg = new FlowGraph();
|
||||
fg.addOperation({ name: "a", namespace: "op", version: "1.0.0", type: "query", inputSchema: Type.Object({ x: Type.String() }), outputSchema: Type.Object({ value: Type.String() }) });
|
||||
fg.addOperation({ name: "b", namespace: "op", version: "1.0.0", type: "query", inputSchema: Type.Object({ value: Type.Number() }), outputSchema: Type.Object({ z: Type.Boolean() }) });
|
||||
buildTypeEdges(fg);
|
||||
const attrs = fg.getEdgeAttributes("op.a", "op.b") as Record<string, unknown>;
|
||||
expect(attrs.compatible).toBe(false);
|
||||
expect(Array.isArray(attrs.mismatches)).toBe(true);
|
||||
expect((attrs.mismatches as Array<unknown>).length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("does not add edges when either schema is Unknown", () => {
|
||||
const fg = new FlowGraph();
|
||||
fg.addOperation({ name: "unk_out", namespace: "op", version: "1.0.0", type: "query", inputSchema: Type.Object({ x: Type.String() }), outputSchema: Type.Unknown() });
|
||||
fg.addOperation({ name: "unk_in", namespace: "op", version: "1.0.0", type: "query", inputSchema: Type.Unknown(), outputSchema: Type.Object({ y: Type.String() }) });
|
||||
fg.addOperation({ name: "normal", namespace: "op", version: "1.0.0", type: "query", inputSchema: Type.Object({ y: Type.String() }), outputSchema: Type.Object({ x: Type.String() }) });
|
||||
buildTypeEdges(fg);
|
||||
expect(fg.hasEdge("op.unk_out", "op.unk_in")).toBe(false);
|
||||
expect(fg.hasEdge("op.unk_out", "op.normal")).toBe(false);
|
||||
expect(fg.hasEdge("op.normal", "op.unk_in")).toBe(false);
|
||||
});
|
||||
|
||||
it("sets detail to namespace.name.output → namespace.name.input for compatible edges", () => {
|
||||
const fg = new FlowGraph();
|
||||
fg.addOperation({ name: "extract", namespace: "task", version: "1.0.0", type: "query", inputSchema: Type.Object({ raw: Type.String() }), outputSchema: Type.Object({ text: Type.String() }) });
|
||||
fg.addOperation({ name: "classify", namespace: "task", version: "1.0.0", type: "query", inputSchema: Type.Object({ text: Type.String() }), outputSchema: Type.Object({ label: Type.String() }) });
|
||||
buildTypeEdges(fg);
|
||||
const attrs = fg.getEdgeAttributes("task.extract", "task.classify") as Record<string, unknown>;
|
||||
expect(attrs.detail).toContain("task.extract.output → task.classify.input");
|
||||
});
|
||||
|
||||
it("is callable after incremental addOperation calls", () => {
|
||||
const fg = new FlowGraph();
|
||||
fg.addOperation({ name: "extract", namespace: "op", version: "1.0.0", type: "query", inputSchema: Type.Object({ raw: Type.String() }), outputSchema: Type.Object({ text: Type.String() }) });
|
||||
buildTypeEdges(fg);
|
||||
expect(fg.size).toBe(0);
|
||||
fg.addOperation({ name: "classify", namespace: "op", version: "1.0.0", type: "query", inputSchema: Type.Object({ text: Type.String() }), outputSchema: Type.Object({ label: Type.String() }) });
|
||||
buildTypeEdges(fg);
|
||||
expect(fg.hasEdge("op.extract", "op.classify")).toBe(true);
|
||||
});
|
||||
|
||||
it("produces edges for three operations in a pipeline", () => {
|
||||
const fg = new FlowGraph();
|
||||
fg.addOperation({ name: "extract", namespace: "task", version: "1.0.0", type: "query", inputSchema: Type.Object({ raw: Type.String() }), outputSchema: Type.Object({ text: Type.String() }) });
|
||||
fg.addOperation({ name: "classify", namespace: "task", version: "1.0.0", type: "query", inputSchema: Type.Object({ text: Type.String() }), outputSchema: Type.Object({ label: Type.String() }) });
|
||||
fg.addOperation({ name: "enrich", namespace: "task", version: "1.0.0", type: "query", inputSchema: Type.Object({ label: Type.String() }), outputSchema: Type.Object({ enriched: Type.String() }) });
|
||||
buildTypeEdges(fg);
|
||||
expect(fg.hasEdge("task.extract", "task.classify")).toBe(true);
|
||||
expect(fg.hasEdge("task.classify", "task.enrich")).toBe(true);
|
||||
expect(fg.hasEdge("task.extract", "task.enrich")).toBe(true);
|
||||
const e2c = fg.getEdgeAttributes("task.extract", "task.classify") as Record<string, unknown>;
|
||||
const c2e = fg.getEdgeAttributes("task.classify", "task.enrich") as Record<string, unknown>;
|
||||
const e2e = fg.getEdgeAttributes("task.extract", "task.enrich") as Record<string, unknown>;
|
||||
expect(e2c.compatible).toBe(true);
|
||||
expect(c2e.compatible).toBe(true);
|
||||
expect(e2e.compatible).toBe(false);
|
||||
});
|
||||
|
||||
it("does not add self-loops", () => {
|
||||
const fg = new FlowGraph();
|
||||
fg.addOperation({ name: "a", namespace: "op", version: "1.0.0", type: "query", inputSchema: Type.Object({ x: Type.String() }), outputSchema: Type.Object({ x: Type.String() }) });
|
||||
buildTypeEdges(fg);
|
||||
expect(fg.size).toBe(0);
|
||||
});
|
||||
|
||||
it("returns empty graph with no edges for empty graph", () => {
|
||||
const fg = new FlowGraph();
|
||||
buildTypeEdges(fg);
|
||||
expect(fg.order).toBe(0);
|
||||
expect(fg.size).toBe(0);
|
||||
});
|
||||
|
||||
it("skips edges that would already exist", () => {
|
||||
const fg = new FlowGraph();
|
||||
fg.addOperation({ name: "a", namespace: "op", version: "1.0.0", type: "query", inputSchema: Type.Object({ x: Type.String() }), outputSchema: Type.Object({ y: Type.String() }) });
|
||||
fg.addOperation({ name: "b", namespace: "op", version: "1.0.0", type: "query", inputSchema: Type.Object({ y: Type.String() }), outputSchema: Type.Object({ z: Type.String() }) });
|
||||
buildTypeEdges(fg);
|
||||
const sizeAfterFirst = fg.size;
|
||||
buildTypeEdges(fg);
|
||||
expect(fg.size).toBe(sizeAfterFirst);
|
||||
});
|
||||
});
|
||||
@@ -1,15 +1,13 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { Type } from "@alkdev/typebox";
|
||||
import { FlowGraph, buildTypeEdges } from "../../src/graph/construction.js";
|
||||
import type { OperationSpec, CallEventMapValue } from "../../src/graph/construction.js";
|
||||
import type { OperationSpec } from "../../src/graph/construction.js";
|
||||
import {
|
||||
DuplicateNodeError,
|
||||
DuplicateEdgeError,
|
||||
NodeNotFoundError,
|
||||
CycleError,
|
||||
InvalidTransitionError,
|
||||
} from "../../src/error/index.js";
|
||||
import type { CallStatus } from "../../src/error/index.js";
|
||||
|
||||
describe("FlowGraph constructor", () => {
|
||||
it("creates an empty graph", () => {
|
||||
@@ -302,14 +300,8 @@ describe("FlowGraph query methods", () => {
|
||||
});
|
||||
|
||||
describe("FlowGraph static stubs", () => {
|
||||
it("fromCallEvents returns empty graph for empty events", () => {
|
||||
const graph = FlowGraph.fromCallEvents([]);
|
||||
expect(graph.order).toBe(0);
|
||||
expect(graph.size).toBe(0);
|
||||
});
|
||||
|
||||
it("fromJSON throws not implemented", () => {
|
||||
expect(() => FlowGraph.fromJSON({} as never)).toThrow();
|
||||
it("fromCallEvents throws not implemented", () => {
|
||||
expect(() => FlowGraph.fromCallEvents([])).toThrow("not implemented");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -642,520 +634,4 @@ describe("FlowGraph cycle detection", () => {
|
||||
fg.addEdge("a", "c");
|
||||
expect(() => fg.addEdge("b", "c")).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("FlowGraph.fromCallEvents", () => {
|
||||
const requestedEvent: CallEventMapValue = {
|
||||
type: "call.requested",
|
||||
requestId: "req-1",
|
||||
operationId: "task.classify",
|
||||
input: { text: "hello" },
|
||||
timestamp: "2026-01-01T00:00:00Z",
|
||||
};
|
||||
|
||||
const requestedWithParent: CallEventMapValue = {
|
||||
type: "call.requested",
|
||||
requestId: "req-2",
|
||||
operationId: "task.enrich",
|
||||
input: { label: "greeting" },
|
||||
timestamp: "2026-01-01T00:00:01Z",
|
||||
parentRequestId: "req-1",
|
||||
};
|
||||
|
||||
const respondedEvent: CallEventMapValue = {
|
||||
type: "call.responded",
|
||||
requestId: "req-1",
|
||||
output: { label: "greeting" },
|
||||
timestamp: "2026-01-01T00:00:02Z",
|
||||
};
|
||||
|
||||
const errorEvent: CallEventMapValue = {
|
||||
type: "call.error",
|
||||
requestId: "req-1",
|
||||
error: { code: "INTERNAL", message: "Something went wrong" },
|
||||
timestamp: "2026-01-01T00:00:03Z",
|
||||
};
|
||||
|
||||
const abortedEvent: CallEventMapValue = {
|
||||
type: "call.aborted",
|
||||
requestId: "req-1",
|
||||
timestamp: "2026-01-01T00:00:04Z",
|
||||
};
|
||||
|
||||
const completedEvent: CallEventMapValue = {
|
||||
type: "call.completed",
|
||||
requestId: "req-1",
|
||||
output: { label: "greeting" },
|
||||
timestamp: "2026-01-01T00:00:05Z",
|
||||
};
|
||||
|
||||
it("adds node from call.requested event", () => {
|
||||
const graph = FlowGraph.fromCallEvents([requestedEvent]);
|
||||
expect(graph.order).toBe(1);
|
||||
expect(graph.hasNode("req-1")).toBe(true);
|
||||
const attrs = graph.getNodeAttributes("req-1") as Record<string, unknown>;
|
||||
expect(attrs.status).toBe("pending");
|
||||
expect(attrs.operationId).toBe("task.classify");
|
||||
});
|
||||
|
||||
it("creates triggered edge from parentRequestId", () => {
|
||||
const graph = FlowGraph.fromCallEvents([requestedEvent, requestedWithParent]);
|
||||
expect(graph.order).toBe(2);
|
||||
expect(graph.hasNode("req-2")).toBe(true);
|
||||
expect(graph.hasEdge("req-1", "req-2")).toBe(true);
|
||||
const edgeAttrs = graph.getEdgeAttributes("req-1", "req-2") as Record<string, unknown>;
|
||||
expect(edgeAttrs.edgeType).toBe("triggered");
|
||||
});
|
||||
|
||||
it("updates status to completed on call.responded", () => {
|
||||
const graph = FlowGraph.fromCallEvents([requestedEvent, respondedEvent]);
|
||||
const attrs = graph.getNodeAttributes("req-1") as Record<string, unknown>;
|
||||
expect(attrs.status).toBe("completed");
|
||||
expect(attrs.output).toEqual({ label: "greeting" });
|
||||
expect(attrs.completedAt).toBe("2026-01-01T00:00:02Z");
|
||||
});
|
||||
|
||||
it("updates status to failed on call.error", () => {
|
||||
const graph = FlowGraph.fromCallEvents([requestedEvent, errorEvent]);
|
||||
const attrs = graph.getNodeAttributes("req-1") as Record<string, unknown>;
|
||||
expect(attrs.status).toBe("failed");
|
||||
expect(attrs.error).toEqual({ code: "INTERNAL", message: "Something went wrong" });
|
||||
expect(attrs.completedAt).toBe("2026-01-01T00:00:03Z");
|
||||
});
|
||||
|
||||
it("updates status to aborted on call.aborted", () => {
|
||||
const graph = FlowGraph.fromCallEvents([requestedEvent, abortedEvent]);
|
||||
const attrs = graph.getNodeAttributes("req-1") as Record<string, unknown>;
|
||||
expect(attrs.status).toBe("aborted");
|
||||
expect(attrs.completedAt).toBe("2026-01-01T00:00:04Z");
|
||||
});
|
||||
|
||||
it("updates status to completed on call.completed", () => {
|
||||
const graph = FlowGraph.fromCallEvents([requestedEvent, completedEvent]);
|
||||
const attrs = graph.getNodeAttributes("req-1") as Record<string, unknown>;
|
||||
expect(attrs.status).toBe("completed");
|
||||
expect(attrs.completedAt).toBe("2026-01-01T00:00:05Z");
|
||||
});
|
||||
|
||||
it("is idempotent — duplicate events have no effect", () => {
|
||||
const graph = FlowGraph.fromCallEvents([requestedEvent, requestedEvent, respondedEvent, respondedEvent]);
|
||||
expect(graph.order).toBe(1);
|
||||
const attrs = graph.getNodeAttributes("req-1") as Record<string, unknown>;
|
||||
expect(attrs.status).toBe("completed");
|
||||
});
|
||||
|
||||
it("ignores responded/error/aborted for unknown requestId", () => {
|
||||
const graph = FlowGraph.fromCallEvents([respondedEvent, errorEvent, abortedEvent]);
|
||||
expect(graph.order).toBe(0);
|
||||
});
|
||||
|
||||
it("creates node for unknown operationId", () => {
|
||||
const unknownOpEvent: CallEventMapValue = {
|
||||
type: "call.requested",
|
||||
requestId: "req-unknown",
|
||||
operationId: "unknown.op",
|
||||
input: {},
|
||||
timestamp: "2026-01-01T00:00:00Z",
|
||||
};
|
||||
const graph = FlowGraph.fromCallEvents([unknownOpEvent]);
|
||||
expect(graph.order).toBe(1);
|
||||
const attrs = graph.getNodeAttributes("req-unknown") as Record<string, unknown>;
|
||||
expect(attrs.status).toBe("pending");
|
||||
expect(attrs.operationId).toBe("unknown.op");
|
||||
});
|
||||
|
||||
it("processes full event sequence", () => {
|
||||
const req1: CallEventMapValue = {
|
||||
type: "call.requested",
|
||||
requestId: "req-parent",
|
||||
operationId: "task.parent",
|
||||
input: {},
|
||||
timestamp: "2026-01-01T00:00:00Z",
|
||||
};
|
||||
const req2: CallEventMapValue = {
|
||||
type: "call.requested",
|
||||
requestId: "req-child",
|
||||
operationId: "task.child",
|
||||
input: {},
|
||||
timestamp: "2026-01-01T00:00:01Z",
|
||||
parentRequestId: "req-parent",
|
||||
};
|
||||
const resp: CallEventMapValue = {
|
||||
type: "call.responded",
|
||||
requestId: "req-parent",
|
||||
output: "done",
|
||||
timestamp: "2026-01-01T00:00:02Z",
|
||||
};
|
||||
const graph = FlowGraph.fromCallEvents([req1, req2, resp]);
|
||||
expect(graph.order).toBe(2);
|
||||
expect(graph.hasEdge("req-parent", "req-child")).toBe(true);
|
||||
const parentAttrs = graph.getNodeAttributes("req-parent") as Record<string, unknown>;
|
||||
expect(parentAttrs.status).toBe("completed");
|
||||
const childAttrs = graph.getNodeAttributes("req-child") as Record<string, unknown>;
|
||||
expect(childAttrs.status).toBe("pending");
|
||||
});
|
||||
|
||||
it("stores identity and startedAt from call.requested", () => {
|
||||
const event: CallEventMapValue = {
|
||||
type: "call.requested",
|
||||
requestId: "req-id",
|
||||
operationId: "task.op",
|
||||
input: {},
|
||||
timestamp: "2026-01-01T00:00:00Z",
|
||||
identity: { id: "user-1", scopes: ["read"] },
|
||||
startedAt: "2026-01-01T00:00:01Z",
|
||||
};
|
||||
const graph = FlowGraph.fromCallEvents([event]);
|
||||
const attrs = graph.getNodeAttributes("req-id") as Record<string, unknown>;
|
||||
expect(attrs.identity).toEqual({ id: "user-1", scopes: ["read"] });
|
||||
expect(attrs.startedAt).toBe("2026-01-01T00:00:01Z");
|
||||
});
|
||||
|
||||
it("skips triggered edge if parent node does not exist", () => {
|
||||
const orphanEvent: CallEventMapValue = {
|
||||
type: "call.requested",
|
||||
requestId: "req-orphan",
|
||||
operationId: "task.child",
|
||||
input: {},
|
||||
timestamp: "2026-01-01T00:00:00Z",
|
||||
parentRequestId: "req-nonexistent",
|
||||
};
|
||||
const graph = FlowGraph.fromCallEvents([orphanEvent]);
|
||||
expect(graph.order).toBe(1);
|
||||
expect(graph.hasNode("req-orphan")).toBe(true);
|
||||
expect(graph.size).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("FlowGraph.updateFromEvent", () => {
|
||||
it("processes single event for real-time pattern", () => {
|
||||
const graph = new FlowGraph();
|
||||
graph.updateFromEvent({
|
||||
type: "call.requested",
|
||||
requestId: "req-1",
|
||||
operationId: "task.classify",
|
||||
input: { text: "hello" },
|
||||
timestamp: "2026-01-01T00:00:00Z",
|
||||
});
|
||||
expect(graph.hasNode("req-1")).toBe(true);
|
||||
|
||||
graph.updateFromEvent({
|
||||
type: "call.responded",
|
||||
requestId: "req-1",
|
||||
output: { label: "hi" },
|
||||
timestamp: "2026-01-01T00:00:02Z",
|
||||
});
|
||||
const attrs = graph.getNodeAttributes("req-1") as Record<string, unknown>;
|
||||
expect(attrs.status).toBe("completed");
|
||||
expect(attrs.output).toEqual({ label: "hi" });
|
||||
});
|
||||
|
||||
it("ignores events for unknown requestId", () => {
|
||||
const graph = new FlowGraph();
|
||||
graph.updateFromEvent({
|
||||
type: "call.responded",
|
||||
requestId: "unknown",
|
||||
output: "x",
|
||||
timestamp: "2026-01-01T00:00:00Z",
|
||||
});
|
||||
expect(graph.order).toBe(0);
|
||||
});
|
||||
|
||||
it("ignores terminal event re-processing", () => {
|
||||
const graph = new FlowGraph();
|
||||
graph.updateFromEvent({
|
||||
type: "call.requested",
|
||||
requestId: "req-1",
|
||||
operationId: "task.op",
|
||||
input: {},
|
||||
timestamp: "2026-01-01T00:00:00Z",
|
||||
});
|
||||
graph.updateFromEvent({
|
||||
type: "call.responded",
|
||||
requestId: "req-1",
|
||||
output: "done",
|
||||
timestamp: "2026-01-01T00:00:01Z",
|
||||
});
|
||||
graph.updateFromEvent({
|
||||
type: "call.error",
|
||||
requestId: "req-1",
|
||||
error: { code: "X", message: "Y" },
|
||||
timestamp: "2026-01-01T00:00:02Z",
|
||||
});
|
||||
const attrs = graph.getNodeAttributes("req-1") as Record<string, unknown>;
|
||||
expect(attrs.status).toBe("completed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("FlowGraph.addCall", () => {
|
||||
it("adds a call node", () => {
|
||||
const graph = new FlowGraph();
|
||||
graph.addCall({
|
||||
requestId: "req-1",
|
||||
operationId: "task.classify",
|
||||
status: "pending",
|
||||
input: { text: "hello" },
|
||||
});
|
||||
expect(graph.hasNode("req-1")).toBe(true);
|
||||
const attrs = graph.getNodeAttributes("req-1") as Record<string, unknown>;
|
||||
expect(attrs.status).toBe("pending");
|
||||
});
|
||||
|
||||
it("adds triggered edge when parentRequestId is present", () => {
|
||||
const graph = new FlowGraph();
|
||||
graph.addCall({
|
||||
requestId: "req-parent",
|
||||
operationId: "task.parent",
|
||||
status: "pending",
|
||||
input: {},
|
||||
});
|
||||
graph.addCall({
|
||||
requestId: "req-child",
|
||||
operationId: "task.child",
|
||||
status: "pending",
|
||||
input: {},
|
||||
parentRequestId: "req-parent",
|
||||
});
|
||||
expect(graph.hasEdge("req-parent", "req-child")).toBe(true);
|
||||
const edgeAttrs = graph.getEdgeAttributes("req-parent", "req-child") as Record<string, unknown>;
|
||||
expect(edgeAttrs.edgeType).toBe("triggered");
|
||||
});
|
||||
|
||||
it("is idempotent — duplicate addCall is ignored", () => {
|
||||
const graph = new FlowGraph();
|
||||
graph.addCall({
|
||||
requestId: "req-1",
|
||||
operationId: "task.op",
|
||||
status: "pending",
|
||||
input: {},
|
||||
});
|
||||
graph.addCall({
|
||||
requestId: "req-1",
|
||||
operationId: "task.op",
|
||||
status: "pending",
|
||||
input: {},
|
||||
});
|
||||
expect(graph.order).toBe(1);
|
||||
});
|
||||
|
||||
it("does not throw if parentRequestId node does not exist", () => {
|
||||
const graph = new FlowGraph();
|
||||
graph.addCall({
|
||||
requestId: "req-child",
|
||||
operationId: "task.child",
|
||||
status: "pending",
|
||||
input: {},
|
||||
parentRequestId: "nonexistent",
|
||||
});
|
||||
expect(graph.hasNode("req-child")).toBe(true);
|
||||
expect(graph.size).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("FlowGraph.addDependency", () => {
|
||||
it("creates depends_on edge", () => {
|
||||
const graph = new FlowGraph();
|
||||
graph.addCall({ requestId: "req-1", operationId: "task.a", status: "pending", input: {} });
|
||||
graph.addCall({ requestId: "req-2", operationId: "task.b", status: "pending", input: {} });
|
||||
graph.addDependency("req-1", "req-2");
|
||||
const edgeKey = "req-1->req-2:depends_on";
|
||||
expect(graph.graph.hasEdge(edgeKey)).toBe(true);
|
||||
const attrs = graph.graph.getEdgeAttributes(edgeKey) as Record<string, unknown>;
|
||||
expect(attrs.edgeType).toBe("depends_on");
|
||||
});
|
||||
|
||||
it("is idempotent — duplicate addDependency is ignored", () => {
|
||||
const graph = new FlowGraph();
|
||||
graph.addCall({ requestId: "req-1", operationId: "task.a", status: "pending", input: {} });
|
||||
graph.addCall({ requestId: "req-2", operationId: "task.b", status: "pending", input: {} });
|
||||
graph.addDependency("req-1", "req-2");
|
||||
graph.addDependency("req-1", "req-2");
|
||||
expect(graph.graph.hasEdge("req-1->req-2:depends_on")).toBe(true);
|
||||
});
|
||||
|
||||
it("throws NodeNotFoundError if source doesn't exist", () => {
|
||||
const graph = new FlowGraph();
|
||||
graph.addCall({ requestId: "req-2", operationId: "task.b", status: "pending", input: {} });
|
||||
expect(() => graph.addDependency("missing", "req-2")).toThrow(NodeNotFoundError);
|
||||
});
|
||||
|
||||
it("throws NodeNotFoundError if target doesn't exist", () => {
|
||||
const graph = new FlowGraph();
|
||||
graph.addCall({ requestId: "req-1", operationId: "task.a", status: "pending", input: {} });
|
||||
expect(() => graph.addDependency("req-1", "missing")).toThrow(NodeNotFoundError);
|
||||
});
|
||||
|
||||
it("throws CycleError if adding would create cycle", () => {
|
||||
const graph = new FlowGraph();
|
||||
graph.addCall({ requestId: "req-1", operationId: "task.a", status: "pending", input: {} });
|
||||
graph.addCall({ requestId: "req-2", operationId: "task.b", status: "pending", input: {} });
|
||||
graph.addCall({ requestId: "req-3", operationId: "task.c", status: "pending", input: {} });
|
||||
graph.addEdge("req-1", "req-2");
|
||||
graph.addEdge("req-2", "req-3");
|
||||
expect(() => graph.addDependency("req-3", "req-1")).toThrow(CycleError);
|
||||
});
|
||||
});
|
||||
|
||||
describe("FlowGraph.updateStatus", () => {
|
||||
it("transitions pending to running", () => {
|
||||
const graph = new FlowGraph();
|
||||
graph.addCall({ requestId: "req-1", operationId: "task.op", status: "pending", input: {} });
|
||||
graph.updateStatus("req-1", "running");
|
||||
const attrs = graph.getNodeAttributes("req-1") as Record<string, unknown>;
|
||||
expect(attrs.status).toBe("running");
|
||||
});
|
||||
|
||||
it("transitions running to completed", () => {
|
||||
const graph = new FlowGraph();
|
||||
graph.addCall({ requestId: "req-1", operationId: "task.op", status: "pending", input: {} });
|
||||
graph.updateStatus("req-1", "running");
|
||||
graph.updateStatus("req-1", "completed", { completedAt: "2026-01-01T00:00:01Z" });
|
||||
const attrs = graph.getNodeAttributes("req-1") as Record<string, unknown>;
|
||||
expect(attrs.status).toBe("completed");
|
||||
expect(attrs.completedAt).toBe("2026-01-01T00:00:01Z");
|
||||
});
|
||||
|
||||
it("transitions running to failed", () => {
|
||||
const graph = new FlowGraph();
|
||||
graph.addCall({ requestId: "req-1", operationId: "task.op", status: "pending", input: {} });
|
||||
graph.updateStatus("req-1", "running");
|
||||
graph.updateStatus("req-1", "failed");
|
||||
const attrs = graph.getNodeAttributes("req-1") as Record<string, unknown>;
|
||||
expect(attrs.status).toBe("failed");
|
||||
});
|
||||
|
||||
it("transitions pending to aborted", () => {
|
||||
const graph = new FlowGraph();
|
||||
graph.addCall({ requestId: "req-1", operationId: "task.op", status: "pending", input: {} });
|
||||
graph.updateStatus("req-1", "aborted");
|
||||
const attrs = graph.getNodeAttributes("req-1") as Record<string, unknown>;
|
||||
expect(attrs.status).toBe("aborted");
|
||||
});
|
||||
|
||||
it("transitions running to aborted", () => {
|
||||
const graph = new FlowGraph();
|
||||
graph.addCall({ requestId: "req-1", operationId: "task.op", status: "pending", input: {} });
|
||||
graph.updateStatus("req-1", "running");
|
||||
graph.updateStatus("req-1", "aborted");
|
||||
const attrs = graph.getNodeAttributes("req-1") as Record<string, unknown>;
|
||||
expect(attrs.status).toBe("aborted");
|
||||
});
|
||||
|
||||
it("is no-op if status is already the target", () => {
|
||||
const graph = new FlowGraph();
|
||||
graph.addCall({ requestId: "req-1", operationId: "task.op", status: "pending", input: {} });
|
||||
graph.updateStatus("req-1", "pending");
|
||||
const attrs = graph.getNodeAttributes("req-1") as Record<string, unknown>;
|
||||
expect(attrs.status).toBe("pending");
|
||||
});
|
||||
|
||||
it("throws InvalidTransitionError for completed to running", () => {
|
||||
const graph = new FlowGraph();
|
||||
graph.addCall({ requestId: "req-1", operationId: "task.op", status: "pending", input: {} });
|
||||
graph.updateStatus("req-1", "running");
|
||||
graph.updateStatus("req-1", "completed", { completedAt: "2026-01-01T00:00:01Z" });
|
||||
expect(() => graph.updateStatus("req-1", "running")).toThrow(InvalidTransitionError);
|
||||
});
|
||||
|
||||
it("throws InvalidTransitionError for failed to running", () => {
|
||||
const graph = new FlowGraph();
|
||||
graph.addCall({ requestId: "req-1", operationId: "task.op", status: "pending", input: {} });
|
||||
graph.updateStatus("req-1", "running");
|
||||
graph.updateStatus("req-1", "failed");
|
||||
expect(() => graph.updateStatus("req-1", "running")).toThrow(InvalidTransitionError);
|
||||
});
|
||||
|
||||
it("throws InvalidTransitionError for aborted to running", () => {
|
||||
const graph = new FlowGraph();
|
||||
graph.addCall({ requestId: "req-1", operationId: "task.op", status: "pending", input: {} });
|
||||
graph.updateStatus("req-1", "aborted");
|
||||
expect(() => graph.updateStatus("req-1", "running")).toThrow(InvalidTransitionError);
|
||||
});
|
||||
|
||||
it("throws InvalidTransitionError for pending to completed", () => {
|
||||
const graph = new FlowGraph();
|
||||
graph.addCall({ requestId: "req-1", operationId: "task.op", status: "pending", input: {} });
|
||||
expect(() => graph.updateStatus("req-1", "completed")).toThrow(InvalidTransitionError);
|
||||
});
|
||||
|
||||
it("throws InvalidTransitionError for pending to failed", () => {
|
||||
const graph = new FlowGraph();
|
||||
graph.addCall({ requestId: "req-1", operationId: "task.op", status: "pending", input: {} });
|
||||
expect(() => graph.updateStatus("req-1", "failed")).toThrow(InvalidTransitionError);
|
||||
});
|
||||
|
||||
it("throws NodeNotFoundError for unknown requestId", () => {
|
||||
const graph = new FlowGraph();
|
||||
expect(() => graph.updateStatus("missing", "running")).toThrow(NodeNotFoundError);
|
||||
});
|
||||
|
||||
it("InvalidTransitionError contains from/to info", () => {
|
||||
const graph = new FlowGraph();
|
||||
graph.addCall({ requestId: "req-1", operationId: "task.op", status: "pending", input: {} });
|
||||
graph.updateStatus("req-1", "running");
|
||||
graph.updateStatus("req-1", "completed", { completedAt: "2026-01-01T00:00:01Z" });
|
||||
try {
|
||||
graph.updateStatus("req-1", "running");
|
||||
expect.unreachable("should throw");
|
||||
} catch (e) {
|
||||
expect(e).toBeInstanceOf(InvalidTransitionError);
|
||||
const ite = e as InvalidTransitionError;
|
||||
expect(ite.requestId).toBe("req-1");
|
||||
expect(ite.from).toBe("completed" as CallStatus);
|
||||
expect(ite.to).toBe("running" as CallStatus);
|
||||
}
|
||||
});
|
||||
|
||||
it("merges extra attributes on transition", () => {
|
||||
const graph = new FlowGraph();
|
||||
graph.addCall({ requestId: "req-1", operationId: "task.op", status: "pending", input: {} });
|
||||
graph.updateStatus("req-1", "running");
|
||||
graph.updateStatus("req-1", "completed", {
|
||||
output: { result: 42 },
|
||||
completedAt: "2026-01-01T00:00:01Z",
|
||||
});
|
||||
const attrs = graph.getNodeAttributes("req-1") as Record<string, unknown>;
|
||||
expect(attrs.status).toBe("completed");
|
||||
expect(attrs.output).toEqual({ result: 42 });
|
||||
expect(attrs.completedAt).toBe("2026-01-01T00:00:01Z");
|
||||
});
|
||||
});
|
||||
|
||||
describe("FlowGraph.updateCall", () => {
|
||||
it("partially merges call attributes", () => {
|
||||
const graph = new FlowGraph();
|
||||
graph.addCall({
|
||||
requestId: "req-1",
|
||||
operationId: "task.op",
|
||||
status: "pending",
|
||||
input: {},
|
||||
});
|
||||
graph.updateCall("req-1", { output: "some result" });
|
||||
const attrs = graph.getNodeAttributes("req-1") as Record<string, unknown>;
|
||||
expect(attrs.output).toBe("some result");
|
||||
expect(attrs.status).toBe("pending");
|
||||
});
|
||||
|
||||
it("throws NodeNotFoundError for unknown requestId", () => {
|
||||
const graph = new FlowGraph();
|
||||
expect(() => graph.updateCall("missing", { output: "x" })).toThrow(NodeNotFoundError);
|
||||
});
|
||||
});
|
||||
|
||||
describe("FlowGraph.removeCall", () => {
|
||||
it("removes node and attached edges", () => {
|
||||
const graph = new FlowGraph();
|
||||
graph.addCall({ requestId: "req-1", operationId: "task.parent", status: "pending", input: {} });
|
||||
graph.addCall({ requestId: "req-2", operationId: "task.child", status: "pending", input: {}, parentRequestId: "req-1" });
|
||||
expect(graph.size).toBe(1);
|
||||
graph.removeCall("req-2");
|
||||
expect(graph.hasNode("req-2")).toBe(false);
|
||||
expect(graph.size).toBe(0);
|
||||
expect(graph.hasNode("req-1")).toBe(true);
|
||||
});
|
||||
|
||||
it("is a no-op if requestId doesn't exist", () => {
|
||||
const graph = new FlowGraph();
|
||||
expect(() => graph.removeCall("missing")).not.toThrow();
|
||||
});
|
||||
});
|
||||
232
test/graph/serialization.test.ts
Normal file
232
test/graph/serialization.test.ts
Normal file
@@ -0,0 +1,232 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { Type } from "@alkdev/typebox";
|
||||
import { FlowGraph } from "../../src/graph/construction.js";
|
||||
import type { OperationSpec } from "../../src/graph/construction.js";
|
||||
import { InvalidInputError, CycleError } from "../../src/error/index.js";
|
||||
|
||||
describe("FlowGraph.export", () => {
|
||||
it("returns graphology native JSON format for empty graph", () => {
|
||||
const fg = new FlowGraph();
|
||||
const data = fg.export();
|
||||
expect(data.options).toEqual({ type: "directed", multi: false, allowSelfLoops: false });
|
||||
expect(data.attributes).toEqual({});
|
||||
expect(data.nodes).toEqual([]);
|
||||
expect(data.edges).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns graphology native JSON format for operation graph", () => {
|
||||
const specs: OperationSpec[] = [
|
||||
{ name: "extract", namespace: "task", version: "1.0.0", type: "query", inputSchema: Type.Object({ raw: Type.String() }), outputSchema: Type.Object({ text: Type.String() }) },
|
||||
{ name: "classify", namespace: "task", version: "1.0.0", type: "query", inputSchema: Type.Object({ text: Type.String() }), outputSchema: Type.Object({ label: Type.String() }) },
|
||||
];
|
||||
const graph = FlowGraph.fromSpecs(specs);
|
||||
const data = graph.export();
|
||||
expect(data.options.type).toBe("directed");
|
||||
expect(data.nodes.length).toBe(2);
|
||||
expect(data.edges.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("FlowGraph.toJSON", () => {
|
||||
it("is an alias for export", () => {
|
||||
const fg = new FlowGraph();
|
||||
fg.addNode("a", { name: "a" } as never);
|
||||
const exported = fg.export();
|
||||
const jsoned = fg.toJSON();
|
||||
expect(jsoned).toEqual(exported);
|
||||
});
|
||||
});
|
||||
|
||||
describe("FlowGraph.toString", () => {
|
||||
it("returns JSON.stringify of export()", () => {
|
||||
const fg = new FlowGraph();
|
||||
fg.addNode("a", { name: "a" } as never);
|
||||
expect(fg.toString()).toBe(JSON.stringify(fg.export()));
|
||||
});
|
||||
|
||||
it("round-trips through JSON.parse", () => {
|
||||
const fg = new FlowGraph();
|
||||
fg.addNode("a", { name: "a" } as never);
|
||||
const parsed = JSON.parse(fg.toString());
|
||||
expect(parsed.options).toEqual({ type: "directed", multi: false, allowSelfLoops: false });
|
||||
});
|
||||
});
|
||||
|
||||
describe("FlowGraph.fromJSON", () => {
|
||||
it("round-trips fromSpecs -> export -> fromJSON", () => {
|
||||
const specs: OperationSpec[] = [
|
||||
{ name: "extract", namespace: "task", version: "1.0.0", type: "query", inputSchema: Type.Object({ raw: Type.String() }), outputSchema: Type.Object({ text: Type.String() }) },
|
||||
{ name: "classify", namespace: "task", version: "1.0.0", type: "query", inputSchema: Type.Object({ text: Type.String() }), outputSchema: Type.Object({ label: Type.String() }) },
|
||||
];
|
||||
const original = FlowGraph.fromSpecs(specs);
|
||||
const data = original.export();
|
||||
const restored = FlowGraph.fromJSON(data);
|
||||
expect(restored.order).toBe(original.order);
|
||||
expect(restored.size).toBe(original.size);
|
||||
for (const node of original.nodes()) {
|
||||
expect(restored.hasNode(node)).toBe(true);
|
||||
const origAttrs = original.getNodeAttributes(node as never) as Record<string, unknown>;
|
||||
const restAttrs = restored.getNodeAttributes(node as never) as Record<string, unknown>;
|
||||
expect(restAttrs.name).toBe(origAttrs.name);
|
||||
expect(restAttrs.namespace).toBe(origAttrs.namespace);
|
||||
}
|
||||
for (const edge of original.edges()) {
|
||||
const source = edge.split("->")[0]!;
|
||||
const target = edge.split("->")[1]!;
|
||||
expect(restored.hasEdge(source, target)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("round-trips empty graph", () => {
|
||||
const fg = new FlowGraph();
|
||||
const data = fg.export();
|
||||
const restored = FlowGraph.fromJSON(data);
|
||||
expect(restored.order).toBe(0);
|
||||
expect(restored.size).toBe(0);
|
||||
expect(restored.export()).toEqual(data);
|
||||
});
|
||||
|
||||
it("throws InvalidInputError on invalid input", () => {
|
||||
expect(() => FlowGraph.fromJSON({})).toThrow(InvalidInputError);
|
||||
});
|
||||
|
||||
it("InvalidInputError contains errors array", () => {
|
||||
try {
|
||||
FlowGraph.fromJSON({});
|
||||
expect.unreachable("should throw");
|
||||
} catch (e) {
|
||||
expect(e).toBeInstanceOf(InvalidInputError);
|
||||
const err = e as InvalidInputError;
|
||||
expect(err.errors.length).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
|
||||
it("throws InvalidInputError on missing nodes", () => {
|
||||
const bad = {
|
||||
options: { type: "directed", multi: false, allowSelfLoops: false },
|
||||
attributes: {},
|
||||
edges: [],
|
||||
};
|
||||
expect(() => FlowGraph.fromJSON(bad as never)).toThrow(InvalidInputError);
|
||||
});
|
||||
|
||||
it("throws CycleError on cyclic input", () => {
|
||||
const cyclicData = {
|
||||
options: { type: "directed", multi: false, allowSelfLoops: false },
|
||||
attributes: {},
|
||||
nodes: [
|
||||
{ key: "a", attributes: { requestId: "a", operationId: "op.a", status: "completed", input: {} } },
|
||||
{ key: "b", attributes: { requestId: "b", operationId: "op.b", status: "completed", input: {} } },
|
||||
],
|
||||
edges: [
|
||||
{ key: "a->b", source: "a", target: "b", attributes: {} },
|
||||
{ key: "b->a", source: "b", target: "a", attributes: {} },
|
||||
],
|
||||
};
|
||||
expect(() => FlowGraph.fromJSON(cyclicData as never)).toThrow(CycleError);
|
||||
});
|
||||
|
||||
it("CycleError contains cycle paths on cyclic input", () => {
|
||||
const cyclicData = {
|
||||
options: { type: "directed", multi: false, allowSelfLoops: false },
|
||||
attributes: {},
|
||||
nodes: [
|
||||
{ key: "a", attributes: { requestId: "a", operationId: "op.a", status: "completed", input: {} } },
|
||||
{ key: "b", attributes: { requestId: "b", operationId: "op.b", status: "completed", input: {} } },
|
||||
],
|
||||
edges: [
|
||||
{ key: "a->b", source: "a", target: "b", attributes: {} },
|
||||
{ key: "b->a", source: "b", target: "a", attributes: {} },
|
||||
],
|
||||
};
|
||||
try {
|
||||
FlowGraph.fromJSON(cyclicData as never);
|
||||
expect.unreachable("should throw");
|
||||
} catch (e) {
|
||||
expect(e).toBeInstanceOf(CycleError);
|
||||
const ce = e as CycleError;
|
||||
expect(ce.cycles.length).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves node attributes through round-trip", () => {
|
||||
const specs: OperationSpec[] = [
|
||||
{ name: "classify", namespace: "task", version: "2.0.0", type: "mutation", inputSchema: Type.Object({ text: Type.String() }), outputSchema: Type.Object({ label: Type.String() }), description: "Classifies text", tags: ["nlp"] },
|
||||
];
|
||||
const original = FlowGraph.fromSpecs(specs);
|
||||
const data = original.export();
|
||||
const restored = FlowGraph.fromJSON(data);
|
||||
const origAttrs = original.getNodeAttributes("task.classify" as never) as Record<string, unknown>;
|
||||
const restAttrs = restored.getNodeAttributes("task.classify" as never) as Record<string, unknown>;
|
||||
expect(restAttrs.name).toBe(origAttrs.name);
|
||||
expect(restAttrs.namespace).toBe(origAttrs.namespace);
|
||||
expect(restAttrs.version).toBe(origAttrs.version);
|
||||
expect(restAttrs.type).toBe(origAttrs.type);
|
||||
expect(restAttrs.description).toBe(origAttrs.description);
|
||||
expect(restAttrs.tags).toEqual(origAttrs.tags);
|
||||
});
|
||||
|
||||
it("preserves edge attributes through round-trip", () => {
|
||||
const specs: OperationSpec[] = [
|
||||
{ name: "extract", namespace: "task", version: "1.0.0", type: "query", inputSchema: Type.Object({ raw: Type.String() }), outputSchema: Type.Object({ text: Type.String() }) },
|
||||
{ name: "classify", namespace: "task", version: "1.0.0", type: "query", inputSchema: Type.Object({ text: Type.String() }), outputSchema: Type.Object({ label: Type.String() }) },
|
||||
];
|
||||
const original = FlowGraph.fromSpecs(specs);
|
||||
const data = original.export();
|
||||
const restored = FlowGraph.fromJSON(data);
|
||||
const origEdgeAttrs = original.getEdgeAttributes("task.extract", "task.classify") as Record<string, unknown>;
|
||||
const restEdgeAttrs = restored.getEdgeAttributes("task.extract", "task.classify") as Record<string, unknown>;
|
||||
expect(restEdgeAttrs.edgeType).toBe(origEdgeAttrs.edgeType);
|
||||
expect(restEdgeAttrs.compatible).toBe(origEdgeAttrs.compatible);
|
||||
});
|
||||
|
||||
it("double round-trip is lossless", () => {
|
||||
const specs: OperationSpec[] = [
|
||||
{ name: "extract", namespace: "task", version: "1.0.0", type: "query", inputSchema: Type.Object({ raw: Type.String() }), outputSchema: Type.Object({ text: Type.String() }) },
|
||||
{ name: "classify", namespace: "task", version: "1.0.0", type: "query", inputSchema: Type.Object({ text: Type.String() }), outputSchema: Type.Object({ label: Type.String() }) },
|
||||
];
|
||||
const original = FlowGraph.fromSpecs(specs);
|
||||
const first = original.export();
|
||||
const restored1 = FlowGraph.fromJSON(first);
|
||||
const second = restored1.export();
|
||||
const restored2 = FlowGraph.fromJSON(second);
|
||||
const third = restored2.export();
|
||||
expect(third).toEqual(first);
|
||||
expect(third).toEqual(second);
|
||||
});
|
||||
|
||||
it("accepts valid call graph serialized data", () => {
|
||||
const callData = {
|
||||
options: { type: "directed", multi: false, allowSelfLoops: false },
|
||||
attributes: {},
|
||||
nodes: [
|
||||
{
|
||||
key: "req_1",
|
||||
attributes: {
|
||||
requestId: "req_1",
|
||||
operationId: "task.classify",
|
||||
status: "completed",
|
||||
input: { text: "hello" },
|
||||
output: { label: "greeting" },
|
||||
},
|
||||
},
|
||||
],
|
||||
edges: [],
|
||||
};
|
||||
const fg = FlowGraph.fromJSON(callData as never);
|
||||
expect(fg.order).toBe(1);
|
||||
expect(fg.hasNode("req_1")).toBe(true);
|
||||
});
|
||||
|
||||
it("throws InvalidInputError for invalid node attributes", () => {
|
||||
const bad = {
|
||||
options: { type: "directed", multi: false, allowSelfLoops: false },
|
||||
attributes: {},
|
||||
nodes: [
|
||||
{ key: "a", attributes: { invalid: true } },
|
||||
],
|
||||
edges: [],
|
||||
};
|
||||
expect(() => FlowGraph.fromJSON(bad as never)).toThrow(InvalidInputError);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user