All files / src/util pipelineUtils.ts

98.43% Statements 189/192
93.24% Branches 138/148
100% Functions 47/47
100% Lines 152/152

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499                                                                                                                                                                          136x 51x 208x                   147x 145x 136x 129x 2x 127x           280x 80x 71x   64x                       319x                     54x 54x 67x 67x 17x 17x 17x 52x   44x 17x 11x 10x   8x 2x   4x                         285x 285x 285x 285x 299x   299x 198x   101x 1x 1x   101x 101x   299x 299x 251x 205x 299x   285x       85x 270x               113x 183x 79x   104x 30x   104x     30x                   85x 85x 188x 62x             228x           129x 28x 83x           21x             15x 15x 2x 15x 15x     1x             16x               16x                                         6x 4x 6x 6x 5x 5x 6x 4x 4x 4x 1x 1x     4x 4x                           64x   72x 64x     64x 6x         6x 48x         64x 147x   64x     64x 3x 23x 5x 5x         64x                                                     64x 64x 64x 491x     64x     64x 64x   64x 147x       147x 147x 132x 132x 132x 132x 132x     15x   147x 147x 147x 147x     64x       64x   64x 64x   64x 383x         15x 15x 15x 15x                       64x 64x 319x 319x 319x       319x 76x 243x     112x   144x   99x   319x                       319x     64x             3x 3x         145x 92x      
import {
  GraphPlanStage,
  NodeExecution,
  SystemNodeResult,
  TraceEvent,
} from "@/objects/Model";
import { NodeHitl } from "@/objects/Hitl";
import {
  KNOWLEDGE_PLAN_NODE_ID,
  LANE_NODE_IDS,
  RETRIEVAL_JOIN_NODE_ID,
} from "@/objects/systemNodes";
import { knowledgeMix, knowledgePlanResult, laneSearchResult } from "@/util/systemNodeTrace";
import { isSystemNodeId } from "@/util/traceUtils";
 
/**
 * Derivation of the CI-style pipeline view from a `graph_plan` frame plus the
 * node events seen so far.
 *
 * svc-ai announces the whole pipeline before the first node runs, so every
 * stage can be rendered immediately — pending ones greyed out, the active one
 * highlighted, bypassed ones marked skipped — instead of the view growing a
 * card at a time.  Everything here is pure so the rendering components stay
 * presentational and the state machine is unit-testable.
 */
 
// ─── Types ────────────────────────────────────────────────────────────────────
 
export type StageState =
  | "pending"
  | "running"
  /** Stopped for a person — waiting on their answer or approval. */
  | "awaiting"
  | "done"
  /** A parallel stage some of whose branches failed while the rest, and
   *  the node they meet in, went on. */
  | "degraded"
  | "skipped"
  | "failed";
 
/** One execution of one node inside a stage (a node can run more than once). */
export type PipelineAttempt = {
  execution: NodeExecution;
  state: Extract<StageState, "running" | "awaiting" | "done" | "failed">;
};
 
export type PipelineStage = {
  id: string;
  /** Node IDs this stage covers — several when only a subset of them runs. */
  node_ids: string[];
  is_system_stage: boolean;
  optional: boolean;
  state: StageState;
  /** Executions attributed to this stage, in arrival order. */
  attempts: PipelineAttempt[];
  /** True for stages synthesised from unplanned nodes (rule enforcement etc.). */
  unplanned: boolean;
  /** A parallel stage's fork, branches and join (`GraphPlanStage`). */
  fork?: string;
  branches?: string[];
  join?: string;
};
 
/**
 * One pass of a stage: what it ran on the graph's first pass, or on a
 * revision after the quality check. A parallel stage's pass is a fork, the
 * branches it started side by side, and the join they met in; any other
 * stage's is its executions on that pass (more than one when a pause
 * replayed it).
 */
export type StagePass = {
  /** 0 the first, one more per revision. */
  index: number;
  fork?: PipelineAttempt;
  branches: PipelineAttempt[];
  join?: PipelineAttempt;
};
 
