// Composition comparison — two archived runs side by side. // // This answers the cross-composition question ("A vs B, what actually // differs and what did it buy me?") that single-run cards cannot: // * configuration diff — which node params differ between the two // graphs (computed structurally, not by node id); // * step-by-step alignment with each side's transformation // signature and headline metric; // * fidelity deltas as INTERVALS, not scalars — when both sides // carry a sampled distribution the two Wilson CIs render on one // 0-1 scale, and overlap is called out, because "0.462 < 0.475" // is not evidence when both intervals span the difference. import { useEffect, useState } from "react"; import { Presentation, X } from "lucide-react"; import type { StepResult } from "../lib/api"; import { useApp } from "../lib/store"; import { getRun, type RunRecord } from "../lib/runStore"; import { SignatureGlyph, transformationOf } from "./TransformationSignature"; import { DifferenceFunnel, useDifferenceEvidence } from "./DifferenceFunnel"; function sigText(step: StepResult | undefined): string { const t = transformationOf(step); if (!t || !t.changed) return "·"; const parts: string[] = []; const d = t.delta; if (d.depth) parts.push(`D${d.depth > 0 ? "+" : ""}${d.depth}`); if (d.size) parts.push(`G${d.size > 0 ? "+" : ""}${d.size}`); if (d.num_parameters) parts.push(`P${d.num_parameters > 0 ? "+" : ""}${d.num_parameters}`); if (d.num_qubits) parts.push(`Q${d.num_qubits > 0 ? "+" : ""}${d.num_qubits}`); return parts.join(" ") || "·"; } /** Table cell: the shared delta-strip glyph, one per side per step. * Rendering the strip even for pass-through steps (all faint ticks) * keeps every row the same shape, so scanning a column reads as * aligned small multiples; sigText survives as the hover tooltip * carrying the exact numbers. Steps with no circuit in scope at all * fall back to the old middot. */ function SigCell({ step }: { step: StepResult | undefined }) { const t = transformationOf(step); if (!t) return ·; return ( ); } interface StepPair { a: StepResult | undefined; b: StepResult | undefined; } /** Chip timestamp: time-only for today's runs, date + time otherwise * (audit S3 — cross-day pairs looked minutes apart). */ function fmtWhen(t: number): string { const d = new Date(t); if (d.toDateString() === new Date().toDateString()) return d.toLocaleTimeString(); return `${d.toLocaleDateString()} ${d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}`; } /** One aligned step row. `divergence` marks the first row where the * two compositions part ways — accent left border + tiny label, so * the eye lands exactly where the evidence starts. */ function CompareRow({ pair, divergence = false, }: { pair: StepPair; divergence?: boolean; }) { const { a, b } = pair; return ( {a?.label ?? b?.label ?? "—"} {a && b && a.node_type !== b.node_type && ( ≠ )} {divergence && ( divergence point )} {a?.status ?? "—"} / {b?.status ?? "—"} ); } /** Does the record carry at least one sampled per-batch trace? The * theater overlay needs the funnel data, not just a final interval. */ function hasSampledTrace(r: RunRecord): boolean { return r.response.steps.some((st) => { const d = st.distribution as | { kind?: string; trace?: unknown[] } | null | undefined; return d?.kind === "binomial" && Array.isArray(d.trace) && d.trace.length > 0; }); } function fidelityStep(r: RunRecord): StepResult | undefined { for (let i = r.response.steps.length - 1; i >= 0; i--) { const s = r.response.steps[i]; if (s.node_type === "fidelity" && s.status === "ok") return s; } return undefined; } /** Structural param diff between the two graphs: nodes are matched by * (kind, occurrence index in a canonically sorted list), the same * convention configHash uses, so layout and node ids don't matter. */ function paramDiff(a: RunRecord, b: RunRecord): Array<{ where: string; left: string; right: string }> { const canon = (r: RunRecord) => [...r.graph.n] .map((n) => ({ kind: n.k, params: n.p ?? {} })) .sort((x, y) => { const kx = `${x.kind}|${JSON.stringify(x.params)}`; const ky = `${y.kind}|${JSON.stringify(y.params)}`; return kx < ky ? -1 : kx > ky ? 1 : 0; }); const A = canon(a); const B = canon(b); const out: Array<{ where: string; left: string; right: string }> = []; const byKind = (list: typeof A) => { const m = new Map>>(); list.forEach((n) => { const arr = m.get(n.kind) ?? []; arr.push(n.params); m.set(n.kind, arr); }); return m; }; const mA = byKind(A); const mB = byKind(B); const kinds = new Set([...mA.keys(), ...mB.keys()]); kinds.forEach((kind) => { const la = mA.get(kind) ?? []; const lb = mB.get(kind) ?? []; const n = Math.max(la.length, lb.length); for (let i = 0; i < n; i++) { const pa = la[i]; const pb = lb[i]; if (pa === undefined || pb === undefined) { out.push({ where: kind, left: pa === undefined ? "(absent)" : "(present)", right: pb === undefined ? "(absent)" : "(present)", }); continue; } const keys = new Set([...Object.keys(pa), ...Object.keys(pb)]); keys.forEach((k) => { const va = JSON.stringify(pa[k] ?? null); const vb = JSON.stringify(pb[k] ?? null); if (va !== vb) out.push({ where: `${kind}.${k}`, left: va, right: vb }); }); } }); if (a.sample_key !== b.sample_key) { out.unshift({ where: "circuit", left: a.sample_key ?? a.circuit_name ?? "upload", right: b.sample_key ?? b.circuit_name ?? "upload", }); } return out; } function ciOf(s: StepResult | undefined): [number, number] | null { const d = s?.distribution as { ci95?: [number, number] } | null | undefined; return d?.ci95 ?? null; } export function CompareView() { const compareIds = useApp((s) => s.compareIds); const clearCompare = useApp((s) => s.clearCompare); const setTheaterOverlay = useApp((s) => s.setTheaterOverlay); // historyVersion: a selected run can be DELETED from the archive // while it is being compared. The bump re-runs the lookup below, and // the missing-record branch clears the stale pair — without this the // view kept rendering the deleted run's data. const historyVersion = useApp((s) => s.historyVersion); const [recs, setRecs] = useState<[RunRecord, RunRecord] | null>(null); // Distinguishes "lookup in flight" (render nothing, brief) from // "records gone" (render an honest explanation — audit S2: a null // return here left the Compare tab silently blank after Clear demo // data / delete). const [missing, setMissing] = useState(false); useEffect(() => { if (compareIds.length !== 2) { setRecs(null); setMissing(false); return; } let cancelled = false; Promise.all([getRun(compareIds[0]), getRun(compareIds[1])]) .then(([a, b]) => { if (cancelled) return; // Either record gone (deleted / IndexedDB hiccup) → say so // rather than rendering a stale or half pair. if (a && b) { setRecs([a, b]); setMissing(false); } else { setRecs(null); setMissing(true); } }) .catch(() => { if (!cancelled) { setRecs(null); setMissing(true); } }); return () => { cancelled = true; }; }, [compareIds, historyVersion]); // Difference-funnel data (marker: difference-funnel) — fetched via // the hook here rather than inside the funnel component, so the // verdict wording below can defer to the funnel exactly when the // funnel will actually render. const diffData = useDifferenceEvidence(recs?.[0] ?? null, recs?.[1] ?? null); if (compareIds.length !== 2) return null; if (!recs) { if (!missing) return null; // lookup in flight — resolves in ms return (
Comparing two runs

