File size: 13,256 Bytes
ea5983b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa87757
 
ea5983b
 
 
 
 
 
 
 
 
74b7708
 
 
 
 
 
 
ea5983b
5c58e08
ea5983b
 
 
 
 
 
 
 
 
 
 
 
5c58e08
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2316315
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea5983b
 
 
 
 
 
 
728039f
 
 
 
ea5983b
 
 
 
 
 
 
 
 
 
 
 
74b7708
ea5983b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74b7708
ea5983b
 
74b7708
 
 
ea5983b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2316315
ea5983b
 
 
 
 
2316315
 
 
ea5983b
 
 
 
 
 
 
2316315
 
 
 
 
 
 
 
 
 
 
 
 
ea5983b
2316315
 
 
 
 
 
 
 
 
 
 
 
 
ea5983b
 
 
 
 
2316315
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea5983b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4f6e441
 
 
 
 
 
 
fa87757
2316315
 
 
 
 
 
ea5983b
 
 
 
74b7708
 
4f6e441
2316315
 
 
ea5983b
 
 
 
 
4f6e441
 
 
ceee520
4f6e441
 
 
 
 
 
 
 
 
ea5983b
 
 
728039f
 
 
 
 
 
 
 
 
 
 
 
 
ea5983b
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
// One-click pipeline wiring: turn a pile of dropped blocks into a
// sensible main chain without the user having to know which family
// connects to which.
//
// Strategy
// --------
// Every node kind carries a `family` tag in nodeCatalog.ts: one of
// `source`, `backend`, `algorithm`, `metric`, `sink`. The research
// workflow these blocks mirror is always the same canonical sequence:
//
//     source → backend → algorithm(s) → metric(s) → sink
//
// `autoConnect` groups the nodes on the canvas by that family, sorts
// each group by x-position (so the user can hint at intra-family order
// by dragging blocks left-to-right), flattens the groups in canonical
// order, and strings the result into a single main chain.
//
// Deliberate design choices:
//
// * **The result completely replaces the existing edges.** Calling
//   Auto-connect is "I want sensible wiring", not "patch my wiring".
//   Users with hand-drawn edges they want to keep simply don't press
//   the button.
// * **Edge semantics are just execution order.** The backend runs Kahn
//   topological sort over the graph and shares state via a single ctx
//   dict; there's no such thing as a "data" vs "side-channel" edge.
//   So a single flat chain is sufficient — no need to model
//   "backend → algorithm" as a separate noise-profile branch.
// * **We never produce a cycle.** Family order is a strict total
//   order, so edges always point down the order and the graph stays a
//   DAG.
// * **Warnings are advisory.** We still return a chain even if, say,
//   there's no Input circuit — the user can inspect what we'd link
//   and fix up from there.

import type { Edge, Node } from "@xyflow/react";
import type { QNodeData } from "../components/QNode";
import {
  NODE_BY_KIND,
  resolveNodeSpec,
  type NodeKind,
  type NodeSpec,
} from "./nodeCatalog";
import type { PluginManifest } from "./api";

export type Family = NodeSpec["family"];

// Canonical execution order of the pipeline families. Keep this list
// stable: the Auto-connect algorithm and the visual left-to-right layout
// in `buildPresetGraph` both assume this ordering.
const FAMILY_ORDER: Family[] = [
  "source",
  "backend",
  "algorithm",
  "metric",
  "sink",
];

/**
 * Which families may legally FOLLOW a block of `family` in a chain —
 * the grammar the canvas insert menu (marker canvas-insert-menu)
 * filters by. Derived from how autoConnect itself builds chains, not
 * from taste:
 *
 *   - The flatten step strings the non-empty family buckets together
 *     in FAMILY_ORDER, so any LATER family can be the direct
 *     successor when the buckets between are empty (source → sink is
 *     a legal, if spartan, chain).
 *   - Same-family succession is family-specific. algorithm →
 *     algorithm is the normal way to stack transforms (multiple
 *     algorithms chain in x-order with no warning), and metric →
 *     metric just measures more than one thing. source → source and
 *     backend → backend DO occur in a flattened chain, but they are
 *     exactly the shapes autoConnect's advisory warnings flag
 *     ("duplicate summary rows" / "only the rightmost one is used") —
 *     an insert menu must not OFFER to build a warned-about shape.
 *   - sink is terminal: nothing follows the evidence collector. The
 *     follow set is empty and callers skip the menu entirely.
 */
export function nextFamilies(family: Family): Family[] {
  const later = FAMILY_ORDER.slice(FAMILY_ORDER.indexOf(family) + 1);
  return family === "algorithm" || family === "metric"
    ? [family, ...later]
    : later;
}