// ─── Node-level state ─────────────────────────────────────────────────────────
 
/**
 * System nodes report failures inside their structured result rather than on
 * the node_end frame, under an `error`-suffixed key (`error`, `plan_error`, …).
 */
function hasResultError(result: SystemNodeResult | undefined): boolean {
  if (!result) return false;
  return Object.entries(result).some(
    ([key, value]) =>
      (key === "error" || key.endsWith("_error")) &&
      typeof value === "string" &&
      value.trim().length > 0,
  );
}
 
function attemptState(node: NodeExecution): PipelineAttempt["state"] {
  // A paused execution never gets a node_end: the run replays the node after
  // the answer, as a new attempt. So the pause itself decides this one.
  if (node.hitl) return node.hitl.resume ? "done" : "awaiting";
  if (!node.done) return "running";
  if (hasResultError(node.system_result)) return "failed";
  if (node.tools.length > 0 && node.tools.every((t) => t.status === "error"))
    return "failed";
  return "done";
}
 
function stageStateFromAttempts(
  attempts: PipelineAttempt[],
): StageState | null {
  if (attempts.length === 0) return null;
  if (attempts.some((a) => a.state === "running")) return "running";
  if (attempts.some((a) => a.state === "awaiting")) return "awaiting";
  // A retried node that ultimately succeeded is a pass, not a failure.
  return attempts[attempts.length - 1].state;
}
 
/** Whether a stage's nodes may run side by side: a fork and a join, or —
 *  on traces from before them — a system stage holding several nodes (the
 *  retrieval stage's internal ∥ external). */
export function isParallelStage(stage: {
  fork?: string;
  join?: string;
  node_ids: string[];
  is_system_stage: boolean;
}): boolean {
  return !!(stage.fork || stage.join) || (stage.is_system_stage && stage.node_ids.length > 1);
}
 
/**
 * A parallel stage's state, from its latest pass: failed only when the join
 * failed or, with no join, every branch did; degraded when something else
 * failed and the stage went on; done otherwise.
 */
function parallelStageState(
  stage: Pick<PipelineStage, "fork" | "join" | "attempts">,
): StageState | null {
  const { attempts } = stage;
  if (attempts.length === 0) return null;
  Iif (attempts.some((a) => a.state === "running")) return "running";
  Iif (attempts.some((a) => a.state === "awaiting")) return "awaiting";
  const passes = buildFlows(stage);
  const last = passes[passes.length - 1];
  const before = [last.fork, ...last.branches].filter(
    (a): a is PipelineAttempt => !!a,
  );
  const someFailed = before.some((a) => a.state === "failed");
  if (last.join) {
    if (last.join.state === "failed") return "failed";
    return someFailed ? "degraded" : "done";
  }
  if (before.length > 0 && before.every((a) => a.state === "failed")) {
    return "failed";
  }
  return someFailed ? "degraded" : "done";
}
 
// ─── Passes, branches and time ────────────────────────────────────────────────
 
/**
 * A stage's executions by pass, then by branch. The pass is the one each
 * execution started on (`pass`); a trace stored before it is read as a new
 * pass each time a node it already holds runs again.
 */
export function buildFlows(
  stage: Pick<PipelineStage, "fork" | "join" | "attempts">,
): StagePass[] {
  const passes = new Map<number, StagePass>();
  let inferred = 0;
  const seen = new Set<string>();
  for (const attempt of stage.attempts) {
    const nodeId = attempt.execution.node_id;
    let index: number;
    if (typeof attempt.execution.pass === "number") {
      index = attempt.execution.pass;
    } else {
      if (seen.has(nodeId)) {
        inferred += 1;
        seen.clear();
      }
      seen.add(nodeId);
      index = inferred;
    }
    const pass = passes.get(index) ?? { index, branches: [] };
    if (stage.fork && nodeId === stage.fork && !pass.fork) pass.fork = attempt;
    else if (stage.join && nodeId === stage.join && !pass.join) pass.join = attempt;
    else pass.branches.push(attempt);
    passes.set(index, pass);
  }
  return Array.from(passes.values()).sort((a, b) => a.index - b.index);
}
 