The selected runs are no longer archived — they were deleted or removed with the demo data. Tick two runs in the{" "} “This configuration” tab to start a new comparison.

); } const [A, B] = recs; const diffs = paramDiff(A, B); const fa = fidelityStep(A); const fb = fidelityStep(B); const va = A.headline_value; const vb = B.headline_value; const ciA = ciOf(fa); const ciB = ciOf(fb); const overlap = ciA && ciB ? Math.max(0, Math.min(ciA[1], ciB[1]) - Math.max(ciA[0], ciB[0])) > 0 : null; const n = Math.max(A.response.steps.length, B.response.steps.length); const rows: StepPair[] = Array.from({ length: n }, (_, i) => ({ a: A.response.steps[i], b: B.response.steps[i], })); // ---- shared-prefix folding ------------------------------------- // The analytical question a comparison answers is "where do these // compositions part ways, and what did it cost?" Leading steps that // are identical on both sides carry no part of that answer — they // only push the divergence point (where the evidence lives) below // the fold. A leading row folds when (1) both sides run the same // node kind, (2) the structural param diff above found nothing for // that kind, and (3) both sides' transformation signatures report // the same delta. Such rows collapse into one expandable "shared // prefix" row; the first row that breaks any condition is the // divergence point and gets an accent marker. const diffTouchesKind = (kind: string): boolean => diffs.some( (d) => d.where === kind || d.where.startsWith(`${kind}.`) || // the circuit-level diff is reported as `where: "circuit"` // but structurally belongs to the input step (d.where === "circuit" && kind === "input_circuit"), ); const sameSignature = (x?: StepResult, y?: StepResult): boolean => { const sx = transformationOf(x); const sy = transformationOf(y); if (!sx && !sy) return true; // both signature-less (analysis-only steps) if (!sx || !sy) return false; return (["depth", "size", "num_parameters", "num_qubits"] as const).every( (k) => sx.delta[k] === sy.delta[k], ); }; let prefixLen = 0; while (prefixLen < rows.length) { const { a, b } = rows[prefixLen]; if (!a || !b || a.node_type !== b.node_type) break; if (diffTouchesKind(a.node_type)) break; if (!sameSignature(a, b)) break; prefixLen++; } // Marker before fold decision (audit S3): zeroing prefixLen for // fold economy also erased the divergence marker whenever the // shared prefix was a single row. const divergenceIdx = prefixLen > 0 && prefixLen < rows.length ? prefixLen : -1; if (prefixLen < 2) prefixLen = 0; // folding a single row saves nothing return (
{/* flex-wrap: the verdict chip alone (~230px) plus the A/B time chips exceed a narrow Evidence pane / mobile drawer; without wrapping the ml-auto close button was pushed out of the overflow-x-hidden aside. */}
Comparing two runs {/* Date shown whenever a run is not from today (audit S3): bare times made "14:02 vs 14:07" from different days read as five minutes apart. Full timestamp in the tooltip. */} A · {fmtWhen(A.created_at)} B · {fmtWhen(B.created_at)} {A.config_hash === B.config_hash ? ( same configuration — differences are noise ) : ( {diffs.length} setting{diffs.length === 1 ? "" : "s"} differ )} {/* Theater overlay (marker: theater-overlay): only offered when the pair is genuinely overlayable — same configuration (so "one rule, two draws" is a true statement) AND both runs persisted a per-batch trace (the funnel data). */} {A.config_hash === B.config_hash && hasSampledTrace(A) && hasSampledTrace(B) && ( )}
{diffs.length > 0 && (
{diffs.slice(0, 8).map((d, i) => (
{d.where} {d.left} → {d.right}
))} {diffs.length > 8 && (
…and {diffs.length - 8} more
)}
)} {/* Fidelity: intervals, not scalars */} {va != null && vb != null && (
fidelity
{ciA && (
)} {/* 2px marks are unhoverable — a transparent 10px-wide wrapper carries the tooltip (audit S3); the values are also spelled out in the readout line below. */}
{ciB && (
)}
A {(va * 100).toFixed(2)}% · B {(vb * 100).toFixed(2)}% · Δ(B−A){" "} {((vb - va) * 100).toFixed(2)}pp {/* When the difference funnel renders, IT owns the verdict: the two bars above compare only the two selected runs, while the funnel pools every archived replicate and puts one interval on the difference itself. The overlap wording survives only when the funnel cannot render. */} {diffData?.status === "ready" ? ( — see the difference funnel below: the honest verdict accumulates across all archived replicates ) : ( <> {overlap === true && ( — intervals overlap: not evidence )} {overlap === false && ( — intervals separated )} )}
)} {/* Difference funnel (marker: difference-funnel): the 95% interval of Δ(B−A) narrowing as replicates of BOTH configurations accumulate — the sequential A/B instrument. Renders below the two-run interval bars; null for same-config pairs (the theater overlay owns those). */} {/* step-by-step */} {prefixLen > 0 && ( )} {rows.slice(prefixLen).map((pair, i) => ( ))}
step A sig B sig A / B status
shared prefix · {prefixLen} steps (identical kind, params and signature on both sides) {rows.slice(0, prefixLen).map((pair, i) => ( ))}
); }