// Per-algorithm dependency on an upstream backend, derived from the
// runtime handlers in backend/app/services/workflow_service.py. Three
// possible relationships:
//
//   - "required":   handler hard-errors without ctx["backend"]
//                   (currently only QuCAD).
//   - "optional":   handler silently falls back to FakeFez when no
//                   backend is connected (QuBound, CompressVQC).
//   - "ignored":    handler is self-contained and ignores ctx["backend"]
//                   even if one is wired (Qshot — uses its own bundled
//                   noise snapshots).
//
// Keeping this here means Auto-connect's warnings can be specific
// instead of issuing a one-size-fits-all "algorithms that need a noise
// model will error" line that's wrong for everything except QuCAD.
const ALGO_BACKEND_DEPENDENCY: Record<NodeKind, "required" | "optional" | "ignored" | undefined> = {
  qucad: "required",
  qubound: "optional",
  compvqc: "optional",
  qshot: "ignored",
  // Non-algorithm kinds: undefined (irrelevant to backend dependency).
  input_circuit: undefined,
  ibm_backend: undefined,
  fake_backend: undefined,
  fidelity: undefined,
  output: undefined,
};

export interface AutoConnectResult {
  /** New edge array to replace the current one (empty if nothing to do). */
  edges: Edge[];
  /** Human-readable advisory messages (missing/duplicate families). */
  warnings: string[];
  /** `true` when at least one edge was produced. */
  connected: boolean;
  /** Number of pre-existing edges this result actually REWIRES —
   *  edges whose (source, target) pair survives verbatim don't count
   *  (audit S3: re-running Auto-connect on an already-canonical chain
   *  used to claim it replaced everything). */
  replacedCount: number;
}

/**
 * Compute the auto-connected edge set for the current canvas.
 *
 * Pure function: does not mutate the inputs and has no side effects.
 * Callers typically do `setEdges(result.edges)` on `result.connected`.
 */