function attemptsOf(pass: StagePass): PipelineAttempt[] {
  return [pass.fork, ...pass.branches, pass.join].filter(
    (a): a is PipelineAttempt => !!a,
  );
}
 
/** Wall clock over executions that say when they ran: from the first start
 *  to the last end (or start, for one still running). Null when any does
 *  not say. */
function clockSpan(attempts: PipelineAttempt[]): number | null {
  if (attempts.length === 0) return 0;
  if (!attempts.every((a) => typeof a.execution.started_ms === "number")) {
    return null;
  }
  const start = Math.min(...attempts.map((a) => a.execution.started_ms as number));
  const end = Math.max(
    ...attempts.map(
      (a) => a.execution.ended_ms ?? (a.execution.started_ms as number),
    ),
  );
  return Math.max(0, end - start);
}
 
/**
 * How long one pass took. Measured, from the first start to the last end;
 * on a trace from before nodes said when they ran, what ran in turn (the
 * fork, the join) plus the longest of what ran side by side — never their
 * sum, which counted parallel searches twice.
 */
export function passWallClock(pass: StagePass): number {
  const span = clockSpan(attemptsOf(pass));
  if (span !== null) return span;
  const d = (a?: PipelineAttempt) => a?.execution.duration_ms ?? 0;
  return d(pass.fork) + Math.max(0, ...pass.branches.map(d)) + d(pass.join);
}
 
/** How long a stage took: each of its passes, one after another. */
export function stageWallClock(
  stage: Pick<PipelineStage, "fork" | "join" | "attempts">,
): number {
  return buildFlows(stage).reduce((total, pass) => total + passWallClock(pass), 0);
}
 
/** How long the run took, as the header says: measured from its first
 *  start to its last end, else each stage's own time added up. */
export function runWallClock(stages: PipelineStage[]): number {
  const span = clockSpan(stages.flatMap((s) => s.attempts));
  if (span !== null) return span;
  return stages.reduce((total, stage) => total + stageWallClock(stage), 0);
}
 
/** How many passes a stage ran: more than one only when the graph came
 *  back to it (a revision), never for branches that ran side by side. */
export function stagePassCount(stage: PipelineStage): number {
  return buildFlows(stage).length;
}
 
/** A branch's role in the turn's knowledge mix (`primary`, `supporting`,
 *  `method`): the lane's own result once it ends, else the plan's. Empty
 *  for the web, the tools and traces from before the lanes. */
export function branchRole(pass: StagePass, attempt: PipelineAttempt): string {
  const own = laneSearchResult(attempt.execution.system_result)?.role;
  if (own) return own;
  const planned = knowledgePlanResult(pass.fork?.execution.system_result);
  const nodeId = attempt.execution.node_id;
  return (
    planned?.lanes.find(
      (lane) =>
        LANE_NODE_IDS[lane.category as keyof typeof LANE_NODE_IDS] === nodeId,
    )?.role ?? ""
  );
}
 
// ─── Predictive pruning ───────────────────────────────────────────────────────
 
const RETRIEVAL_NODE_BY_TARGET: Record<string, string> = {
  internal: "__internal_retrieval__",
  external: "__external_retrieval__",
  tools: "__tool_retrieval__",
};
 
/** Every node a retrieval stage may hold: today's (the plan, a lane per
 *  kind, the join) and a stored trace's (one internal node). */
const RETRIEVAL_NODES: string[] = [
  ...Object.values(RETRIEVAL_NODE_BY_TARGET),
  KNOWLEDGE_PLAN_NODE_ID,
  ...Object.values(LANE_NODE_IDS),
  RETRIEVAL_JOIN_NODE_ID,
];
 
/**
 * The retrieval nodes a gate decision dispatches to.
 *
 * Mirrors svc-ai's `_retrieval_targets` / `_planning_router`: only a
 * `retrieve` route retrieves at all, `both` means internal ∥ external, and
 * targets may arrive "+"-joined (e.g. `internal+tools`). Searching the
 * knowledge runs the plan and the lanes the turn's mix names (the gate's
 * `knowledge_mix`; none without one), and every route meets in the join.
 */
function expectedRetrievalNodes(
  route: string,
  retrievalType: string,
  mix: unknown,
): string[] {
  if (route !== "retrieve") return [];
  const raw = (retrievalType || "internal").trim().toLowerCase();
  const targets = raw === "both" ? ["internal", "external"] : raw.split("+");
  const nodes = targets
    .map((t) => RETRIEVAL_NODE_BY_TARGET[t.trim()])
    .filter((n): n is string => !!n);
  Iif (nodes.length === 0) nodes.push(RETRIEVAL_NODE_BY_TARGET.internal);
  Eif (nodes.includes(RETRIEVAL_NODE_BY_TARGET.internal)) {
    nodes.push(KNOWLEDGE_PLAN_NODE_ID);
    for (const lane of knowledgeMix(mix)?.lanes ?? []) {
      const nodeId = LANE_NODE_IDS[lane.category as keyof typeof LANE_NODE_IDS];
      Eif (nodeId) nodes.push(nodeId);
    }
  }
  nodes.push(RETRIEVAL_JOIN_NODE_ID);
  return nodes;
}
 
/**
 * Nodes the run has already committed to *not* executing.
 *
 * The gate publishes its retrieval route and the planner publishes its
 * dispatch list, so stages that will never run are greyed out as skipped the
 * moment those land rather than when the turn ends.
 */
function bypassedNodes(
  planned: GraphPlanStage[],
  executions: NodeExecution[],
): Set<string> {
  const bypassed = new Set<string>();
 
  const gate = executions.find((n) => n.node_id === "__gate__" && n.done);
  const gateResult = gate?.system_result as
    | { route?: string; retrieval_type?: string; knowledge_mix?: unknown }
    | undefined;
  if (gateResult?.route) {
    const expected = expectedRetrievalNodes(
      gateResult.route,
      gateResult.retrieval_type ?? "",
      gateResult.knowledge_mix,
    );
    for (const nodeId of RETRIEVAL_NODES) {
      if (!expected.includes(nodeId)) bypassed.add(nodeId);
    }
  }
 
  // Last planning pass wins — an evaluator retry can re-plan the dispatch.
  const planning = executions
    .filter((n) => n.node_id === "__planning__" && n.done)
    .pop();
  const active = (
    planning?.system_result as { active_node_ids?: string[] } | undefined
  )?.active_node_ids;
  if (Array.isArray(active)) {
    for (const stage of planned) {
      if (stage.is_system_stage) continue;
      for (const nodeId of stage.node_ids) {
        if (!active.includes(nodeId)) bypassed.add(nodeId);
      }
    }
  }
 
  return bypassed;
}
 
// ─── Stage assembly ───────────────────────────────────────────────────────────
 
export type BuildPipelineArgs = {
  /** Stages announced by svc-ai; absent for runs that never sent a plan. */
  plan: GraphPlanStage[] | undefined;
  executions: NodeExecution[];
  /** True once the turn has finished — every unreached stage is then skipped. */
  finished: boolean;
};
 
/**
 * Merge the announced plan with observed executions into one ordered stage
 * list.
 *
 * Unplanned nodes (rule enforcement injected by svc-core, nodes from a plan
 * that predates a graph change) become their own stages, anchored after the
 * last planned stage that had started when they arrived — so the pipeline
 * stays chronological even when it does not match the plan.
 */