export function autoConnect(
  nodes: Node<QNodeData>[],
  existingEdges: Edge[],
  plugins: PluginManifest[] = [],
): AutoConnectResult {
  const warnings: string[] = [];
  const replacedCount = existingEdges.length;

  // ---- degenerate inputs ----
  if (nodes.length === 0) {
    return {
      edges: [],
      warnings: ["Drop some blocks on the canvas first."],
      connected: false,
      replacedCount,
    };
  }
  if (nodes.length === 1) {
    return {
      edges: [],
      warnings: ["Only one block on the canvas — nothing to connect."],
      connected: false,
      replacedCount,
    };
  }

  // ---- bucket by family ----
  const buckets: Record<Family, Node<QNodeData>[]> = {
    source: [],
    backend: [],
    algorithm: [],
    metric: [],
    sink: [],
  };
  const unknown: Node<QNodeData>[] = [];
  for (const n of nodes) {
    const spec = resolveNodeSpec(n.data.kind, plugins);
    if (!spec) {
      // Forward-compat: unrecognised kinds (e.g. a node kind added in a
      // newer build loaded via a stale share link, or a plugin missing
      // from this browser) are preserved on the canvas but left out of
      // the chain rather than silently dropped.
      unknown.push(n);
      continue;
    }
    buckets[spec.family].push(n);
  }
  if (unknown.length > 0) {
    warnings.push(
      `${unknown.length} block${unknown.length > 1 ? "s" : ""} with unknown kind were skipped.`,
    );
  }

  // ---- sort each bucket left-to-right, id as deterministic tiebreaker ----
  for (const fam of FAMILY_ORDER) {
    buckets[fam].sort((a, b) => {
      const dx = (a.position?.x ?? 0) - (b.position?.x ?? 0);
      if (dx !== 0) return dx;
      return a.id.localeCompare(b.id);
    });
  }

  // ---- advisory warnings about the composition ----
  //
  // Semantics rest on three facts about the runner in workflow_service.py:
  //   (1) Every backend handler writes `ctx["backend"] = backend`, so a
  //       later backend node wipes an earlier one — "last wins".
  //   (2) Input-circuit handlers only emit a summary step, they don't
  //       replace `ctx["circuit"]`. So extra Input nodes are merely
  //       redundant (duplicate summary rows), not actively wrong.
  //   (3) Algorithms differ on whether they need a backend — see
  //       ALGO_BACKEND_DEPENDENCY above. Auto-connect warns specifically
  //       per algorithm rather than issuing a blanket "no backend" line.
  if (buckets.source.length === 0) {
    warnings.push("No Input circuit — pipeline has no clear starting point.");
  } else if (buckets.source.length > 1) {
    warnings.push(
      `${buckets.source.length} Input circuits — extras produce duplicate summary rows.`,
    );
  }

  // Backend-dependency warnings, one per offending algorithm. We split
  // them so the user sees concrete consequences ("QuCAD will error",
  // "QuBound will fall back to FakeFez") instead of a single vague
  // bullet.
  const hasBackend = buckets.backend.length > 0;
  const algoKinds = buckets.algorithm.map((n) => n.data.kind);
  if (!hasBackend) {
    const requiredKinds = algoKinds.filter(
      (k) => ALGO_BACKEND_DEPENDENCY[k] === "required",
    );
    const optionalKinds = algoKinds.filter(
      (k) => ALGO_BACKEND_DEPENDENCY[k] === "optional",
    );
    for (const k of requiredKinds) {
      warnings.push(
        `${NODE_BY_KIND[k].label} requires a backend node upstream and will error at run time.`,
      );
    }
    if (optionalKinds.length > 0) {
      const labels = optionalKinds
        .map((k) => NODE_BY_KIND[k].label)
        .join(" and ");
      warnings.push(
        `${labels} will fall back to FakeFez since no backend is connected.`,
      );
    }
  } else if (buckets.backend.length > 1) {
    warnings.push(
      `${buckets.backend.length} backends linked in series — only the rightmost one is used downstream.`,
    );
  }

  // Self-contained algorithms (Qshot) ignore upstream backends. If the
  // user wired a backend in front of a chain that contains only
  // self-contained algorithms, that backend node is dead weight —
  // worth flagging so the user doesn't expect it to influence the
  // result.
  if (
    hasBackend &&
    algoKinds.length > 0 &&
    algoKinds.every((k) => ALGO_BACKEND_DEPENDENCY[k] === "ignored")
  ) {
    const ignoredLabels = Array.from(new Set(algoKinds))
      .map((k) => NODE_BY_KIND[k].label)
      .join(" / ");
    warnings.push(
      `${ignoredLabels} is self-contained — the backend node will be ignored at run time.`,
    );
  }

  if (buckets.sink.length === 0) {
    warnings.push("No Output block — final metrics will not be aggregated.");
  }

  // ---- flatten in family order ----
  const chain: Node<QNodeData>[] = [];
  for (const fam of FAMILY_ORDER) chain.push(...buckets[fam]);

  // Shouldn't happen given len >= 2 and at most a handful of unknowns,
  // but defensively: if the chain collapses to fewer than 2 eligible
  // nodes, there's nothing to wire.
  if (chain.length < 2) {
    return {
      edges: [],
      warnings: warnings.length > 0 ? warnings : ["Nothing eligible to connect."],
      connected: false,
      replacedCount,
    };
  }

  // ---- string into a single main chain ----
  //
  // Most edges represent the actual data flow (circuit / metrics moving
  // downstream). The one exception is backend → algorithm: the backend
  // node doesn't hand a circuit to the algorithm, it seeds `ctx["backend"]`
  // so the algorithm can read the noise model. That's a side-channel, not
  // a pipeline step. Mark it visually with a dashed stroke + small label
  // so readers of the graph can tell "this block feeds calibration data,
  // not a transformed circuit" at a glance.
  //
  // Exception: Qshot (kind === "qshot") is self-contained and ignores
  // ctx["backend"] entirely. Putting a "noise profile" label on a
  // backend → qshot edge would be a lie. We still draw the edge so the
  // chain stays visually connected (and Auto-connect emits the "Qshot
  // is self-contained" warning above), but with a plain undashed style.
  const edges: Edge[] = [];
  for (let i = 0; i < chain.length - 1; i++) {
    const src = chain[i];
    const dst = chain[i + 1];
    const srcFamily = resolveNodeSpec(src.data.kind, plugins)?.family;
    const dstFamily = resolveNodeSpec(dst.data.kind, plugins)?.family;
    const isNoiseSidechain =
      srcFamily === "backend" &&
      dstFamily === "algorithm" &&
      ALGO_BACKEND_DEPENDENCY[dst.data.kind] !== "ignored";
    edges.push({
      id: `auto-${src.id}-${dst.id}`,
      source: src.id,
      target: dst.id,
      animated: true,
      ...(isNoiseSidechain && {
        label: "noise profile",
        // SVG `fill` accepts `rgb(var(--name))` so the label + background
        // follow the active theme (dark / light) automatically.
        labelStyle: { fontSize: 10, fill: "rgb(var(--color-mute))" },
        labelBgStyle: {
          fill: "rgb(var(--color-surface))",
          fillOpacity: 0.92,
        },
        labelBgPadding: [6, 3] as [number, number],
        labelBgBorderRadius: 3,
        style: { strokeDasharray: "4 3" },
      }),
    });
  }

  // Identity is the (source, target) pair — edge ids and styling are
  // cosmetic, so a rewire that reproduces the same pair replaced
  // nothing the user would recognise as a change.
  const newPairs = new Set(edges.map((e) => `${e.source}>${e.target}`));
  const actuallyReplaced = existingEdges.filter(
    (e) => !newPairs.has(`${e.source}>${e.target}`),
  ).length;
  return {
    edges,
    warnings,
    connected: true,
    replacedCount: actuallyReplaced,
  };
}