export function buildPipeline({
  plan,
  executions,
  finished,
}: BuildPipelineArgs): PipelineStage[] {
  const planned = plan ?? [];
  const stageIndexByNode = new Map<string, number>();
  planned.forEach((stage, i) => {
    for (const nodeId of stage.node_ids) stageIndexByNode.set(nodeId, i);
  });
 
  const attemptsByStage = new Map<number, PipelineAttempt[]>();
  // Unplanned nodes keyed by the planned stage index they follow (-1 = before
  // the pipeline proper, which is where input-phase rule nodes land).
  const unplannedByAnchor = new Map<number, Map<string, PipelineAttempt[]>>();
  let cursor = -1;
 
  for (const execution of executions) {
    const attempt: PipelineAttempt = {
      execution,
      state: attemptState(execution),
    };
    const index = stageIndexByNode.get(execution.node_id);
    if (index !== undefined) {
      cursor = Math.max(cursor, index);
      const list = attemptsByStage.get(index) ?? [];
      list.push(attempt);
      attemptsByStage.set(index, list);
      continue;
    }
    const atAnchor =
      unplannedByAnchor.get(cursor) ??
      new Map<string, PipelineAttempt[]>();
    const unplannedList = atAnchor.get(execution.node_id) ?? [];
    unplannedList.push(attempt);
    atAnchor.set(execution.node_id, unplannedList);
    unplannedByAnchor.set(cursor, atAnchor);
  }
 
  const reachedIndex = Math.max(
    -1,
    ...Array.from(attemptsByStage.keys()),
  );
  const bypassed = bypassedNodes(planned, executions);
 
  const stages: PipelineStage[] = [];
  const usedIds = new Set<string>();
 
  const pushUnplanned = (anchor: number) => {
    for (const [nodeId, attempts] of unplannedByAnchor.get(anchor) ?? []) {
      // The same unplanned node can land at two anchors — traces persisted
      // before svc-core merged svc-ai's rule enforcement carry a second
      // policy node after the answer. The id is a React key and a scroll
      // target, so the later one is told apart by where it landed.
      const baseId = `node:${nodeId}`;
      const id = usedIds.has(baseId) ? `${baseId}@${anchor}` : baseId;
      usedIds.add(id);
      stages.push({
        id,
        node_ids: [nodeId],
        is_system_stage: isSystemNodeId(nodeId),
        optional: true,
        state: stageStateFromAttempts(attempts) ?? "pending",
        attempts,
        unplanned: true,
      });
    }
  };
 
  pushUnplanned(-1);
  planned.forEach((stage, i) => {
    const attempts = attemptsByStage.get(i) ?? [];
    const shape = { fork: stage.fork, join: stage.join, attempts };
    const observed = isParallelStage(stage)
      ? parallelStageState(shape)
      : stageStateFromAttempts(attempts);
    let state: StageState;
    if (observed) {
      state = observed;
    } else if (
      finished ||
      i < reachedIndex ||
      stage.node_ids.every((nodeId) => bypassed.has(nodeId))
    ) {
      state = "skipped";
    } else {
      state = "pending";
    }
    stages.push({
      id: stage.id,
      node_ids: stage.node_ids,
      is_system_stage: stage.is_system_stage,
      optional: stage.optional,
      state,
      attempts,
      unplanned: false,
      ...(stage.fork ? { fork: stage.fork } : {}),
      ...(stage.branches ? { branches: stage.branches } : {}),
      ...(stage.join ? { join: stage.join } : {}),
    });
    pushUnplanned(i);
  });
 
  return stages;
}
 
/** Extracts the plan from a persisted trace, if it carried one. */
export function planFromTrace(
  trace: TraceEvent[],
): GraphPlanStage[] | undefined {
  const frame = trace.find((ev) => ev.type === "graph_plan");
  return frame?.stages && frame.stages.length > 0 ? frame.stages : undefined;
}
 
/** Every time this stage stopped for a person, in order. */
export function stageHitl(stage: PipelineStage): NodeHitl[] {
  return stage.attempts.flatMap((a) =>
    a.execution.hitl ? [a.execution.hitl] : [],
  );
}